blob: 0424c43b9822f48ccef03dae64f5cdab3a411a50 [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 {
639 for (const auto &I : S)
640 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 {
648 for (const auto &I : S)
649 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
1094 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1095
1096 Code += PredicateCode;
1097
1098 if (PredicateCode.empty() && !Code.empty())
1099 Code += "return true;\n";
1100
1101 return Code;
Chris Lattner514e2922011-04-17 21:38:24 +00001102}
1103
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001104bool TreePredicateFn::hasImmCode() const {
1105 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1106}
1107
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001108std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesendd8fbf52012-01-13 03:38:34 +00001109 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001110}
1111
Daniel Sanders649c5852017-10-13 20:42:18 +00001112bool TreePredicateFn::immCodeUsesAPInt() const {
1113 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1114}
1115
1116bool TreePredicateFn::immCodeUsesAPFloat() const {
1117 bool Unset;
1118 // The return value will be false when IsAPFloat is unset.
1119 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1120 Unset);
1121}
1122
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001123bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1124 bool Value) const {
1125 bool Unset;
1126 bool Result =
1127 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1128 if (Unset)
1129 return false;
1130 return Result == Value;
1131}
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001132bool TreePredicateFn::usesOperands() const {
1133 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1134}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001135bool TreePredicateFn::isLoad() const {
1136 return isPredefinedPredicateEqualTo("IsLoad", true);
1137}
1138bool TreePredicateFn::isStore() const {
1139 return isPredefinedPredicateEqualTo("IsStore", true);
1140}
Daniel Sanders87d196c2017-11-13 22:26:13 +00001141bool TreePredicateFn::isAtomic() const {
1142 return isPredefinedPredicateEqualTo("IsAtomic", true);
1143}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001144bool TreePredicateFn::isUnindexed() const {
1145 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1146}
1147bool TreePredicateFn::isNonExtLoad() const {
1148 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1149}
1150bool TreePredicateFn::isAnyExtLoad() const {
1151 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1152}
1153bool TreePredicateFn::isSignExtLoad() const {
1154 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1155}
1156bool TreePredicateFn::isZeroExtLoad() const {
1157 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1158}
1159bool TreePredicateFn::isNonTruncStore() const {
1160 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1161}
1162bool TreePredicateFn::isTruncStore() const {
1163 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1164}
Daniel Sanders6d9d30a2017-11-13 23:03:47 +00001165bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1166 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1167}
1168bool TreePredicateFn::isAtomicOrderingAcquire() const {
1169 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1170}
1171bool TreePredicateFn::isAtomicOrderingRelease() const {
1172 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1173}
1174bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1175 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1176}
1177bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1178 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1179 true);
1180}
Daniel Sanders0c43b3a2017-11-30 21:05:59 +00001181bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1182 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1183}
1184bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1185 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1186}
1187bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1188 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1189}
1190bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1191 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1192}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001193Record *TreePredicateFn::getMemoryVT() const {
1194 Record *R = getOrigPatFragRecord()->getRecord();
1195 if (R->isValueUnset("MemoryVT"))
1196 return nullptr;
1197 return R->getValueAsDef("MemoryVT");
1198}
Matt Arsenaultd00d8572019-07-15 20:59:42 +00001199
1200ListInit *TreePredicateFn::getAddressSpaces() const {
1201 Record *R = getOrigPatFragRecord()->getRecord();
1202 if (R->isValueUnset("AddressSpaces"))
1203 return nullptr;
1204 return R->getValueAsListInit("AddressSpaces");
1205}
1206
Matt Arsenault52c26242019-07-31 00:14:43 +00001207int64_t TreePredicateFn::getMinAlignment() const {
1208 Record *R = getOrigPatFragRecord()->getRecord();
1209 if (R->isValueUnset("MinAlignment"))
1210 return 0;
1211 return R->getValueAsInt("MinAlignment");
1212}
1213
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001214Record *TreePredicateFn::getScalarMemoryVT() const {
1215 Record *R = getOrigPatFragRecord()->getRecord();
1216 if (R->isValueUnset("ScalarMemoryVT"))
1217 return nullptr;
1218 return R->getValueAsDef("ScalarMemoryVT");
1219}
Daniel Sanders8ead1292018-06-15 23:13:43 +00001220bool TreePredicateFn::hasGISelPredicateCode() const {
1221 return !PatFragRec->getRecord()
1222 ->getValueAsString("GISelPredicateCode")
1223 .empty();
1224}
1225std::string TreePredicateFn::getGISelPredicateCode() const {
1226 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1227}
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001228
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001229StringRef TreePredicateFn::getImmType() const {
Daniel Sanders649c5852017-10-13 20:42:18 +00001230 if (immCodeUsesAPInt())
1231 return "const APInt &";
1232 if (immCodeUsesAPFloat())
1233 return "const APFloat &";
1234 return "int64_t";
1235}
Chris Lattner514e2922011-04-17 21:38:24 +00001236
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001237StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders11300ce2017-10-13 21:28:03 +00001238 if (immCodeUsesAPInt())
1239 return "APInt";
1240 else if (immCodeUsesAPFloat())
1241 return "APFloat";
1242 return "I64";
1243}
1244
Chris Lattner514e2922011-04-17 21:38:24 +00001245/// isAlwaysTrue - Return true if this is a noop predicate.
1246bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001247 return !hasPredCode() && !hasImmCode();
Chris Lattner514e2922011-04-17 21:38:24 +00001248}
1249
1250/// Return the name to use in the generated code to reference this, this is
1251/// "Predicate_foo" if from a pattern fragment "foo".
1252std::string TreePredicateFn::getFnName() const {
Matthias Braun4a86d452016-12-04 05:48:16 +00001253 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner514e2922011-04-17 21:38:24 +00001254}
1255
1256/// getCodeToRunOnSDNode - Return the code for the function body that
1257/// evaluates this predicate. The argument is expected to be in "Node",
1258/// not N. This handles casting and conversion to a concrete node type as
1259/// appropriate.
1260std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001261 // Handle immediate predicates first.
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001262 std::string ImmCode = getImmCode();
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001263 if (!ImmCode.empty()) {
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001264 if (isLoad())
1265 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1266 "IsLoad cannot be used with ImmLeaf or its subclasses");
1267 if (isStore())
1268 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1269 "IsStore cannot be used with ImmLeaf or its subclasses");
1270 if (isUnindexed())
1271 PrintFatalError(
1272 getOrigPatFragRecord()->getRecord()->getLoc(),
1273 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1274 if (isNonExtLoad())
1275 PrintFatalError(
1276 getOrigPatFragRecord()->getRecord()->getLoc(),
1277 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1278 if (isAnyExtLoad())
1279 PrintFatalError(
1280 getOrigPatFragRecord()->getRecord()->getLoc(),
1281 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1282 if (isSignExtLoad())
1283 PrintFatalError(
1284 getOrigPatFragRecord()->getRecord()->getLoc(),
1285 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1286 if (isZeroExtLoad())
1287 PrintFatalError(
1288 getOrigPatFragRecord()->getRecord()->getLoc(),
1289 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1290 if (isNonTruncStore())
1291 PrintFatalError(
1292 getOrigPatFragRecord()->getRecord()->getLoc(),
1293 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1294 if (isTruncStore())
1295 PrintFatalError(
1296 getOrigPatFragRecord()->getRecord()->getLoc(),
1297 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1298 if (getMemoryVT())
1299 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1300 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1301 if (getScalarMemoryVT())
1302 PrintFatalError(
1303 getOrigPatFragRecord()->getRecord()->getLoc(),
1304 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1305
1306 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders649c5852017-10-13 20:42:18 +00001307 if (immCodeUsesAPFloat())
1308 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1309 else if (immCodeUsesAPInt())
1310 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1311 else
1312 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders3f267bf2017-10-15 02:06:44 +00001313 return Result + ImmCode;
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001314 }
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001315
Chris Lattner2ff8c1a2011-04-17 22:05:17 +00001316 // Handle arbitrary node predicates.
Daniel Sandersadbf58d2017-10-15 19:01:32 +00001317 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001318 StringRef ClassName;
Chris Lattner514e2922011-04-17 21:38:24 +00001319 if (PatFragRec->getOnlyTree()->isLeaf())
1320 ClassName = "SDNode";
1321 else {
1322 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1323 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1324 }
1325 std::string Result;
1326 if (ClassName == "SDNode")
1327 Result = " SDNode *N = Node;\n";
1328 else
Simon Pilgrim6ecae9f2017-10-14 21:27:53 +00001329 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim8c4d0612017-09-22 16:57:28 +00001330
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001331 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
Scott Michel94420742008-03-05 17:49:05 +00001332}
1333
Chris Lattner8cab0212008-01-05 22:25:12 +00001334//===----------------------------------------------------------------------===//
Dan Gohman49e19e92008-08-22 00:20:26 +00001335// PatternToMatch implementation
1336//
1337
Craig Topper1a872f22019-03-10 05:21:52 +00001338static bool isImmAllOnesAllZerosMatch(const TreePatternNode *P) {
1339 if (!P->isLeaf())
1340 return false;
1341 DefInit *DI = dyn_cast<DefInit>(P->getLeafValue());
1342 if (!DI)
1343 return false;
1344
1345 Record *R = DI->getDef();
1346 return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1347}
1348
Chris Lattner05925fe2010-03-29 01:40:38 +00001349/// getPatternSize - Return the 'size' of this pattern. We want to match large
1350/// patterns before small ones. This is used to determine the size of a
1351/// pattern.
Florian Hahn6b1db822018-06-14 20:32:58 +00001352static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner05925fe2010-03-29 01:40:38 +00001353 const CodeGenDAGPatterns &CGP) {
1354 unsigned Size = 3; // The node itself.
1355 // If the root node is a ConstantSDNode, increases its size.
1356 // e.g. (set R32:$dst, 0).
Florian Hahn6b1db822018-06-14 20:32:58 +00001357 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001358 Size += 2;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001359
Florian Hahn6b1db822018-06-14 20:32:58 +00001360 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne32ab3a82016-11-09 23:53:43 +00001361 Size += AM->getComplexity();
Tim Northoverc807a172014-05-20 11:52:46 +00001362 // We don't want to count any children twice, so return early.
1363 return Size;
1364 }
1365
Chris Lattner05925fe2010-03-29 01:40:38 +00001366 // If this node has some predicate function that must match, it adds to the
1367 // complexity of this node.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001368 if (!P->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001369 ++Size;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001370
Chris Lattner05925fe2010-03-29 01:40:38 +00001371 // Count children in the count if they are also nodes.
Florian Hahn6b1db822018-06-14 20:32:58 +00001372 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1373 const TreePatternNode *Child = P->getChild(i);
1374 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrimc3c14412018-08-15 20:41:19 +00001375 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001376 // At this point, all variable type sets should be simple, i.e. only
1377 // have a default mode.
1378 if (T0.getMachineValueType() != MVT::Other) {
1379 Size += getPatternSize(Child, CGP);
1380 continue;
1381 }
1382 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001383 if (Child->isLeaf()) {
1384 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner05925fe2010-03-29 01:40:38 +00001385 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn6b1db822018-06-14 20:32:58 +00001386 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner05925fe2010-03-29 01:40:38 +00001387 Size += getPatternSize(Child, CGP);
Craig Topper1a872f22019-03-10 05:21:52 +00001388 else if (isImmAllOnesAllZerosMatch(Child))
1389 Size += 4; // Matches a build_vector(+3) and a predicate (+1).
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001390 else if (!Child->getPredicateCalls().empty())
Chris Lattner05925fe2010-03-29 01:40:38 +00001391 ++Size;
1392 }
1393 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001394
Chris Lattner05925fe2010-03-29 01:40:38 +00001395 return Size;
1396}
1397
1398/// Compute the complexity metric for the input pattern. This roughly
1399/// corresponds to the number of nodes that are covered.
Tom Stellard6655dd62014-08-01 00:32:36 +00001400int PatternToMatch::
Chris Lattner05925fe2010-03-29 01:40:38 +00001401getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001402 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner05925fe2010-03-29 01:40:38 +00001403}
1404
Dan Gohman49e19e92008-08-22 00:20:26 +00001405/// getPredicateCheck - Return a single string containing all of this
1406/// pattern's predicates concatenated with "&&" operators.
1407///
1408std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001409 SmallVector<const Predicate*,4> PredList;
Matt Arsenault57ef94f2019-07-30 15:56:43 +00001410 for (const Predicate &P : Predicates) {
1411 if (!P.getCondString().empty())
1412 PredList.push_back(&P);
1413 }
Benjamin Kramerd5aecb92019-08-22 17:31:59 +00001414 llvm::sort(PredList, deref<std::less<>>());
Craig Topper8985efe2015-11-27 05:44:04 +00001415
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001416 std::string Check;
1417 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1418 if (i != 0)
1419 Check += " && ";
1420 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper8985efe2015-11-27 05:44:04 +00001421 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001422 return Check;
Dan Gohman49e19e92008-08-22 00:20:26 +00001423}
1424
1425//===----------------------------------------------------------------------===//
Chris Lattner8cab0212008-01-05 22:25:12 +00001426// SDTypeConstraint implementation
1427//
1428
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001429SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001430 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001431
Chris Lattner8cab0212008-01-05 22:25:12 +00001432 if (R->isSubClassOf("SDTCisVT")) {
1433 ConstraintType = SDTCisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001434 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1435 for (const auto &P : VVT)
1436 if (P.second == MVT::isVoid)
1437 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner8cab0212008-01-05 22:25:12 +00001438 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1439 ConstraintType = SDTCisPtrTy;
1440 } else if (R->isSubClassOf("SDTCisInt")) {
1441 ConstraintType = SDTCisInt;
1442 } else if (R->isSubClassOf("SDTCisFP")) {
1443 ConstraintType = SDTCisFP;
Bob Wilsonf7e587f2009-08-12 22:30:59 +00001444 } else if (R->isSubClassOf("SDTCisVec")) {
1445 ConstraintType = SDTCisVec;
Chris Lattner8cab0212008-01-05 22:25:12 +00001446 } else if (R->isSubClassOf("SDTCisSameAs")) {
1447 ConstraintType = SDTCisSameAs;
1448 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1449 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1450 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001451 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001452 R->getValueAsInt("OtherOperandNum");
1453 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1454 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001455 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner8cab0212008-01-05 22:25:12 +00001456 R->getValueAsInt("BigOperandNum");
Nate Begeman17bedbc2008-02-09 01:37:05 +00001457 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1458 ConstraintType = SDTCisEltOfVec;
Chris Lattnercabe0372010-03-15 06:00:16 +00001459 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene127fd1d2011-01-24 20:53:18 +00001460 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1461 ConstraintType = SDTCisSubVecOfVec;
1462 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1463 R->getValueAsInt("OtherOpNum");
Craig Topper0be34582015-03-05 07:11:34 +00001464 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1465 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001466 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1467 for (const auto &P : VVT) {
1468 MVT T = P.second;
1469 if (T.isVector())
1470 PrintFatalError(R->getLoc(),
1471 "Cannot use vector type as SDTCVecEltisVT");
1472 if (!T.isInteger() && !T.isFloatingPoint())
1473 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1474 "as SDTCVecEltisVT");
1475 }
Craig Topper0be34582015-03-05 07:11:34 +00001476 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1477 ConstraintType = SDTCisSameNumEltsAs;
1478 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1479 R->getValueAsInt("OtherOperandNum");
Craig Topper9a44b3f2015-11-26 07:02:18 +00001480 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1481 ConstraintType = SDTCisSameSizeAs;
1482 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1483 R->getValueAsInt("OtherOperandNum");
Chris Lattner8cab0212008-01-05 22:25:12 +00001484 } else {
Daniel Sandersdff673b2019-02-12 17:36:57 +00001485 PrintFatalError(R->getLoc(),
1486 "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00001487 }
1488}
1489
1490/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2db7aba2010-03-19 21:56:21 +00001491/// N, and the result number in ResNo.
Florian Hahn6b1db822018-06-14 20:32:58 +00001492static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2db7aba2010-03-19 21:56:21 +00001493 const SDNodeInfo &NodeInfo,
1494 unsigned &ResNo) {
1495 unsigned NumResults = NodeInfo.getNumResults();
1496 if (OpNo < NumResults) {
1497 ResNo = OpNo;
1498 return N;
1499 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001500
Chris Lattner2db7aba2010-03-19 21:56:21 +00001501 OpNo -= NumResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001502
Florian Hahn6b1db822018-06-14 20:32:58 +00001503 if (OpNo >= N->getNumChildren()) {
James Y Knighte452e272015-05-11 22:17:13 +00001504 std::string S;
1505 raw_string_ostream OS(S);
1506 OS << "Invalid operand number in type constraint "
Chris Lattner2db7aba2010-03-19 21:56:21 +00001507 << (OpNo+NumResults) << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001508 N->print(OS);
James Y Knighte452e272015-05-11 22:17:13 +00001509 PrintFatalError(OS.str());
Chris Lattner8cab0212008-01-05 22:25:12 +00001510 }
1511
Florian Hahn6b1db822018-06-14 20:32:58 +00001512 return N->getChild(OpNo);
Chris Lattner8cab0212008-01-05 22:25:12 +00001513}
1514
1515/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1516/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001517/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn6b1db822018-06-14 20:32:58 +00001518bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner8cab0212008-01-05 22:25:12 +00001519 const SDNodeInfo &NodeInfo,
1520 TreePattern &TP) const {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001521 if (TP.hasError())
1522 return false;
1523
Chris Lattner2db7aba2010-03-19 21:56:21 +00001524 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn6b1db822018-06-14 20:32:58 +00001525 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001526 TypeInfer &TI = TP.getInfer();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001527
Chris Lattner8cab0212008-01-05 22:25:12 +00001528 switch (ConstraintType) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001529 case SDTCisVT:
1530 // Operand must be a particular type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001531 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001532 case SDTCisPtrTy:
Chris Lattner8cab0212008-01-05 22:25:12 +00001533 // Operand must be same as target pointer type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001534 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattnercabe0372010-03-15 06:00:16 +00001535 case SDTCisInt:
1536 // Require it to be one of the legal integer VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001537 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001538 case SDTCisFP:
1539 // Require it to be one of the legal fp VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001540 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattnercabe0372010-03-15 06:00:16 +00001541 case SDTCisVec:
1542 // Require it to be one of the legal vector VTs.
Florian Hahn6b1db822018-06-14 20:32:58 +00001543 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001544 case SDTCisSameAs: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001545 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001546 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001547 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001548 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1549 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00001550 }
1551 case SDTCisVTSmallerThanOp: {
1552 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1553 // have an integer type that is smaller than the VT.
Florian Hahn6b1db822018-06-14 20:32:58 +00001554 if (!NodeToApply->isLeaf() ||
1555 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1556 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001557 ->isSubClassOf("ValueType")) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001558 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001559 return false;
1560 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001561 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001562 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1563 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1564 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001565
Chris Lattner2db7aba2010-03-19 21:56:21 +00001566 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001567 TreePatternNode *OtherNode =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001568 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1569 OResNo);
Chris Lattnercabe0372010-03-15 06:00:16 +00001570
Florian Hahn6b1db822018-06-14 20:32:58 +00001571 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001572 }
1573 case SDTCisOpSmallerThanOp: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001574 unsigned BResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001575 TreePatternNode *BigOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001576 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1577 BResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001578 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1579 BigOperand->getExtType(BResNo));
Chris Lattner8cab0212008-01-05 22:25:12 +00001580 }
Nate Begeman17bedbc2008-02-09 01:37:05 +00001581 case SDTCisEltOfVec: {
Chris Lattner2db7aba2010-03-19 21:56:21 +00001582 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001583 TreePatternNode *VecOperand =
Chris Lattner2db7aba2010-03-19 21:56:21 +00001584 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1585 VResNo);
Chris Lattner57ebf632010-03-24 00:01:16 +00001586 // Filter vector types out of VecOperand that don't have the right element
1587 // type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001588 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1589 NodeToApply->getExtType(ResNo));
Nate Begeman17bedbc2008-02-09 01:37:05 +00001590 }
David Greene127fd1d2011-01-24 20:53:18 +00001591 case SDTCisSubVecOfVec: {
1592 unsigned VResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001593 TreePatternNode *BigVecOperand =
David Greene127fd1d2011-01-24 20:53:18 +00001594 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1595 VResNo);
1596
1597 // Filter vector types out of BigVecOperand that don't have the
1598 // right subvector type.
Florian Hahn6b1db822018-06-14 20:32:58 +00001599 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1600 NodeToApply->getExtType(ResNo));
David Greene127fd1d2011-01-24 20:53:18 +00001601 }
Craig Topper0be34582015-03-05 07:11:34 +00001602 case SDTCVecEltisVT: {
Florian Hahn6b1db822018-06-14 20:32:58 +00001603 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper0be34582015-03-05 07:11:34 +00001604 }
1605 case SDTCisSameNumEltsAs: {
1606 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001607 TreePatternNode *OtherNode =
Craig Topper0be34582015-03-05 07:11:34 +00001608 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1609 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001610 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1611 NodeToApply->getExtType(ResNo));
Craig Topper0be34582015-03-05 07:11:34 +00001612 }
Craig Topper9a44b3f2015-11-26 07:02:18 +00001613 case SDTCisSameSizeAs: {
1614 unsigned OResNo = 0;
Florian Hahn6b1db822018-06-14 20:32:58 +00001615 TreePatternNode *OtherNode =
Craig Topper9a44b3f2015-11-26 07:02:18 +00001616 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1617 N, NodeInfo, OResNo);
Florian Hahn6b1db822018-06-14 20:32:58 +00001618 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1619 NodeToApply->getExtType(ResNo));
Craig Topper9a44b3f2015-11-26 07:02:18 +00001620 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001621 }
David Blaikiea5708dc2012-01-17 07:00:13 +00001622 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner8cab0212008-01-05 22:25:12 +00001623}
1624
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001625// Update the node type to match an instruction operand or result as specified
1626// in the ins or outs lists on the instruction definition. Return true if the
1627// type was actually changed.
1628bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1629 Record *Operand,
1630 TreePattern &TP) {
1631 // The 'unknown' operand indicates that types should be inferred from the
1632 // context.
1633 if (Operand->isSubClassOf("unknown_class"))
1634 return false;
1635
1636 // The Operand class specifies a type directly.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001637 if (Operand->isSubClassOf("Operand")) {
1638 Record *R = Operand->getValueAsDef("Type");
1639 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1640 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1641 }
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001642
1643 // PointerLikeRegClass has a type that is determined at runtime.
1644 if (Operand->isSubClassOf("PointerLikeRegClass"))
1645 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1646
1647 // Both RegisterClass and RegisterOperand operands derive their types from a
1648 // register class def.
Craig Topper24064772014-04-15 07:20:03 +00001649 Record *RC = nullptr;
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001650 if (Operand->isSubClassOf("RegisterClass"))
1651 RC = Operand;
1652 else if (Operand->isSubClassOf("RegisterOperand"))
1653 RC = Operand->getValueAsDef("RegClass");
1654
1655 assert(RC && "Unknown operand type");
1656 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1657 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1658}
1659
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001660bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1661 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1662 if (!TP.getInfer().isConcrete(Types[i], true))
1663 return true;
1664 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001665 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001666 return true;
1667 return false;
1668}
1669
1670bool TreePatternNode::hasProperTypeByHwMode() const {
1671 for (const TypeSetByHwMode &S : Types)
1672 if (!S.isDefaultOnly())
1673 return true;
Florian Hahn75e87c32018-05-30 21:00:18 +00001674 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001675 if (C->hasProperTypeByHwMode())
1676 return true;
1677 return false;
1678}
1679
1680bool TreePatternNode::hasPossibleType() const {
1681 for (const TypeSetByHwMode &S : Types)
1682 if (!S.isPossible())
1683 return false;
Florian Hahn75e87c32018-05-30 21:00:18 +00001684 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001685 if (!C->hasPossibleType())
1686 return false;
1687 return true;
1688}
1689
1690bool TreePatternNode::setDefaultMode(unsigned Mode) {
1691 for (TypeSetByHwMode &S : Types) {
1692 S.makeSimple(Mode);
1693 // Check if the selected mode had a type conflict.
1694 if (S.get(DefaultMode).empty())
1695 return false;
1696 }
Florian Hahn75e87c32018-05-30 21:00:18 +00001697 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001698 if (!C->setDefaultMode(Mode))
1699 return false;
1700 return true;
1701}
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00001702
Chris Lattner8cab0212008-01-05 22:25:12 +00001703//===----------------------------------------------------------------------===//
1704// SDNodeInfo implementation
1705//
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001706SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001707 EnumName = R->getValueAsString("Opcode");
1708 SDClassName = R->getValueAsString("SDClass");
1709 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1710 NumResults = TypeProfile->getValueAsInt("NumResults");
1711 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001712
Chris Lattner8cab0212008-01-05 22:25:12 +00001713 // Parse the properties.
Matt Arsenault303327d2017-12-20 19:36:28 +00001714 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00001715
Chris Lattner8cab0212008-01-05 22:25:12 +00001716 // Parse the type constraints.
1717 std::vector<Record*> ConstraintList =
1718 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001719 for (Record *R : ConstraintList)
1720 TypeConstraints.emplace_back(R, CGH);
Chris Lattner8cab0212008-01-05 22:25:12 +00001721}
1722
Chris Lattner99e53b32010-02-28 00:22:30 +00001723/// getKnownType - If the type constraints on this node imply a fixed type
1724/// (e.g. all stores return void, etc), then return it as an
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001725/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner6c2d1782010-03-24 00:41:19 +00001726MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner99e53b32010-02-28 00:22:30 +00001727 unsigned NumResults = getNumResults();
1728 assert(NumResults <= 1 &&
1729 "We only work with nodes with zero or one result so far!");
Chris Lattner6c2d1782010-03-24 00:41:19 +00001730 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbach65586fe2010-12-21 16:16:00 +00001731
Craig Topper306cb122015-11-22 20:46:24 +00001732 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001733 // Make sure that this applies to the correct node result.
Craig Topper306cb122015-11-22 20:46:24 +00001734 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner99e53b32010-02-28 00:22:30 +00001735 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001736
Craig Topper306cb122015-11-22 20:46:24 +00001737 switch (Constraint.ConstraintType) {
Chris Lattner99e53b32010-02-28 00:22:30 +00001738 default: break;
1739 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001740 if (Constraint.VVT.isSimple())
1741 return Constraint.VVT.getSimple().SimpleTy;
1742 break;
Chris Lattner99e53b32010-02-28 00:22:30 +00001743 case SDTypeConstraint::SDTCisPtrTy:
1744 return MVT::iPTR;
1745 }
1746 }
Chris Lattnerda5b4ad2010-03-19 01:14:27 +00001747 return MVT::Other;
Chris Lattner99e53b32010-02-28 00:22:30 +00001748}
1749
Chris Lattner8cab0212008-01-05 22:25:12 +00001750//===----------------------------------------------------------------------===//
1751// TreePatternNode implementation
1752//
1753
Chris Lattnerf1447252010-03-19 21:37:09 +00001754static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1755 if (Operator->getName() == "set" ||
Chris Lattner5c2182e2010-03-27 02:53:27 +00001756 Operator->getName() == "implicit")
Chris Lattnerf1447252010-03-19 21:37:09 +00001757 return 0; // All return nothing.
Jim Grosbach65586fe2010-12-21 16:16:00 +00001758
Chris Lattner2109cb42010-03-22 20:56:36 +00001759 if (Operator->isSubClassOf("Intrinsic"))
1760 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001761
Chris Lattnerf1447252010-03-19 21:37:09 +00001762 if (Operator->isSubClassOf("SDNode"))
1763 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001764
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001765 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerf1447252010-03-19 21:37:09 +00001766 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1767 // the forward reference case where one pattern fragment references another
1768 // before it is processed.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001769 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1770 // The number of results of a fragment with alternative records is the
1771 // maximum number of results across all alternatives.
1772 unsigned NumResults = 0;
1773 for (auto T : PFRec->getTrees())
1774 NumResults = std::max(NumResults, T->getNumTypes());
1775 return NumResults;
1776 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001777
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001778 ListInit *LI = Operator->getValueAsListInit("Fragments");
1779 assert(LI && "Invalid Fragment");
1780 unsigned NumResults = 0;
1781 for (Init *I : LI->getValues()) {
1782 Record *Op = nullptr;
1783 if (DagInit *Dag = dyn_cast<DagInit>(I))
1784 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1785 Op = DI->getDef();
1786 assert(Op && "Invalid Fragment");
1787 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1788 }
1789 return NumResults;
Chris Lattnerf1447252010-03-19 21:37:09 +00001790 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001791
Chris Lattnerf1447252010-03-19 21:37:09 +00001792 if (Operator->isSubClassOf("Instruction")) {
1793 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattnerd44966f2010-03-27 19:15:02 +00001794
Craig Topper3a8eb892015-03-20 05:09:06 +00001795 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1796
1797 // Subtract any defaulted outputs.
1798 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1799 Record *OperandNode = InstInfo.Operands[i].Rec;
1800
1801 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1802 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1803 --NumDefsToAdd;
1804 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001805
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00001806 // Add on one implicit def if it has a resolvable type.
1807 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1808 ++NumDefsToAdd;
Chris Lattnerd44966f2010-03-27 19:15:02 +00001809 return NumDefsToAdd;
Chris Lattnerf1447252010-03-19 21:37:09 +00001810 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001811
Chris Lattnerf1447252010-03-19 21:37:09 +00001812 if (Operator->isSubClassOf("SDNodeXForm"))
1813 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbach65586fe2010-12-21 16:16:00 +00001814
Hal Finkel49f1c2a2014-01-02 20:47:05 +00001815 if (Operator->isSubClassOf("ValueType"))
1816 return 1; // A type-cast of one result.
1817
Tim Northoverc807a172014-05-20 11:52:46 +00001818 if (Operator->isSubClassOf("ComplexPattern"))
1819 return 1;
1820
Matthias Braun8c209aa2017-01-28 02:02:38 +00001821 errs() << *Operator;
James Y Knighte452e272015-05-11 22:17:13 +00001822 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerf1447252010-03-19 21:37:09 +00001823}
1824
1825void TreePatternNode::print(raw_ostream &OS) const {
1826 if (isLeaf())
1827 OS << *getLeafValue();
1828 else
1829 OS << '(' << getOperator()->getName();
1830
Zachary Turner249dc142017-09-20 18:01:40 +00001831 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1832 OS << ':';
1833 getExtType(i).writeToStream(OS);
1834 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001835
1836 if (!isLeaf()) {
1837 if (getNumChildren() != 0) {
1838 OS << " ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001839 getChild(0)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001840 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1841 OS << ", ";
Florian Hahn6b1db822018-06-14 20:32:58 +00001842 getChild(i)->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00001843 }
1844 }
1845 OS << ")";
1846 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001847
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001848 for (const TreePredicateCall &Pred : PredicateCalls) {
1849 OS << "<<P:";
1850 if (Pred.Scope)
1851 OS << Pred.Scope << ":";
1852 OS << Pred.Fn.getFnName() << ">>";
1853 }
Chris Lattner8cab0212008-01-05 22:25:12 +00001854 if (TransformFn)
1855 OS << "<<X:" << TransformFn->getName() << ">>";
1856 if (!getName().empty())
1857 OS << ":$" << getName();
1858
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001859 for (const ScopedName &Name : NamesAsPredicateArg)
1860 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
Chris Lattner8cab0212008-01-05 22:25:12 +00001861}
1862void TreePatternNode::dump() const {
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00001863 print(errs());
Chris Lattner8cab0212008-01-05 22:25:12 +00001864}
1865
Scott Michel94420742008-03-05 17:49:05 +00001866/// isIsomorphicTo - Return true if this node is recursively
1867/// isomorphic to the specified node. For this comparison, the node's
1868/// entire state is considered. The assigned name is ignored, since
1869/// nodes with differing names are considered isomorphic. However, if
1870/// the assigned name is present in the dependent variable set, then
1871/// the assigned name is considered significant and the node is
1872/// isomorphic if the names match.
Florian Hahn6b1db822018-06-14 20:32:58 +00001873bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel94420742008-03-05 17:49:05 +00001874 const MultipleUseVarSet &DepVars) const {
Florian Hahn6b1db822018-06-14 20:32:58 +00001875 if (N == this) return true;
1876 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001877 getPredicateCalls() != N->getPredicateCalls() ||
Florian Hahn6b1db822018-06-14 20:32:58 +00001878 getTransformFn() != N->getTransformFn())
Chris Lattner8cab0212008-01-05 22:25:12 +00001879 return false;
1880
1881 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00001882 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001883 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattnera7cca362008-03-20 01:22:40 +00001884 return ((DI->getDef() == NDI->getDef())
1885 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn6b1db822018-06-14 20:32:58 +00001886 || getName() == N->getName()));
Scott Michel94420742008-03-05 17:49:05 +00001887 }
1888 }
Florian Hahn6b1db822018-06-14 20:32:58 +00001889 return getLeafValue() == N->getLeafValue();
Chris Lattner8cab0212008-01-05 22:25:12 +00001890 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00001891
Florian Hahn6b1db822018-06-14 20:32:58 +00001892 if (N->getOperator() != getOperator() ||
1893 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner8cab0212008-01-05 22:25:12 +00001894 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001895 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner8cab0212008-01-05 22:25:12 +00001896 return false;
1897 return true;
1898}
1899
1900/// clone - Make a copy of this tree and all of its children.
1901///
Florian Hahn75e87c32018-05-30 21:00:18 +00001902TreePatternNodePtr TreePatternNode::clone() const {
1903 TreePatternNodePtr New;
Chris Lattner8cab0212008-01-05 22:25:12 +00001904 if (isLeaf()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001905 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001906 } else {
Florian Hahn75e87c32018-05-30 21:00:18 +00001907 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00001908 CChildren.reserve(Children.size());
1909 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001910 CChildren.push_back(getChild(i)->clone());
Craig Topper26fc06352018-07-15 06:52:49 +00001911 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn75e87c32018-05-30 21:00:18 +00001912 getNumTypes());
Chris Lattner8cab0212008-01-05 22:25:12 +00001913 }
1914 New->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001915 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
Chris Lattnerf1447252010-03-19 21:37:09 +00001916 New->Types = Types;
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001917 New->setPredicateCalls(getPredicateCalls());
Chris Lattner8cab0212008-01-05 22:25:12 +00001918 New->setTransformFn(getTransformFn());
1919 return New;
1920}
1921
Chris Lattner53c39ba2010-02-14 22:22:58 +00001922/// RemoveAllTypes - Recursively strip all the types of this tree.
1923void TreePatternNode::RemoveAllTypes() {
Craig Topper43c414f2015-11-22 20:46:22 +00001924 // Reset to unknown type.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00001925 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner53c39ba2010-02-14 22:22:58 +00001926 if (isLeaf()) return;
1927 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00001928 getChild(i)->RemoveAllTypes();
Chris Lattner53c39ba2010-02-14 22:22:58 +00001929}
1930
1931
Chris Lattner8cab0212008-01-05 22:25:12 +00001932/// SubstituteFormalArguments - Replace the formal arguments in this tree
1933/// with actual values specified by ArgMap.
Florian Hahn75e87c32018-05-30 21:00:18 +00001934void TreePatternNode::SubstituteFormalArguments(
1935 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001936 if (isLeaf()) return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00001937
Chris Lattner8cab0212008-01-05 22:25:12 +00001938 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00001939 TreePatternNode *Child = getChild(i);
1940 if (Child->isLeaf()) {
1941 Init *Val = Child->getLeafValue();
Hal Finkel2756dc12014-02-28 00:26:56 +00001942 // Note that, when substituting into an output pattern, Val might be an
1943 // UnsetInit.
1944 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1945 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00001946 // We found a use of a formal argument, replace it with its value.
Florian Hahn6b1db822018-06-14 20:32:58 +00001947 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman6e979022008-10-15 06:17:21 +00001948 assert(NewChild && "Couldn't find formal argument!");
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001949 assert((Child->getPredicateCalls().empty() ||
1950 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Dan Gohman6e979022008-10-15 06:17:21 +00001951 "Non-empty child predicate clobbered!");
Florian Hahn0a2e0b62018-06-14 11:56:19 +00001952 setChild(i, std::move(NewChild));
Chris Lattner8cab0212008-01-05 22:25:12 +00001953 }
1954 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00001955 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner8cab0212008-01-05 22:25:12 +00001956 }
1957 }
1958}
1959
1960
1961/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001962/// fragments, return the set of inlined versions (this can be more than
1963/// one if a PatFrags record has multiple alternatives).
1964void TreePatternNode::InlinePatternFragments(
1965 TreePatternNodePtr T, TreePattern &TP,
1966 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00001967
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001968 if (TP.hasError())
1969 return;
1970
1971 if (isLeaf()) {
1972 OutAlternatives.push_back(T); // nothing to do.
1973 return;
1974 }
1975
Chris Lattner8cab0212008-01-05 22:25:12 +00001976 Record *Op = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00001977
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001978 if (!Op->isSubClassOf("PatFrags")) {
1979 if (getNumChildren() == 0) {
1980 OutAlternatives.push_back(T);
1981 return;
1982 }
1983
1984 // Recursively inline children nodes.
1985 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1986 ChildAlternatives.resize(getNumChildren());
Dan Gohman6e979022008-10-15 06:17:21 +00001987 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00001988 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001989 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1990 // If there are no alternatives for any child, there are no
1991 // alternatives for this expression as whole.
1992 if (ChildAlternatives[i].empty())
1993 return;
Dan Gohman6e979022008-10-15 06:17:21 +00001994
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001995 for (auto NewChild : ChildAlternatives[i])
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00001996 assert((Child->getPredicateCalls().empty() ||
1997 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00001998 "Non-empty child predicate clobbered!");
Dan Gohman6e979022008-10-15 06:17:21 +00001999 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002000
2001 // The end result is an all-pairs construction of the resultant pattern.
2002 std::vector<unsigned> Idxs;
2003 Idxs.resize(ChildAlternatives.size());
2004 bool NotDone;
2005 do {
2006 // Create the variant and add it to the output list.
2007 std::vector<TreePatternNodePtr> NewChildren;
2008 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2009 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
2010 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00002011 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002012
2013 // Copy over properties.
2014 R->setName(getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002015 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2016 R->setPredicateCalls(getPredicateCalls());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002017 R->setTransformFn(getTransformFn());
2018 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2019 R->setType(i, getExtType(i));
Craig Topperbd199f82018-12-05 00:47:59 +00002020 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2021 R->setResultIndex(i, getResultIndex(i));
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002022
2023 // Register alternative.
2024 OutAlternatives.push_back(R);
2025
2026 // Increment indices to the next permutation by incrementing the
2027 // indices from last index backward, e.g., generate the sequence
2028 // [0, 0], [0, 1], [1, 0], [1, 1].
2029 int IdxsIdx;
2030 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2031 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2032 Idxs[IdxsIdx] = 0;
2033 else
2034 break;
2035 }
2036 NotDone = (IdxsIdx >= 0);
2037 } while (NotDone);
2038
2039 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002040 }
2041
2042 // Otherwise, we found a reference to a fragment. First, look up its
2043 // TreePattern record.
2044 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002045
Chris Lattner8cab0212008-01-05 22:25:12 +00002046 // Verify that we are passing the right number of operands.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002047 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002048 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002049 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002050 return;
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002051 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002052
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002053 TreePredicateFn PredFn(Frag);
2054 unsigned Scope = 0;
2055 if (TreePredicateFn(Frag).usesOperands())
2056 Scope = TP.getDAGPatterns().allocateScope();
2057
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002058 // Compute the map of formal to actual arguments.
2059 std::map<std::string, TreePatternNodePtr> ArgMap;
2060 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002061 TreePatternNodePtr Child = getChildShared(i);
2062 if (Scope != 0) {
2063 Child = Child->clone();
2064 Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
2065 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002066 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner8cab0212008-01-05 22:25:12 +00002067 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002068
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002069 // Loop over all fragment alternatives.
2070 for (auto Alternative : Frag->getTrees()) {
2071 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman6e979022008-10-15 06:17:21 +00002072
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002073 if (!PredFn.isAlwaysTrue())
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002074 FragTree->addPredicateCall(PredFn, Scope);
Dan Gohman6e979022008-10-15 06:17:21 +00002075
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002076 // Resolve formal arguments to their actual value.
2077 if (Frag->getNumArgs())
2078 FragTree->SubstituteFormalArguments(ArgMap);
2079
2080 // Transfer types. Note that the resolved alternative may have fewer
2081 // (but not more) results than the PatFrags node.
2082 FragTree->setName(getName());
2083 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2084 FragTree->UpdateNodeType(i, getExtType(i), TP);
2085
2086 // Transfer in the old predicates.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00002087 for (const TreePredicateCall &Pred : getPredicateCalls())
2088 FragTree->addPredicateCall(Pred);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002089
2090 // The fragment we inlined could have recursive inlining that is needed. See
2091 // if there are any pattern fragments in it and inline them as needed.
2092 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2093 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002094}
2095
2096/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyd9d1f812009-06-17 04:23:52 +00002097/// type which should be applied to it. This will infer the type of register
Chris Lattner8cab0212008-01-05 22:25:12 +00002098/// references from the register file information, for example.
2099///
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002100/// When Unnamed is set, return the type of a DAG operand with no name, such as
2101/// the F8RC register class argument in:
2102///
2103/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2104///
2105/// When Unnamed is false, return the type of a named DAG operand such as the
2106/// GPR:$src operand above.
2107///
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002108static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2109 bool NotRegisters,
2110 bool Unnamed,
2111 TreePattern &TP) {
2112 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2113
Owen Andersona84be6c2011-06-27 21:06:21 +00002114 // Check to see if this is a register operand.
2115 if (R->isSubClassOf("RegisterOperand")) {
2116 assert(ResNo == 0 && "Regoperand ref only has one result!");
2117 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002118 return TypeSetByHwMode(); // Unknown.
Owen Andersona84be6c2011-06-27 21:06:21 +00002119 Record *RegClass = R->getValueAsDef("RegClass");
2120 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002121 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersona84be6c2011-06-27 21:06:21 +00002122 }
2123
Chris Lattnercabe0372010-03-15 06:00:16 +00002124 // Check to see if this is a register or a register class.
Chris Lattner8cab0212008-01-05 22:25:12 +00002125 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002126 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002127 // An unnamed register class represents itself as an i32 immediate, for
2128 // example on a COPY_TO_REGCLASS instruction.
2129 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002130 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002131
2132 // In a named operand, the register class provides the possible set of
2133 // types.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002134 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002135 return TypeSetByHwMode(); // Unknown.
Chris Lattnercabe0372010-03-15 06:00:16 +00002136 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002137 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner6070ee22010-03-23 23:50:31 +00002138 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002139
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002140 if (R->isSubClassOf("PatFrags")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002141 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner8cab0212008-01-05 22:25:12 +00002142 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002143 return TypeSetByHwMode(); // Unknown.
Chris Lattner6070ee22010-03-23 23:50:31 +00002144 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002145
Chris Lattner6070ee22010-03-23 23:50:31 +00002146 if (R->isSubClassOf("Register")) {
2147 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002148 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002149 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002150 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002151 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner6070ee22010-03-23 23:50:31 +00002152 }
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002153
2154 if (R->isSubClassOf("SubRegIndex")) {
2155 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002156 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen1c696462010-05-24 14:48:12 +00002157 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002158
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002159 if (R->isSubClassOf("ValueType")) {
Chris Lattner6070ee22010-03-23 23:50:31 +00002160 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002161 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2162 //
2163 // (sext_inreg GPR:$src, i16)
2164 // ~~~
2165 if (Unnamed)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002166 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002167 // With a name, the ValueType simply provides the type of the named
2168 // variable.
2169 //
2170 // (sext_inreg i32:$src, i16)
2171 // ~~~~~~~~
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00002172 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002173 return TypeSetByHwMode(); // Unknown.
2174 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2175 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesend906b902013-03-23 20:35:01 +00002176 }
2177
2178 if (R->isSubClassOf("CondCode")) {
2179 assert(ResNo == 0 && "This node only has one result!");
2180 // Using a CondCodeSDNode.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002181 return TypeSetByHwMode(MVT::Other);
Chris Lattner6070ee22010-03-23 23:50:31 +00002182 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002183
Chris Lattner6070ee22010-03-23 23:50:31 +00002184 if (R->isSubClassOf("ComplexPattern")) {
2185 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002186 if (NotRegisters)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002187 return TypeSetByHwMode(); // Unknown.
2188 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner6070ee22010-03-23 23:50:31 +00002189 }
2190 if (R->isSubClassOf("PointerLikeRegClass")) {
2191 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002192 TypeSetByHwMode VTS(MVT::iPTR);
2193 TP.getInfer().expandOverloads(VTS);
2194 return VTS;
Chris Lattner6070ee22010-03-23 23:50:31 +00002195 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002196
Chris Lattner6070ee22010-03-23 23:50:31 +00002197 if (R->getName() == "node" || R->getName() == "srcvalue" ||
Craig Topper1a872f22019-03-10 05:21:52 +00002198 R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
Sjoerd Meijerde234842019-05-30 07:30:37 +00002199 R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
Chris Lattner8cab0212008-01-05 22:25:12 +00002200 // Placeholder.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002201 return TypeSetByHwMode(); // Unknown.
Chris Lattner8cab0212008-01-05 22:25:12 +00002202 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002203
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002204 if (R->isSubClassOf("Operand")) {
2205 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2206 Record *T = R->getValueAsDef("Type");
2207 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2208 }
Tim Northoverc807a172014-05-20 11:52:46 +00002209
Chris Lattner8cab0212008-01-05 22:25:12 +00002210 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002211 return TypeSetByHwMode(MVT::Other);
Chris Lattner8cab0212008-01-05 22:25:12 +00002212}
2213
Chris Lattner89c65662008-01-06 05:36:50 +00002214
2215/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2216/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2217const CodeGenIntrinsic *TreePatternNode::
2218getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2219 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2220 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2221 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper24064772014-04-15 07:20:03 +00002222 return nullptr;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002223
Florian Hahn6b1db822018-06-14 20:32:58 +00002224 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattner89c65662008-01-06 05:36:50 +00002225 return &CDP.getIntrinsicInfo(IID);
2226}
2227
Chris Lattner53c39ba2010-02-14 22:22:58 +00002228/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2229/// return the ComplexPattern information, otherwise return null.
2230const ComplexPattern *
2231TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoverc807a172014-05-20 11:52:46 +00002232 Record *Rec;
2233 if (isLeaf()) {
2234 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2235 if (!DI)
2236 return nullptr;
2237 Rec = DI->getDef();
2238 } else
2239 Rec = getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002240
Tim Northoverc807a172014-05-20 11:52:46 +00002241 if (!Rec->isSubClassOf("ComplexPattern"))
2242 return nullptr;
2243 return &CGP.getComplexPattern(Rec);
2244}
2245
2246unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2247 // A ComplexPattern specifically declares how many results it fills in.
2248 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2249 return CP->getNumOperands();
2250
2251 // If MIOperandInfo is specified, that gives the count.
2252 if (isLeaf()) {
2253 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2254 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2255 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2256 if (MIOps->getNumArgs())
2257 return MIOps->getNumArgs();
2258 }
2259 }
2260
2261 // Otherwise there is just one result.
2262 return 1;
Chris Lattner53c39ba2010-02-14 22:22:58 +00002263}
2264
2265/// NodeHasProperty - Return true if this node has the specified property.
2266bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002267 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002268 if (isLeaf()) {
2269 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2270 return CP->hasProperty(Property);
Matt Arsenault303327d2017-12-20 19:36:28 +00002271
Chris Lattner53c39ba2010-02-14 22:22:58 +00002272 return false;
2273 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002274
Matt Arsenault303327d2017-12-20 19:36:28 +00002275 if (Property != SDNPHasChain) {
2276 // The chain proprety is already present on the different intrinsic node
2277 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2278 // on the intrinsic. Anything else is specific to the individual intrinsic.
2279 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2280 return Int->hasProperty(Property);
2281 }
2282
2283 if (!Operator->isSubClassOf("SDPatternOperator"))
2284 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002285
Chris Lattner53c39ba2010-02-14 22:22:58 +00002286 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2287}
2288
2289
2290
2291
2292/// TreeHasProperty - Return true if any node in this tree has the specified
2293/// property.
2294bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner450d5042010-02-14 22:33:49 +00002295 const CodeGenDAGPatterns &CGP) const {
Chris Lattner53c39ba2010-02-14 22:22:58 +00002296 if (NodeHasProperty(Property, CGP))
2297 return true;
2298 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002299 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner53c39ba2010-02-14 22:22:58 +00002300 return true;
2301 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002302}
Chris Lattner53c39ba2010-02-14 22:22:58 +00002303
Evan Cheng49bad4c2008-06-16 20:29:38 +00002304/// isCommutativeIntrinsic - Return true if the node corresponds to a
2305/// commutative intrinsic.
2306bool
2307TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2308 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2309 return Int->isCommutative;
2310 return false;
2311}
2312
Florian Hahn6b1db822018-06-14 20:32:58 +00002313static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2314 if (!N->isLeaf())
2315 return N->getOperator()->isSubClassOf(Class);
Chris Lattner89c65662008-01-06 05:36:50 +00002316
Florian Hahn6b1db822018-06-14 20:32:58 +00002317 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenaulteb492162014-11-02 23:46:51 +00002318 if (DI && DI->getDef()->isSubClassOf(Class))
2319 return true;
2320
2321 return false;
2322}
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002323
2324static void emitTooManyOperandsError(TreePattern &TP,
2325 StringRef InstName,
2326 unsigned Expected,
2327 unsigned Actual) {
2328 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2329 " operands but expected only " + Twine(Expected) + "!");
2330}
2331
2332static void emitTooFewOperandsError(TreePattern &TP,
2333 StringRef InstName,
2334 unsigned Actual) {
2335 TP.error("Instruction '" + InstName +
2336 "' expects more than the provided " + Twine(Actual) + " operands!");
2337}
2338
Bob Wilson1b97f3f2009-01-05 17:23:09 +00002339/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner8cab0212008-01-05 22:25:12 +00002340/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002341/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner8cab0212008-01-05 22:25:12 +00002342bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002343 if (TP.hasError())
2344 return false;
2345
Chris Lattnerab3242f2008-01-06 01:10:31 +00002346 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner8cab0212008-01-05 22:25:12 +00002347 if (isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002348 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002349 // If it's a regclass or something else known, include the type.
Chris Lattnerf1447252010-03-19 21:37:09 +00002350 bool MadeChange = false;
2351 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2352 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesenb5b91102013-03-23 18:08:44 +00002353 NotRegisters,
2354 !hasName(), TP), TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002355 return MadeChange;
Chris Lattner78291e32010-02-14 21:10:15 +00002356 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002357
Sean Silvafb509ed2012-10-10 20:24:43 +00002358 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002359 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002360
Chris Lattnerf1447252010-03-19 21:37:09 +00002361 // Int inits are always integers. :)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002362 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002363
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002364 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattnercabe0372010-03-15 06:00:16 +00002365 return MadeChange;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002366
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002367 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2368 for (auto &P : VVT) {
2369 MVT::SimpleValueType VT = P.second.SimpleTy;
2370 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2371 continue;
2372 unsigned Size = MVT(VT).getSizeInBits();
2373 // Make sure that the value is representable for this type.
2374 if (Size >= 32)
2375 continue;
2376 // Check that the value doesn't use more bits than we have. It must
2377 // either be a sign- or zero-extended equivalent of the original.
2378 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2379 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2380 SignBitAndAbove == 1)
2381 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002382
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002383 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002384 "' is out of range for type '" + getEnumName(VT) + "'!");
2385 break;
2386 }
2387 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002388 }
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002389
Chris Lattner8cab0212008-01-05 22:25:12 +00002390 return false;
2391 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002392
Chris Lattneree820ac2010-02-23 05:51:07 +00002393 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002394 bool MadeChange = false;
Duncan Sands13237ac2008-06-06 12:08:01 +00002395
Chris Lattner8cab0212008-01-05 22:25:12 +00002396 // Apply the result type to the node.
Bill Wendling91821472008-11-13 09:08:33 +00002397 unsigned NumRetVTs = Int->IS.RetVTs.size();
2398 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002399
Bill Wendling91821472008-11-13 09:08:33 +00002400 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerf1447252010-03-19 21:37:09 +00002401 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendling91821472008-11-13 09:08:33 +00002402
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002403 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002404 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2405 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002406 return false;
2407 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002408
2409 // Apply type info to the intrinsic ID.
Florian Hahn6b1db822018-06-14 20:32:58 +00002410 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002411
Chris Lattnerf1447252010-03-19 21:37:09 +00002412 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002413 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002414
Chris Lattnerf1447252010-03-19 21:37:09 +00002415 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn6b1db822018-06-14 20:32:58 +00002416 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2417 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002418 }
2419 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002420 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002421
Chris Lattneree820ac2010-02-23 05:51:07 +00002422 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002423 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002424
Chris Lattner135091b2010-03-28 08:48:47 +00002425 // Check that the number of operands is sane. Negative operands -> varargs.
2426 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002427 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner135091b2010-03-28 08:48:47 +00002428 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002429 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002430 return false;
2431 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002432
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002433 bool MadeChange = false;
Chris Lattner8cab0212008-01-05 22:25:12 +00002434 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002435 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2436 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerf1447252010-03-19 21:37:09 +00002437 return MadeChange;
Chris Lattneree820ac2010-02-23 05:51:07 +00002438 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002439
Chris Lattneree820ac2010-02-23 05:51:07 +00002440 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002441 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002442 CodeGenInstruction &InstInfo =
Chris Lattner9aec14b2010-03-19 00:07:20 +00002443 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002444
Chris Lattnerd44966f2010-03-27 19:15:02 +00002445 bool MadeChange = false;
2446
2447 // Apply the result types to the node, these come from the things in the
2448 // (outs) list of the instruction.
Craig Topper3a8eb892015-03-20 05:09:06 +00002449 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2450 Inst.getNumResults());
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002451 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2452 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002453
Chris Lattnerd44966f2010-03-27 19:15:02 +00002454 // If the instruction has implicit defs, we apply the first one as a result.
2455 // FIXME: This sucks, it should apply all implicit defs.
2456 if (!InstInfo.ImplicitDefs.empty()) {
2457 unsigned ResNo = NumResultsToAdd;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002458
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002459 // FIXME: Generalize to multiple possible types and multiple possible
2460 // ImplicitDefs.
2461 MVT::SimpleValueType VT =
2462 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbach65586fe2010-12-21 16:16:00 +00002463
Chris Lattner7bc5d9b2010-03-27 20:09:24 +00002464 if (VT != MVT::Other)
2465 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002466 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002467
Chris Lattnercabe0372010-03-15 06:00:16 +00002468 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2469 // be the same.
2470 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn6b1db822018-06-14 20:32:58 +00002471 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2472 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2473 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002474 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2475 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2476 // variadic.
2477
2478 unsigned NChild = getNumChildren();
2479 if (NChild < 3) {
2480 TP.error("REG_SEQUENCE requires at least 3 operands!");
2481 return false;
2482 }
2483
2484 if (NChild % 2 == 0) {
2485 TP.error("REG_SEQUENCE requires an odd number of operands!");
2486 return false;
2487 }
2488
2489 if (!isOperandClass(getChild(0), "RegisterClass")) {
2490 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2491 return false;
2492 }
2493
2494 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002495 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenaulteb492162014-11-02 23:46:51 +00002496 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2497 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramer3a13ed62017-12-28 16:58:54 +00002498 Twine(I + 1) + "!");
Matt Arsenaulteb492162014-11-02 23:46:51 +00002499 return false;
2500 }
2501 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002502 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002503
Simon Tathamc74322a2019-07-04 08:43:20 +00002504 // If one or more operands with a default value appear at the end of the
2505 // formal operand list for an instruction, we allow them to be overridden
2506 // by optional operands provided in the pattern.
2507 //
2508 // But if an operand B without a default appears at any point after an
2509 // operand A with a default, then we don't allow A to be overridden,
2510 // because there would be no way to specify whether the next operand in
2511 // the pattern was intended to override A or skip it.
2512 unsigned NonOverridableOperands = Inst.getNumOperands();
2513 while (NonOverridableOperands > 0 &&
2514 CDP.operandHasDefault(Inst.getOperand(NonOverridableOperands-1)))
2515 --NonOverridableOperands;
2516
Chris Lattner8cab0212008-01-05 22:25:12 +00002517 unsigned ChildNo = 0;
2518 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2519 Record *OperandNode = Inst.getOperand(i);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002520
Simon Tathamc74322a2019-07-04 08:43:20 +00002521 // If the operand has a default value, do we use it? We must use the
2522 // default if we've run out of children of the pattern DAG to consume,
2523 // or if the operand is followed by a non-defaulted one.
2524 if (CDP.operandHasDefault(OperandNode) &&
2525 (i < NonOverridableOperands || ChildNo >= getNumChildren()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002526 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002527
Simon Tathamc74322a2019-07-04 08:43:20 +00002528 // If we have run out of child nodes and there _isn't_ a default
2529 // value we can use for the next operand, give an error.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002530 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002531 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002532 return false;
2533 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002534
Florian Hahn6b1db822018-06-14 20:32:58 +00002535 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattnerd44966f2010-03-27 19:15:02 +00002536 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigande618abd2013-03-19 19:51:09 +00002537
2538 // If the operand has sub-operands, they may be provided by distinct
2539 // child patterns, so attempt to match each sub-operand separately.
2540 if (OperandNode->isSubClassOf("Operand")) {
2541 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2542 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2543 // But don't do that if the whole operand is being provided by
Tim Northoverc350acf2014-05-22 11:56:09 +00002544 // a single ComplexPattern-related Operand.
2545
2546 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigande618abd2013-03-19 19:51:09 +00002547 // Match first sub-operand against the child we already have.
2548 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2549 MadeChange |=
2550 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2551
2552 // And the remaining sub-operands against subsequent children.
2553 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2554 if (ChildNo >= getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002555 emitTooFewOperandsError(TP, getOperator()->getName(),
2556 getNumChildren());
Ulrich Weigande618abd2013-03-19 19:51:09 +00002557 return false;
2558 }
Florian Hahn6b1db822018-06-14 20:32:58 +00002559 Child = getChild(ChildNo++);
Ulrich Weigande618abd2013-03-19 19:51:09 +00002560
2561 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2562 MadeChange |=
2563 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2564 }
2565 continue;
2566 }
2567 }
2568 }
2569
2570 // If we didn't match by pieces above, attempt to match the whole
2571 // operand now.
Jakob Stoklund Olesen57a86502013-03-18 04:08:07 +00002572 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner8cab0212008-01-05 22:25:12 +00002573 }
Christopher Lamba7312392008-03-11 09:33:47 +00002574
Matt Arsenaulteb492162014-11-02 23:46:51 +00002575 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9ece3ce2014-12-11 22:27:14 +00002576 emitTooManyOperandsError(TP, getOperator()->getName(),
2577 ChildNo, getNumChildren());
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002578 return false;
2579 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002580
Ulrich Weigande618abd2013-03-19 19:51:09 +00002581 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002582 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner8cab0212008-01-05 22:25:12 +00002583 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002584 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002585
Tim Northoverc807a172014-05-20 11:52:46 +00002586 if (getOperator()->isSubClassOf("ComplexPattern")) {
2587 bool MadeChange = false;
2588
2589 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002590 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoverc807a172014-05-20 11:52:46 +00002591
2592 return MadeChange;
2593 }
2594
Chris Lattneree820ac2010-02-23 05:51:07 +00002595 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002596
Chris Lattneree820ac2010-02-23 05:51:07 +00002597 // Node transforms always take one operand.
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002598 if (getNumChildren() != 1) {
Chris Lattneree820ac2010-02-23 05:51:07 +00002599 TP.error("Node transform '" + getOperator()->getName() +
2600 "' requires one operand!");
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002601 return false;
2602 }
Chris Lattneree820ac2010-02-23 05:51:07 +00002603
Florian Hahn6b1db822018-06-14 20:32:58 +00002604 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattnercabe0372010-03-15 06:00:16 +00002605 return MadeChange;
Chris Lattner8cab0212008-01-05 22:25:12 +00002606}
2607
2608/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2609/// RHS of a commutative operation, not the on LHS.
Florian Hahn6b1db822018-06-14 20:32:58 +00002610static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2611 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner8cab0212008-01-05 22:25:12 +00002612 return true;
Florian Hahn6b1db822018-06-14 20:32:58 +00002613 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner8cab0212008-01-05 22:25:12 +00002614 return true;
2615 return false;
2616}
2617
2618
2619/// canPatternMatch - If it is impossible for this pattern to match on this
2620/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002621/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner8cab0212008-01-05 22:25:12 +00002622/// that can never possibly work), and to prevent the pattern permuter from
2623/// generating stuff that is useless.
Jim Grosbach65586fe2010-12-21 16:16:00 +00002624bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00002625 const CodeGenDAGPatterns &CDP) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002626 if (isLeaf()) return true;
2627
2628 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002629 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner8cab0212008-01-05 22:25:12 +00002630 return false;
2631
2632 // If this is an intrinsic, handle cases that would make it not match. For
2633 // example, if an operand is required to be an immediate.
2634 if (getOperator()->isSubClassOf("Intrinsic")) {
2635 // TODO:
2636 return true;
2637 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002638
Tim Northoverc807a172014-05-20 11:52:46 +00002639 if (getOperator()->isSubClassOf("ComplexPattern"))
2640 return true;
2641
Chris Lattner8cab0212008-01-05 22:25:12 +00002642 // If this node is a commutative operator, check that the LHS isn't an
2643 // immediate.
2644 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng49bad4c2008-06-16 20:29:38 +00002645 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2646 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner8cab0212008-01-05 22:25:12 +00002647 // Scan all of the operands of the node and make sure that only the last one
2648 // is a constant node, unless the RHS also is.
2649 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper04bd11e2016-12-19 08:35:08 +00002650 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng49bad4c2008-06-16 20:29:38 +00002651 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner8cab0212008-01-05 22:25:12 +00002652 if (OnlyOnRHSOfCommutative(getChild(i))) {
2653 Reason="Immediate value must be on the RHS of commutative operators!";
2654 return false;
2655 }
2656 }
2657 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002658
Chris Lattner8cab0212008-01-05 22:25:12 +00002659 return true;
2660}
2661
2662//===----------------------------------------------------------------------===//
2663// TreePattern implementation
2664//
2665
David Greeneaf8ee2c2011-07-29 22:43:06 +00002666TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002667 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002668 isInputPattern(isInput), HasError(false),
2669 Infer(*this) {
Craig Topperef0578a2015-06-02 04:15:51 +00002670 for (Init *I : RawPat->getValues())
2671 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002672}
2673
David Greeneaf8ee2c2011-07-29 22:43:06 +00002674TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002675 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002676 isInputPattern(isInput), HasError(false),
2677 Infer(*this) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002678 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner8cab0212008-01-05 22:25:12 +00002679}
2680
Florian Hahn75e87c32018-05-30 21:00:18 +00002681TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2682 CodeGenDAGPatterns &cdp)
2683 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2684 Infer(*this) {
David Blaikiecf195302014-11-17 22:55:41 +00002685 Trees.push_back(Pat);
Chris Lattner8cab0212008-01-05 22:25:12 +00002686}
2687
Matt Arsenaultea8df3a2014-11-11 23:48:11 +00002688void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002689 if (HasError)
2690 return;
Chris Lattner8cab0212008-01-05 22:25:12 +00002691 dump();
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002692 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2693 HasError = true;
Chris Lattner8cab0212008-01-05 22:25:12 +00002694}
2695
Chris Lattnercabe0372010-03-15 06:00:16 +00002696void TreePattern::ComputeNamedNodes() {
Florian Hahn6b1db822018-06-14 20:32:58 +00002697 for (TreePatternNodePtr &Tree : Trees)
2698 ComputeNamedNodes(Tree.get());
Chris Lattnercabe0372010-03-15 06:00:16 +00002699}
2700
Florian Hahn6b1db822018-06-14 20:32:58 +00002701void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002702 if (!N->getName().empty())
Florian Hahn6b1db822018-06-14 20:32:58 +00002703 NamedNodes[N->getName()].push_back(N);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002704
Chris Lattnercabe0372010-03-15 06:00:16 +00002705 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00002706 ComputeNamedNodes(N->getChild(i));
Chris Lattnercabe0372010-03-15 06:00:16 +00002707}
2708
Florian Hahn75e87c32018-05-30 21:00:18 +00002709TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2710 StringRef OpName) {
Sean Silvafb509ed2012-10-10 20:24:43 +00002711 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002712 Record *R = DI->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002713
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002714 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbachfdc02c12011-07-06 23:38:13 +00002715 // TreePatternNode of its own. For example:
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002716 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002717 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenee32ebf22011-07-29 19:07:07 +00002718 return ParseTreePattern(
Matthias Braun7cf3b112016-12-05 06:00:41 +00002719 DagInit::get(DI, nullptr,
Matthias Braunbb053162016-12-05 06:00:46 +00002720 std::vector<std::pair<Init*, StringInit*> >()),
David Greenee32ebf22011-07-29 19:07:07 +00002721 OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002722
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002723 // Input argument?
Florian Hahn75e87c32018-05-30 21:00:18 +00002724 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner135091b2010-03-28 08:48:47 +00002725 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002726 if (OpName.empty())
2727 error("'node' argument requires a name to match with operand list");
2728 Args.push_back(OpName);
2729 }
2730
2731 Res->setName(OpName);
2732 return Res;
2733 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002734
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002735 // ?:$name or just $name.
Craig Topper1bf3d1f2015-04-22 02:09:45 +00002736 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002737 if (OpName.empty())
2738 error("'?' argument requires a name to match with operand list");
Florian Hahn75e87c32018-05-30 21:00:18 +00002739 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen99ffcc82013-03-24 19:37:00 +00002740 Args.push_back(OpName);
2741 Res->setName(OpName);
2742 return Res;
2743 }
2744
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002745 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002746 if (!OpName.empty())
Nicolai Haehnleab390f02018-06-04 14:45:12 +00002747 error("Constant int or bit argument should not have a name!");
2748 if (isa<BitInit>(TheInit))
2749 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2750 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002751 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002752
Sean Silvafb509ed2012-10-10 20:24:43 +00002753 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002754 // Turn this into an IntInit.
David Greeneaf8ee2c2011-07-29 22:43:06 +00002755 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper24064772014-04-15 07:20:03 +00002756 if (!II || !isa<IntInit>(II))
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002757 error("Bits value must be constants!");
Chris Lattner2e9eae12010-03-28 06:57:56 +00002758 return ParseTreePattern(II, OpName);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002759 }
2760
Sean Silvafb509ed2012-10-10 20:24:43 +00002761 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002762 if (!Dag) {
Matthias Braun8c209aa2017-01-28 02:02:38 +00002763 TheInit->print(errs());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002764 error("Pattern has unexpected init kind!");
2765 }
Sean Silvafb509ed2012-10-10 20:24:43 +00002766 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00002767 if (!OpDef) error("Pattern has unexpected operator type!");
2768 Record *Operator = OpDef->getDef();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002769
Chris Lattner8cab0212008-01-05 22:25:12 +00002770 if (Operator->isSubClassOf("ValueType")) {
2771 // If the operator is a ValueType, then this must be "type cast" of a leaf
2772 // node.
2773 if (Dag->getNumArgs() != 1)
2774 error("Type cast only takes one operand!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002775
Florian Hahn75e87c32018-05-30 21:00:18 +00002776 TreePatternNodePtr New =
2777 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002778
Chris Lattner8cab0212008-01-05 22:25:12 +00002779 // Apply the type cast.
Chris Lattnerf1447252010-03-19 21:37:09 +00002780 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002781 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2782 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002783
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002784 if (!OpName.empty())
2785 error("ValueType cast should not have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00002786 return New;
2787 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002788
Chris Lattner8cab0212008-01-05 22:25:12 +00002789 // Verify that this is something that makes sense for an operator.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00002790 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begemandbe3f772009-03-19 05:21:56 +00002791 !Operator->isSubClassOf("SDNode") &&
Jim Grosbach65586fe2010-12-21 16:16:00 +00002792 !Operator->isSubClassOf("Instruction") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002793 !Operator->isSubClassOf("SDNodeXForm") &&
2794 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoverc807a172014-05-20 11:52:46 +00002795 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner8cab0212008-01-05 22:25:12 +00002796 Operator->getName() != "set" &&
Chris Lattner5c2182e2010-03-27 02:53:27 +00002797 Operator->getName() != "implicit")
Chris Lattner8cab0212008-01-05 22:25:12 +00002798 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002799
Chris Lattner8cab0212008-01-05 22:25:12 +00002800 // Check to see if this is something that is illegal in an input pattern.
Chris Lattner2e9eae12010-03-28 06:57:56 +00002801 if (isInputPattern) {
2802 if (Operator->isSubClassOf("Instruction") ||
2803 Operator->isSubClassOf("SDNodeXForm"))
2804 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2805 } else {
2806 if (Operator->isSubClassOf("Intrinsic"))
2807 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002808
Chris Lattner2e9eae12010-03-28 06:57:56 +00002809 if (Operator->isSubClassOf("SDNode") &&
2810 Operator->getName() != "imm" &&
Craig Topper80fda372019-09-22 19:49:39 +00002811 Operator->getName() != "timm" &&
Chris Lattner2e9eae12010-03-28 06:57:56 +00002812 Operator->getName() != "fpimm" &&
2813 Operator->getName() != "tglobaltlsaddr" &&
2814 Operator->getName() != "tconstpool" &&
2815 Operator->getName() != "tjumptable" &&
2816 Operator->getName() != "tframeindex" &&
2817 Operator->getName() != "texternalsym" &&
2818 Operator->getName() != "tblockaddress" &&
2819 Operator->getName() != "tglobaladdr" &&
2820 Operator->getName() != "bb" &&
Rafael Espindola36b718f2015-06-22 17:46:53 +00002821 Operator->getName() != "vt" &&
2822 Operator->getName() != "mcsym")
Chris Lattner2e9eae12010-03-28 06:57:56 +00002823 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2824 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002825
Florian Hahn75e87c32018-05-30 21:00:18 +00002826 std::vector<TreePatternNodePtr> Children;
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002827
2828 // Parse all the operands.
2829 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunbb053162016-12-05 06:00:46 +00002830 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbach65586fe2010-12-21 16:16:00 +00002831
Hal Finkel8b4bdfdb2018-01-03 11:35:09 +00002832 // Get the actual number of results before Operator is converted to an intrinsic
2833 // node (which is hard-coded to have either zero or one result).
2834 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2835
Fangrui Song956ee792018-03-30 22:22:31 +00002836 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbach65586fe2010-12-21 16:16:00 +00002837 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner8cab0212008-01-05 22:25:12 +00002838 // convert the intrinsic name to a number.
2839 if (Operator->isSubClassOf("Intrinsic")) {
2840 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2841 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2842
2843 // If this intrinsic returns void, it must have side-effects and thus a
2844 // chain.
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002845 if (Int.IS.RetVTs.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00002846 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Momchil Velikov52c39392019-07-17 10:53:13 +00002847 else if (Int.ModRef != CodeGenIntrinsic::NoMem || Int.hasSideEffects)
Chris Lattner8cab0212008-01-05 22:25:12 +00002848 // Has side-effects, requires chain.
2849 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002850 else // Otherwise, no chain.
Chris Lattner8cab0212008-01-05 22:25:12 +00002851 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbach65586fe2010-12-21 16:16:00 +00002852
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002853 Children.insert(Children.begin(),
2854 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner8cab0212008-01-05 22:25:12 +00002855 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002856
Tim Northoverc807a172014-05-20 11:52:46 +00002857 if (Operator->isSubClassOf("ComplexPattern")) {
2858 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00002859 TreePatternNodePtr Child = Children[i];
Tim Northoverc807a172014-05-20 11:52:46 +00002860
2861 if (Child->getName().empty())
2862 error("All arguments to a ComplexPattern must be named");
2863
2864 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2865 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2866 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2867 auto OperandId = std::make_pair(Operator, i);
2868 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2869 if (PrevOp != ComplexPatternOperands.end()) {
2870 if (PrevOp->getValue() != OperandId)
2871 error("All ComplexPattern operands must appear consistently: "
2872 "in the same order in just one ComplexPattern instance.");
2873 } else
2874 ComplexPatternOperands[Child->getName()] = OperandId;
2875 }
2876 }
2877
Florian Hahn6b1db822018-06-14 20:32:58 +00002878 TreePatternNodePtr Result =
Craig Topper26fc06352018-07-15 06:52:49 +00002879 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2880 NumResults);
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002881 Result->setName(OpName);
Jim Grosbach65586fe2010-12-21 16:16:00 +00002882
Matthias Braun7cf3b112016-12-05 06:00:41 +00002883 if (Dag->getName()) {
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002884 assert(Result->getName().empty());
Matthias Braun7cf3b112016-12-05 06:00:41 +00002885 Result->setName(Dag->getNameStr());
Chris Lattneradf7ecf2010-03-28 06:50:34 +00002886 }
Nate Begemandbe3f772009-03-19 05:21:56 +00002887 return Result;
Chris Lattner8cab0212008-01-05 22:25:12 +00002888}
2889
Chris Lattnera787c9e2010-03-28 08:38:32 +00002890/// SimplifyTree - See if we can simplify this tree to eliminate something that
2891/// will never match in favor of something obvious that will. This is here
2892/// strictly as a convenience to target authors because it allows them to write
2893/// more type generic things and have useless type casts fold away.
2894///
2895/// This returns true if any change is made.
Florian Hahn75e87c32018-05-30 21:00:18 +00002896static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattnera787c9e2010-03-28 08:38:32 +00002897 if (N->isLeaf())
2898 return false;
2899
2900 // If we have a bitconvert with a resolved type and if the source and
2901 // destination types are the same, then the bitconvert is useless, remove it.
2902 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002903 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn6b1db822018-06-14 20:32:58 +00002904 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattnera787c9e2010-03-28 08:38:32 +00002905 N->getName().empty()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002906 N = N->getChildShared(0);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002907 SimplifyTree(N);
2908 return true;
2909 }
2910
2911 // Walk all children.
2912 bool MadeChange = false;
2913 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn75e87c32018-05-30 21:00:18 +00002914 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002915 MadeChange |= SimplifyTree(Child);
Florian Hahn0a2e0b62018-06-14 11:56:19 +00002916 N->setChild(i, std::move(Child));
Chris Lattnera787c9e2010-03-28 08:38:32 +00002917 }
2918 return MadeChange;
2919}
2920
2921
2922
Chris Lattner8cab0212008-01-05 22:25:12 +00002923/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbach975c1cb2009-03-26 16:17:51 +00002924/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00002925/// otherwise. Flags an error if a type contradiction is found.
Chris Lattnercabe0372010-03-15 06:00:16 +00002926bool TreePattern::
2927InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2928 if (NamedNodes.empty())
2929 ComputeNamedNodes();
2930
Chris Lattner8cab0212008-01-05 22:25:12 +00002931 bool MadeChange = true;
2932 while (MadeChange) {
2933 MadeChange = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002934 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper306cb122015-11-22 20:46:24 +00002935 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2936 MadeChange |= SimplifyTree(Tree);
Chris Lattnera787c9e2010-03-28 08:38:32 +00002937 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002938
2939 // If there are constraints on our named nodes, apply them.
Craig Topper306cb122015-11-22 20:46:24 +00002940 for (auto &Entry : NamedNodes) {
2941 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbach65586fe2010-12-21 16:16:00 +00002942
Chris Lattnercabe0372010-03-15 06:00:16 +00002943 // If we have input named node types, propagate their types to the named
2944 // values here.
2945 if (InNamedTypes) {
Craig Topper306cb122015-11-22 20:46:24 +00002946 if (!InNamedTypes->count(Entry.getKey())) {
2947 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbach37b80932014-07-09 18:55:49 +00002948 "' in output pattern but not input pattern");
2949 return true;
2950 }
Chris Lattnercabe0372010-03-15 06:00:16 +00002951
2952 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper306cb122015-11-22 20:46:24 +00002953 InNamedTypes->find(Entry.getKey())->second;
Chris Lattnercabe0372010-03-15 06:00:16 +00002954
2955 // The input types should be fully resolved by now.
Craig Topper306cb122015-11-22 20:46:24 +00002956 for (TreePatternNode *Node : Nodes) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002957 // If this node is a register class, and it is the root of the pattern
2958 // then we're mapping something onto an input register. We allow
2959 // changing the type of the input register in this case. This allows
2960 // us to match things like:
2961 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn75e87c32018-05-30 21:00:18 +00002962 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper306cb122015-11-22 20:46:24 +00002963 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00002964 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2965 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattnercabe0372010-03-15 06:00:16 +00002966 continue;
2967 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002968
Craig Topper306cb122015-11-22 20:46:24 +00002969 assert(Node->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002970 InNodes[0]->getNumTypes() == 1 &&
2971 "FIXME: cannot name multiple result nodes yet");
Craig Topper306cb122015-11-22 20:46:24 +00002972 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2973 *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002974 }
2975 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002976
Chris Lattnercabe0372010-03-15 06:00:16 +00002977 // If there are multiple nodes with the same name, they must all have the
2978 // same type.
Craig Topper306cb122015-11-22 20:46:24 +00002979 if (Entry.second.size() > 1) {
Chris Lattnercabe0372010-03-15 06:00:16 +00002980 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerf1447252010-03-19 21:37:09 +00002981 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbard177edf2010-03-21 01:38:21 +00002982 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerf1447252010-03-19 21:37:09 +00002983 "FIXME: cannot name multiple result nodes yet");
Jim Grosbach65586fe2010-12-21 16:16:00 +00002984
Chris Lattnerf1447252010-03-19 21:37:09 +00002985 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2986 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattnercabe0372010-03-15 06:00:16 +00002987 }
2988 }
2989 }
Chris Lattner8cab0212008-01-05 22:25:12 +00002990 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00002991
Chris Lattner8cab0212008-01-05 22:25:12 +00002992 bool HasUnresolvedTypes = false;
Florian Hahn75e87c32018-05-30 21:00:18 +00002993 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00002994 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner8cab0212008-01-05 22:25:12 +00002995 return !HasUnresolvedTypes;
2996}
2997
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00002998void TreePattern::print(raw_ostream &OS) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00002999 OS << getRecord()->getName();
3000 if (!Args.empty()) {
3001 OS << "(" << Args[0];
3002 for (unsigned i = 1, e = Args.size(); i != e; ++i)
3003 OS << ", " << Args[i];
3004 OS << ")";
3005 }
3006 OS << ": ";
Jim Grosbach65586fe2010-12-21 16:16:00 +00003007
Chris Lattner8cab0212008-01-05 22:25:12 +00003008 if (Trees.size() > 1)
3009 OS << "[\n";
Florian Hahn75e87c32018-05-30 21:00:18 +00003010 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003011 OS << "\t";
Craig Topper306cb122015-11-22 20:46:24 +00003012 Tree->print(OS);
Chris Lattner8cab0212008-01-05 22:25:12 +00003013 OS << "\n";
3014 }
3015
3016 if (Trees.size() > 1)
3017 OS << "]\n";
3018}
3019
Daniel Dunbar38a22bf2009-07-03 00:10:29 +00003020void TreePattern::dump() const { print(errs()); }
Chris Lattner8cab0212008-01-05 22:25:12 +00003021
3022//===----------------------------------------------------------------------===//
Chris Lattnerab3242f2008-01-06 01:10:31 +00003023// CodeGenDAGPatterns implementation
Chris Lattner8cab0212008-01-05 22:25:12 +00003024//
3025
Daniel Sanders7e523672017-11-11 03:23:44 +00003026CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
3027 PatternRewriterFn PatternRewriter)
3028 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
3029 PatternRewriter(PatternRewriter) {
Chris Lattner77d369c2010-12-13 00:23:57 +00003030
Justin Bogner92a8c612016-07-15 16:31:37 +00003031 Intrinsics = CodeGenIntrinsicTable(Records, false);
3032 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner8cab0212008-01-05 22:25:12 +00003033 ParseNodeInfo();
Chris Lattnercc43e792008-01-05 22:54:53 +00003034 ParseNodeTransforms();
Chris Lattner8cab0212008-01-05 22:25:12 +00003035 ParseComplexPatterns();
Chris Lattnere7170df2008-01-05 22:43:57 +00003036 ParsePatternFragments();
Chris Lattner8cab0212008-01-05 22:25:12 +00003037 ParseDefaultOperands();
3038 ParseInstructions();
Hal Finkel2756dc12014-02-28 00:26:56 +00003039 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner8cab0212008-01-05 22:25:12 +00003040 ParsePatterns();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003041
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003042 // Break patterns with parameterized types into a series of patterns,
3043 // where each one has a fixed type and is predicated on the conditions
3044 // of the associated HW mode.
3045 ExpandHwModeBasedTypes();
3046
Chris Lattner8cab0212008-01-05 22:25:12 +00003047 // Generate variants. For example, commutative patterns can match
3048 // multiple ways. Add them to PatternsToMatch as well.
3049 GenerateVariants();
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003050
3051 // Infer instruction flags. For example, we can detect loads,
3052 // stores, and side effects in many cases by examining an
3053 // instruction's pattern.
3054 InferInstructionFlags();
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003055
3056 // Verify that instruction flags match the patterns.
3057 VerifyInstructionFlags();
Chris Lattner8cab0212008-01-05 22:25:12 +00003058}
3059
Daniel Sanders9e0ae7b2017-10-13 19:00:01 +00003060Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner8cab0212008-01-05 22:25:12 +00003061 Record *N = Records.getDef(Name);
James Y Knighte452e272015-05-11 22:17:13 +00003062 if (!N || !N->isSubClassOf("SDNode"))
3063 PrintFatalError("Error getting SDNode '" + Name + "'!");
3064
Chris Lattner8cab0212008-01-05 22:25:12 +00003065 return N;
3066}
3067
3068// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003069void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003070 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003071 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3072
Chris Lattner8cab0212008-01-05 22:25:12 +00003073 while (!Nodes.empty()) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003074 Record *R = Nodes.back();
3075 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner8cab0212008-01-05 22:25:12 +00003076 Nodes.pop_back();
3077 }
3078
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003079 // Get the builtin intrinsic nodes.
Chris Lattner8cab0212008-01-05 22:25:12 +00003080 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
3081 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
3082 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
3083}
3084
3085/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3086/// map, and emit them to the file as functions.
Chris Lattnerab3242f2008-01-06 01:10:31 +00003087void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003088 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
3089 while (!Xforms.empty()) {
3090 Record *XFormNode = Xforms.back();
3091 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topperbcd3c372017-05-31 21:12:46 +00003092 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattnercc43e792008-01-05 22:54:53 +00003093 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner8cab0212008-01-05 22:25:12 +00003094
3095 Xforms.pop_back();
3096 }
3097}
3098
Chris Lattnerab3242f2008-01-06 01:10:31 +00003099void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00003100 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3101 while (!AMs.empty()) {
3102 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3103 AMs.pop_back();
3104 }
3105}
3106
3107
3108/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3109/// file, building up the PatternFragments map. After we've collected them all,
3110/// inline fragments together as necessary, so that there are no references left
3111/// inside a pattern fragment to a pattern fragment.
3112///
Hal Finkel2756dc12014-02-28 00:26:56 +00003113void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003114 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003115
Chris Lattnere7170df2008-01-05 22:43:57 +00003116 // First step, parse all of the fragments.
Craig Topper306cb122015-11-22 20:46:24 +00003117 for (Record *Frag : Fragments) {
3118 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003119 continue;
3120
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003121 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkel2756dc12014-02-28 00:26:56 +00003122 TreePattern *P =
Jonas Devlieghere0eaee542019-08-15 15:54:37 +00003123 (PatternFragments[Frag] = std::make_unique<TreePattern>(
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003124 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikie3c6ca232014-11-13 21:40:02 +00003125 *this)).get();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003126
Chris Lattnere7170df2008-01-05 22:43:57 +00003127 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner8cab0212008-01-05 22:25:12 +00003128 std::vector<std::string> &Args = P->getArgList();
Zachary Turner249dc142017-09-20 18:01:40 +00003129 // Copy the args so we can take StringRefs to them.
3130 auto ArgsCopy = Args;
3131 SmallDenseSet<StringRef, 4> OperandsSet;
3132 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbach65586fe2010-12-21 16:16:00 +00003133
Chris Lattnere7170df2008-01-05 22:43:57 +00003134 if (OperandsSet.count(""))
Chris Lattner8cab0212008-01-05 22:25:12 +00003135 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003136
Chris Lattner8cab0212008-01-05 22:25:12 +00003137 // Parse the operands list.
Craig Topper306cb122015-11-22 20:46:24 +00003138 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silvafb509ed2012-10-10 20:24:43 +00003139 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner8cab0212008-01-05 22:25:12 +00003140 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbach975c1cb2009-03-26 16:17:51 +00003141 // improve readability.
Chris Lattner8cab0212008-01-05 22:25:12 +00003142 if (!OpsOp ||
3143 (OpsOp->getDef()->getName() != "ops" &&
3144 OpsOp->getDef()->getName() != "outs" &&
3145 OpsOp->getDef()->getName() != "ins"))
3146 P->error("Operands list should start with '(ops ... '!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003147
3148 // Copy over the arguments.
Chris Lattner8cab0212008-01-05 22:25:12 +00003149 Args.clear();
3150 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003151 if (!isa<DefInit>(OpsList->getArg(j)) ||
3152 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner8cab0212008-01-05 22:25:12 +00003153 P->error("Operands list should all be 'node' values.");
Matthias Braunbb053162016-12-05 06:00:46 +00003154 if (!OpsList->getArgName(j))
Chris Lattner8cab0212008-01-05 22:25:12 +00003155 P->error("Operands list should have names for each operand!");
Matthias Braunbb053162016-12-05 06:00:46 +00003156 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3157 if (!OperandsSet.count(ArgNameStr))
3158 P->error("'" + ArgNameStr +
Chris Lattner8cab0212008-01-05 22:25:12 +00003159 "' does not occur in pattern or was multiply specified!");
Matthias Braunbb053162016-12-05 06:00:46 +00003160 OperandsSet.erase(ArgNameStr);
3161 Args.push_back(ArgNameStr);
Chris Lattner8cab0212008-01-05 22:25:12 +00003162 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003163
Chris Lattnere7170df2008-01-05 22:43:57 +00003164 if (!OperandsSet.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00003165 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnere7170df2008-01-05 22:43:57 +00003166 *OperandsSet.begin() + "'!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003167
Chris Lattner8cab0212008-01-05 22:25:12 +00003168 // If there is a node transformation corresponding to this, keep track of
3169 // it.
Craig Topper306cb122015-11-22 20:46:24 +00003170 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner8cab0212008-01-05 22:25:12 +00003171 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003172 for (auto T : P->getTrees())
3173 T->setTransformFn(Transform);
Chris Lattner8cab0212008-01-05 22:25:12 +00003174 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003175
Chris Lattner8cab0212008-01-05 22:25:12 +00003176 // Now that we've parsed all of the tree fragments, do a closure on them so
3177 // that there are not references to PatFrags left inside of them.
Craig Topper306cb122015-11-22 20:46:24 +00003178 for (Record *Frag : Fragments) {
3179 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkel2756dc12014-02-28 00:26:56 +00003180 continue;
3181
Craig Topper306cb122015-11-22 20:46:24 +00003182 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikie3c6ca232014-11-13 21:40:02 +00003183 ThePat.InlinePatternFragments();
Jim Grosbach65586fe2010-12-21 16:16:00 +00003184
Chris Lattner8cab0212008-01-05 22:25:12 +00003185 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigand22b1af82018-07-13 16:42:15 +00003186 // all of them, some may depend on the inputs of the pattern. Also, don't
3187 // validate type sets; validation may cause spurious failures e.g. if a
3188 // fragment needs floating-point types but the current target does not have
3189 // any (this is only an error if that fragment is ever used!).
3190 {
3191 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3192 ThePat.InferAllTypes();
3193 ThePat.resetError();
3194 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003195
Chris Lattner8cab0212008-01-05 22:25:12 +00003196 // If debugging, print out the pattern fragment result.
Nicola Zaghend34e60c2018-05-14 12:53:11 +00003197 LLVM_DEBUG(ThePat.dump());
Chris Lattner8cab0212008-01-05 22:25:12 +00003198 }
3199}
3200
Chris Lattnerab3242f2008-01-06 01:10:31 +00003201void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellardb7246a72012-09-06 14:15:52 +00003202 std::vector<Record*> DefaultOps;
3203 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner8cab0212008-01-05 22:25:12 +00003204
3205 // Find some SDNode.
3206 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greeneaf8ee2c2011-07-29 22:43:06 +00003207 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003208
Tom Stellardb7246a72012-09-06 14:15:52 +00003209 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3210 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003211
Tom Stellardb7246a72012-09-06 14:15:52 +00003212 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3213 // SomeSDnode so that we can parse this.
Matthias Braunbb053162016-12-05 06:00:46 +00003214 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellardb7246a72012-09-06 14:15:52 +00003215 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3216 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3217 DefaultInfo->getArgName(op)));
Matthias Braun7cf3b112016-12-05 06:00:41 +00003218 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003219
Tom Stellardb7246a72012-09-06 14:15:52 +00003220 // Create a TreePattern to parse this.
3221 TreePattern P(DefaultOps[i], DI, false, *this);
3222 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003223
Tom Stellardb7246a72012-09-06 14:15:52 +00003224 // Copy the operands over into a DAGDefaultOperand.
3225 DAGDefaultOperand DefaultOpInfo;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003226
Florian Hahn75e87c32018-05-30 21:00:18 +00003227 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellardb7246a72012-09-06 14:15:52 +00003228 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn75e87c32018-05-30 21:00:18 +00003229 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellardb7246a72012-09-06 14:15:52 +00003230 while (TPN->ApplyTypeConstraints(P, false))
3231 /* Resolve all types */;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003232
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003233 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramer48e7e852014-03-29 17:17:15 +00003234 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3235 DefaultOps[i]->getName() +
3236 "' doesn't have a concrete type!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003237 }
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003238 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner8cab0212008-01-05 22:25:12 +00003239 }
Tom Stellardb7246a72012-09-06 14:15:52 +00003240
3241 // Insert it into the DefaultOperands map so we can find it later.
3242 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner8cab0212008-01-05 22:25:12 +00003243 }
3244}
3245
3246/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3247/// instruction input. Return true if this is a real use.
David Blaikie19b22d42018-06-11 22:14:43 +00003248static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003249 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003250 // No name -> not interesting.
3251 if (Pat->getName().empty()) {
3252 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003253 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersona84be6c2011-06-27 21:06:21 +00003254 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3255 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie19b22d42018-06-11 22:14:43 +00003256 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003257 }
3258 return false;
3259 }
3260
3261 Record *Rec;
3262 if (Pat->isLeaf()) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003263 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie19b22d42018-06-11 22:14:43 +00003264 if (!DI)
3265 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003266 Rec = DI->getDef();
3267 } else {
Chris Lattner8cab0212008-01-05 22:25:12 +00003268 Rec = Pat->getOperator();
3269 }
3270
3271 // SRCVALUE nodes are ignored.
3272 if (Rec->getName() == "srcvalue")
3273 return false;
3274
Florian Hahn75e87c32018-05-30 21:00:18 +00003275 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner8cab0212008-01-05 22:25:12 +00003276 if (!Slot) {
3277 Slot = Pat;
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003278 return true;
Chris Lattner8cab0212008-01-05 22:25:12 +00003279 }
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003280 Record *SlotRec;
3281 if (Slot->isLeaf()) {
Sean Silva88eb8dd2012-10-10 20:24:47 +00003282 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003283 } else {
3284 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3285 SlotRec = Slot->getOperator();
3286 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003287
Chris Lattnerf66b6aa2010-02-23 05:59:10 +00003288 // Ensure that the inputs agree if we've already seen this input.
3289 if (Rec != SlotRec)
David Blaikie19b22d42018-06-11 22:14:43 +00003290 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003291 // Ensure that the types can agree as well.
3292 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3293 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerf1447252010-03-19 21:37:09 +00003294 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie19b22d42018-06-11 22:14:43 +00003295 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner8cab0212008-01-05 22:25:12 +00003296 return true;
3297}
3298
3299/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3300/// part of "I", the instruction), computing the set of inputs and outputs of
3301/// the pattern. Report errors if we see anything naughty.
Florian Hahn75e87c32018-05-30 21:00:18 +00003302void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn6b1db822018-06-14 20:32:58 +00003303 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn75e87c32018-05-30 21:00:18 +00003304 std::map<std::string, TreePatternNodePtr> &InstInputs,
Craig Topperbd199f82018-12-05 00:47:59 +00003305 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3306 &InstResults,
Florian Hahn75e87c32018-05-30 21:00:18 +00003307 std::vector<Record *> &InstImpResults) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003308
3309 // The instruction pattern still has unresolved fragments. For *named*
3310 // nodes we must resolve those here. This may not result in multiple
3311 // alternatives.
3312 if (!Pat->getName().empty()) {
3313 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3314 SrcPattern.InlinePatternFragments();
3315 SrcPattern.InferAllTypes();
3316 Pat = SrcPattern.getOnlyTree();
3317 }
3318
Chris Lattner8cab0212008-01-05 22:25:12 +00003319 if (Pat->isLeaf()) {
Chris Lattner5debc332010-04-20 06:30:25 +00003320 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner8cab0212008-01-05 22:25:12 +00003321 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003322 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003323 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003324 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003325
Chris Lattnerf2d70992010-02-17 06:53:36 +00003326 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003327 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003328 TreePatternNode *Dest = Pat->getChild(i);
3329 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003330 I.error("implicitly defined value should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003331
Florian Hahn6b1db822018-06-14 20:32:58 +00003332 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner8cab0212008-01-05 22:25:12 +00003333 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie19b22d42018-06-11 22:14:43 +00003334 I.error("implicitly defined value should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003335 InstImpResults.push_back(Val->getDef());
3336 }
3337 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003338 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003339
Chris Lattnerf2d70992010-02-17 06:53:36 +00003340 if (Pat->getOperator()->getName() != "set") {
Chris Lattner8cab0212008-01-05 22:25:12 +00003341 // If this is not a set, verify that the children nodes are not void typed,
3342 // and recurse.
3343 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003344 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003345 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn75e87c32018-05-30 21:00:18 +00003346 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3347 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003348 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003349
Chris Lattner8cab0212008-01-05 22:25:12 +00003350 // If this is a non-leaf node with no children, treat it basically as if
3351 // it were a leaf. This handles nodes like (imm).
Chris Lattner5debc332010-04-20 06:30:25 +00003352 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003353
Chris Lattner8cab0212008-01-05 22:25:12 +00003354 if (!isUse && Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003355 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003356 return;
Chris Lattnerf2d70992010-02-17 06:53:36 +00003357 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003358
Chris Lattner8cab0212008-01-05 22:25:12 +00003359 // Otherwise, this is a set, validate and collect instruction results.
3360 if (Pat->getNumChildren() == 0)
David Blaikie19b22d42018-06-11 22:14:43 +00003361 I.error("set requires operands!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003362
Chris Lattner8cab0212008-01-05 22:25:12 +00003363 if (Pat->getTransformFn())
David Blaikie19b22d42018-06-11 22:14:43 +00003364 I.error("Cannot specify a transform function on a set node!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003365
Chris Lattner8cab0212008-01-05 22:25:12 +00003366 // Check the set destinations.
3367 unsigned NumDests = Pat->getNumChildren()-1;
3368 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003369 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003370 // For set destinations we also must resolve fragments here.
3371 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3372 DestPattern.InlinePatternFragments();
3373 DestPattern.InferAllTypes();
3374 Dest = DestPattern.getOnlyTree();
3375
Chris Lattner8cab0212008-01-05 22:25:12 +00003376 if (!Dest->isLeaf())
David Blaikie19b22d42018-06-11 22:14:43 +00003377 I.error("set destination should be a register!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003378
Sean Silvafb509ed2012-10-10 20:24:43 +00003379 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman5be22a12014-12-12 21:48:03 +00003380 if (!Val) {
David Blaikie19b22d42018-06-11 22:14:43 +00003381 I.error("set destination should be a register!");
Michael Ilseman5be22a12014-12-12 21:48:03 +00003382 continue;
3383 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003384
3385 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003386 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersona84be6c2011-06-27 21:06:21 +00003387 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattner426bc7c2009-07-29 20:43:05 +00003388 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00003389 if (Dest->getName().empty())
David Blaikie19b22d42018-06-11 22:14:43 +00003390 I.error("set destination must have a name!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003391 if (InstResults.count(Dest->getName()))
David Blaikie19b22d42018-06-11 22:14:43 +00003392 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner8cab0212008-01-05 22:25:12 +00003393 InstResults[Dest->getName()] = Dest;
3394 } else if (Val->getDef()->isSubClassOf("Register")) {
3395 InstImpResults.push_back(Val->getDef());
3396 } else {
David Blaikie19b22d42018-06-11 22:14:43 +00003397 I.error("set destination should be a register!");
Chris Lattner8cab0212008-01-05 22:25:12 +00003398 }
3399 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003400
Chris Lattner8cab0212008-01-05 22:25:12 +00003401 // Verify and collect info from the computation.
Florian Hahn75e87c32018-05-30 21:00:18 +00003402 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3403 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00003404}
3405
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003406//===----------------------------------------------------------------------===//
3407// Instruction Analysis
3408//===----------------------------------------------------------------------===//
3409
3410class InstAnalyzer {
3411 const CodeGenDAGPatterns &CDP;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003412public:
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003413 bool hasSideEffects;
3414 bool mayStore;
3415 bool mayLoad;
3416 bool isBitcast;
3417 bool isVariadic;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003418 bool hasChain;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003419
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003420 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3421 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003422 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003423
Craig Topper2a053a92017-06-20 16:34:37 +00003424 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003425 const TreePatternNode *N = Pat.getSrcPattern();
3426 AnalyzeNode(N);
3427 // These properties are detected only on the root node.
3428 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003429 }
3430
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003431private:
Florian Hahn6b1db822018-06-14 20:32:58 +00003432 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003433 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng880e299d2011-03-15 05:09:26 +00003434 return false;
3435
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003436 if (N->isLeaf())
3437 return false;
3438 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng880e299d2011-03-15 05:09:26 +00003439 return false;
3440
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003441 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng880e299d2011-03-15 05:09:26 +00003442 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3443 return false;
3444 return OpInfo.getEnumName() == "ISD::BITCAST";
3445 }
3446
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003447public:
Florian Hahn6b1db822018-06-14 20:32:58 +00003448 void AnalyzeNode(const TreePatternNode *N) {
3449 if (N->isLeaf()) {
3450 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003451 Record *LeafRec = DI->getDef();
3452 // Handle ComplexPattern leaves.
3453 if (LeafRec->isSubClassOf("ComplexPattern")) {
3454 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3455 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3456 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003457 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003458 }
3459 }
3460 return;
3461 }
3462
3463 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00003464 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3465 AnalyzeNode(N->getChild(i));
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003466
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003467 // Notice properties of the node.
Florian Hahn6b1db822018-06-14 20:32:58 +00003468 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3469 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3470 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3471 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003472 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003473
Florian Hahn6b1db822018-06-14 20:32:58 +00003474 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003475 // If this is an intrinsic, analyze it.
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003476 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003477 mayLoad = true;// These may load memory.
3478
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003479 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003480 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3481
Matt Arsenault868af922017-04-28 21:01:46 +00003482 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3483 IntInfo->hasSideEffects)
Nicolai Haehnleb48275f2016-04-19 21:58:33 +00003484 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003485 hasSideEffects = true;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003486 }
3487 }
3488
3489};
3490
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003491static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003492 const InstAnalyzer &PatInfo,
3493 Record *PatDef) {
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003494 bool Error = false;
3495
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003496 // Remember where InstInfo got its flags.
3497 if (InstInfo.hasUndefFlags())
3498 InstInfo.InferredFrom = PatDef;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003499
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003500 // Check explicitly set flags for consistency.
3501 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3502 !InstInfo.hasSideEffects_Unset) {
3503 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3504 // the pattern has no side effects. That could be useful for div/rem
3505 // instructions that may trap.
3506 if (!InstInfo.hasSideEffects) {
3507 Error = true;
3508 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3509 Twine(InstInfo.hasSideEffects));
3510 }
3511 }
3512
3513 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3514 Error = true;
3515 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3516 Twine(InstInfo.mayStore));
3517 }
3518
3519 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3520 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00003521 // Some targets translate immediates to loads.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003522 if (!InstInfo.mayLoad) {
3523 Error = true;
3524 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3525 Twine(InstInfo.mayLoad));
3526 }
3527 }
3528
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003529 // Transfer inferred flags.
3530 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3531 InstInfo.mayStore |= PatInfo.mayStore;
3532 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003533
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003534 // These flags are silently added without any verification.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003535 // FIXME: To match historical behavior of TableGen, for now add those flags
3536 // only when we're inferring from the primary instruction pattern.
3537 if (PatDef->isSubClassOf("Instruction")) {
3538 InstInfo.isBitcast |= PatInfo.isBitcast;
3539 InstInfo.hasChain |= PatInfo.hasChain;
3540 InstInfo.hasChain_Inferred = true;
3541 }
Jakob Stoklund Olesenf5dc1bc2012-08-24 21:08:09 +00003542
3543 // Don't infer isVariadic. This flag means something different on SDNodes and
3544 // instructions. For example, a CALL SDNode is variadic because it has the
3545 // call arguments as operands, but a CALL instruction is not variadic - it
3546 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003547
3548 return Error;
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003549}
3550
Jim Grosbach514410b2012-07-17 00:47:06 +00003551/// hasNullFragReference - Return true if the DAG has any reference to the
3552/// null_frag operator.
3553static bool hasNullFragReference(DagInit *DI) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003554 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbach514410b2012-07-17 00:47:06 +00003555 if (!OpDef) return false;
3556 Record *Operator = OpDef->getDef();
3557
3558 // If this is the null fragment, return true.
3559 if (Operator->getName() == "null_frag") return true;
3560 // If any of the arguments reference the null fragment, return true.
3561 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silvafb509ed2012-10-10 20:24:43 +00003562 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbach514410b2012-07-17 00:47:06 +00003563 if (Arg && hasNullFragReference(Arg))
3564 return true;
3565 }
3566
3567 return false;
3568}
3569
3570/// hasNullFragReference - Return true if any DAG in the list references
3571/// the null_frag operator.
3572static bool hasNullFragReference(ListInit *LI) {
Craig Topperef0578a2015-06-02 04:15:51 +00003573 for (Init *I : LI->getValues()) {
3574 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbach514410b2012-07-17 00:47:06 +00003575 assert(DI && "non-dag in an instruction Pattern list?!");
3576 if (hasNullFragReference(DI))
3577 return true;
3578 }
3579 return false;
3580}
3581
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003582/// Get all the instructions in a tree.
3583static void
Florian Hahn6b1db822018-06-14 20:32:58 +00003584getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3585 if (Tree->isLeaf())
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003586 return;
Florian Hahn6b1db822018-06-14 20:32:58 +00003587 if (Tree->getOperator()->isSubClassOf("Instruction"))
3588 Instrs.push_back(Tree->getOperator());
3589 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3590 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003591}
3592
Jakob Stoklund Olesen04b0f912013-03-24 00:56:16 +00003593/// Check the class of a pattern leaf node against the instruction operand it
3594/// represents.
3595static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3596 Record *Leaf) {
3597 if (OI.Rec == Leaf)
3598 return true;
3599
3600 // Allow direct value types to be used in instruction set patterns.
3601 // The type will be checked later.
3602 if (Leaf->isSubClassOf("ValueType"))
3603 return true;
3604
3605 // Patterns can also be ComplexPattern instances.
3606 if (Leaf->isSubClassOf("ComplexPattern"))
3607 return true;
3608
3609 return false;
3610}
3611
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003612void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha14107512013-10-28 18:07:21 +00003613 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00003614
Craig Topper0d1fb902015-03-10 03:25:04 +00003615 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003616
Craig Topper0d1fb902015-03-10 03:25:04 +00003617 // Parse the instruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003618 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003619
Craig Topper0d1fb902015-03-10 03:25:04 +00003620 // InstInputs - Keep track of all of the inputs of the instruction, along
3621 // with the record they are declared as.
Florian Hahn75e87c32018-05-30 21:00:18 +00003622 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003623
Craig Topper0d1fb902015-03-10 03:25:04 +00003624 // InstResults - Keep track of all the virtual registers that are 'set'
3625 // in the instruction, including what reg class they are.
Craig Topperbd199f82018-12-05 00:47:59 +00003626 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3627 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00003628
Craig Topper0d1fb902015-03-10 03:25:04 +00003629 std::vector<Record*> InstImpResults;
Jim Grosbach65586fe2010-12-21 16:16:00 +00003630
Craig Topper0d1fb902015-03-10 03:25:04 +00003631 // Verify that the top-level forms in the instruction are of void type, and
3632 // fill in the InstResults map.
Zachary Turner249dc142017-09-20 18:01:40 +00003633 SmallString<32> TypesString;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003634 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turner249dc142017-09-20 18:01:40 +00003635 TypesString.clear();
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003636 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003637 if (Pat->getNumTypes() != 0) {
Zachary Turner249dc142017-09-20 18:01:40 +00003638 raw_svector_ostream OS(TypesString);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003639 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3640 if (k > 0)
Zachary Turner249dc142017-09-20 18:01:40 +00003641 OS << ", ";
3642 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003643 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003644 I.error("Top-level forms in instruction pattern should have"
Zachary Turner249dc142017-09-20 18:01:40 +00003645 " void types, has types " +
3646 OS.str());
Nicolai Haehnle152c18e2016-04-19 21:58:10 +00003647 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003648
Craig Topper0d1fb902015-03-10 03:25:04 +00003649 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003650 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper0d1fb902015-03-10 03:25:04 +00003651 InstImpResults);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003652 }
3653
Craig Topper0d1fb902015-03-10 03:25:04 +00003654 // Now that we have inputs and outputs of the pattern, inspect the operands
3655 // list for the instruction. This determines the order that operands are
3656 // added to the machine instruction the node corresponds to.
3657 unsigned NumResults = InstResults.size();
3658
3659 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003660 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003661
3662 // Check that all of the results occur first in the list.
3663 std::vector<Record*> Results;
Craig Topperbd199f82018-12-05 00:47:59 +00003664 std::vector<unsigned> ResultIndices;
Florian Hahn75e87c32018-05-30 21:00:18 +00003665 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper0d1fb902015-03-10 03:25:04 +00003666 for (unsigned i = 0; i != NumResults; ++i) {
Craig Topperbd199f82018-12-05 00:47:59 +00003667 if (i == CGI.Operands.size()) {
3668 const std::string &OpName =
3669 std::find_if(InstResults.begin(), InstResults.end(),
3670 [](const std::pair<std::string, TreePatternNodePtr> &P) {
3671 return P.second;
3672 })
3673 ->first;
3674
3675 I.error("'" + OpName + "' set but does not appear in operand list!");
3676 }
3677
Craig Topper0d1fb902015-03-10 03:25:04 +00003678 const std::string &OpName = CGI.Operands[i].Name;
3679
3680 // Check that it exists in InstResults.
Craig Topperbd199f82018-12-05 00:47:59 +00003681 auto InstResultIter = InstResults.find(OpName);
3682 if (InstResultIter == InstResults.end() || !InstResultIter->second)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003683 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003684
Craig Topperbd199f82018-12-05 00:47:59 +00003685 TreePatternNodePtr RNode = InstResultIter->second;
Craig Topper0d1fb902015-03-10 03:25:04 +00003686 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003687 ResNodes.push_back(std::move(RNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003688 if (!R)
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003689 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper0d1fb902015-03-10 03:25:04 +00003690 "outputs must occur before inputs in operand list!");
3691
3692 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003693 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003694
3695 // Remember the return type.
3696 Results.push_back(CGI.Operands[i].Rec);
3697
Craig Topperbd199f82018-12-05 00:47:59 +00003698 // Remember the result index.
3699 ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3700
Craig Topper0d1fb902015-03-10 03:25:04 +00003701 // Okay, this one checks out.
Craig Topperbd199f82018-12-05 00:47:59 +00003702 InstResultIter->second = nullptr;
Craig Topper0d1fb902015-03-10 03:25:04 +00003703 }
3704
Craig Topper765b9202018-07-15 06:52:48 +00003705 // Loop over the inputs next.
Florian Hahn75e87c32018-05-30 21:00:18 +00003706 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper0d1fb902015-03-10 03:25:04 +00003707 std::vector<Record*> Operands;
3708 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3709 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3710 const std::string &OpName = Op.Name;
3711 if (OpName.empty())
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003712 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003713
Craig Topper765b9202018-07-15 06:52:48 +00003714 if (!InstInputs.count(OpName)) {
Craig Topper0d1fb902015-03-10 03:25:04 +00003715 // If this is an operand with a DefaultOps set filled in, we can ignore
3716 // this. When we codegen it, we will do so as always executed.
3717 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3718 // Does it have a non-empty DefaultOps field? If so, ignore this
3719 // operand.
3720 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3721 continue;
3722 }
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003723 I.error("Operand $" + OpName +
Craig Topper0d1fb902015-03-10 03:25:04 +00003724 " does not appear in the instruction pattern");
3725 }
Craig Topper765b9202018-07-15 06:52:48 +00003726 TreePatternNodePtr InVal = InstInputs[OpName];
3727 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper0d1fb902015-03-10 03:25:04 +00003728
3729 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3730 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3731 if (!checkOperandClass(Op, InRec))
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003732 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper0d1fb902015-03-10 03:25:04 +00003733 " between the operand and pattern");
3734 }
3735 Operands.push_back(Op.Rec);
3736
3737 // Construct the result for the dest-pattern operand list.
Florian Hahn75e87c32018-05-30 21:00:18 +00003738 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper0d1fb902015-03-10 03:25:04 +00003739
3740 // No predicate is useful on the result.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00003741 OpNode->clearPredicateCalls();
Craig Topper0d1fb902015-03-10 03:25:04 +00003742
3743 // Promote the xform function to be an explicit node if set.
3744 if (Record *Xform = OpNode->getTransformFn()) {
3745 OpNode->setTransformFn(nullptr);
Florian Hahn75e87c32018-05-30 21:00:18 +00003746 std::vector<TreePatternNodePtr> Children;
Craig Topper0d1fb902015-03-10 03:25:04 +00003747 Children.push_back(OpNode);
Craig Topper26fc06352018-07-15 06:52:49 +00003748 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn6b1db822018-06-14 20:32:58 +00003749 OpNode->getNumTypes());
Craig Topper0d1fb902015-03-10 03:25:04 +00003750 }
3751
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003752 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper0d1fb902015-03-10 03:25:04 +00003753 }
3754
Craig Topper765b9202018-07-15 06:52:48 +00003755 if (!InstInputs.empty())
3756 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003757 " occurs in pattern but not in operands list!");
Craig Topper0d1fb902015-03-10 03:25:04 +00003758
Florian Hahn6b1db822018-06-14 20:32:58 +00003759 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00003760 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003761 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3a8eb892015-03-20 05:09:06 +00003762 // Copy fully inferred output node types to instruction result pattern.
3763 for (unsigned i = 0; i != NumResults; ++i) {
3764 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3765 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
Craig Topperbd199f82018-12-05 00:47:59 +00003766 ResultPattern->setResultIndex(i, ResultIndices[i]);
Craig Topper3a8eb892015-03-20 05:09:06 +00003767 }
Craig Topper0d1fb902015-03-10 03:25:04 +00003768
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003769 // FIXME: Assume only the first tree is the pattern. The others are clobber
3770 // nodes.
3771 TreePatternNodePtr Pattern = I.getTree(0);
3772 TreePatternNodePtr SrcPattern;
3773 if (Pattern->getOperator()->getName() == "set") {
3774 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3775 } else{
3776 // Not a set (store or something?)
3777 SrcPattern = Pattern;
3778 }
3779
Craig Topper0d1fb902015-03-10 03:25:04 +00003780 // Create and insert the instruction.
3781 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003782 Record *R = I.getRecord();
3783 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3784 std::forward_as_tuple(Results, Operands, InstImpResults,
3785 SrcPattern, ResultPattern));
Craig Topper0d1fb902015-03-10 03:25:04 +00003786
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003787 LLVM_DEBUG(I.dump());
Craig Topper0d1fb902015-03-10 03:25:04 +00003788}
3789
Ahmed Bougacha14107512013-10-28 18:07:21 +00003790/// ParseInstructions - Parse all of the instructions, inlining and resolving
3791/// any fragments involved. This populates the Instructions list with fully
3792/// resolved instructions.
3793void CodeGenDAGPatterns::ParseInstructions() {
3794 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3795
Craig Topper306cb122015-11-22 20:46:24 +00003796 for (Record *Instr : Instrs) {
Craig Topper24064772014-04-15 07:20:03 +00003797 ListInit *LI = nullptr;
Ahmed Bougacha14107512013-10-28 18:07:21 +00003798
Craig Topper306cb122015-11-22 20:46:24 +00003799 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3800 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha14107512013-10-28 18:07:21 +00003801
3802 // If there is no pattern, only collect minimal information about the
3803 // instruction for its operand list. We have to assume that there is one
3804 // result, as we have no detailed info. A pattern which references the
3805 // null_frag operator is as-if no pattern were specified. Normally this
3806 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3807 // null_frag.
Craig Topperec9072d2015-05-14 05:53:53 +00003808 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha14107512013-10-28 18:07:21 +00003809 std::vector<Record*> Results;
3810 std::vector<Record*> Operands;
3811
Craig Topper306cb122015-11-22 20:46:24 +00003812 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003813
3814 if (InstInfo.Operands.size() != 0) {
Craig Topper3a8eb892015-03-20 05:09:06 +00003815 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3816 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003817
Craig Topper3a8eb892015-03-20 05:09:06 +00003818 // The rest are inputs.
3819 for (unsigned j = InstInfo.Operands.NumDefs,
3820 e = InstInfo.Operands.size(); j < e; ++j)
3821 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha14107512013-10-28 18:07:21 +00003822 }
3823
3824 // Create and insert the instruction.
3825 std::vector<Record*> ImpResults;
Craig Topper306cb122015-11-22 20:46:24 +00003826 Instructions.insert(std::make_pair(Instr,
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003827 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha14107512013-10-28 18:07:21 +00003828 continue; // no pattern.
3829 }
3830
Craig Topper306cb122015-11-22 20:46:24 +00003831 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003832 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner8cab0212008-01-05 22:25:12 +00003833 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003834
Chris Lattner8cab0212008-01-05 22:25:12 +00003835 // If we can, convert the instructions to be patterns that are matched!
Craig Topper306cb122015-11-22 20:46:24 +00003836 for (auto &Entry : Instructions) {
Craig Topper306cb122015-11-22 20:46:24 +00003837 Record *Instr = Entry.first;
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003838 DAGInstruction &TheInst = Entry.second;
3839 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3840 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3841
3842 if (SrcPattern && ResultPattern) {
3843 TreePattern Pattern(Instr, SrcPattern, true, *this);
3844 TreePattern Result(Instr, ResultPattern, false, *this);
3845 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3846 }
Chris Lattner8cab0212008-01-05 22:25:12 +00003847 }
3848}
3849
Florian Hahn6b1db822018-06-14 20:32:58 +00003850typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattnera7722b62010-02-23 06:55:24 +00003851
Florian Hahn6b1db822018-06-14 20:32:58 +00003852static void FindNames(TreePatternNode *P,
Chris Lattner5b0e2492010-02-23 07:22:28 +00003853 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003854 TreePattern *PatternTop) {
Florian Hahn6b1db822018-06-14 20:32:58 +00003855 if (!P->getName().empty()) {
3856 NameRecord &Rec = Names[P->getName()];
Chris Lattnera7722b62010-02-23 06:55:24 +00003857 // If this is the first instance of the name, remember the node.
3858 if (Rec.second++ == 0)
Florian Hahn6b1db822018-06-14 20:32:58 +00003859 Rec.first = P;
3860 else if (Rec.first->getExtTypes() != P->getExtTypes())
3861 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattner5b0e2492010-02-23 07:22:28 +00003862 " where different uses have different types!");
Chris Lattnera7722b62010-02-23 06:55:24 +00003863 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003864
Florian Hahn6b1db822018-06-14 20:32:58 +00003865 if (!P->isLeaf()) {
3866 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3867 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003868 }
3869}
3870
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003871std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3872 std::vector<Predicate> Preds;
3873 for (Init *I : L->getValues()) {
3874 if (DefInit *Pred = dyn_cast<DefInit>(I))
3875 Preds.push_back(Pred->getDef());
3876 else
3877 llvm_unreachable("Non-def on the list");
3878 }
3879
3880 // Sort so that different orders get canonicalized to the same string.
Fangrui Song0cac7262018-09-27 02:13:45 +00003881 llvm::sort(Preds);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00003882 return Preds;
3883}
3884
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003885void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper18e6b572017-06-25 17:33:49 +00003886 PatternToMatch &&PTM) {
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003887 // Do some sanity checking on the pattern we're about to match.
Chris Lattner0c0baa92010-02-23 06:16:51 +00003888 std::string Reason;
Owen Andersondee65832012-09-19 22:15:06 +00003889 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3890 PrintWarning(Pattern->getRecord()->getLoc(),
3891 Twine("Pattern can never match: ") + Reason);
3892 return;
3893 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003894
Chris Lattner1e634e32010-03-01 22:29:19 +00003895 // If the source pattern's root is a complex pattern, that complex pattern
3896 // must specify the nodes it can potentially match.
3897 if (const ComplexPattern *CP =
3898 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3899 if (CP->getRootNodes().empty())
3900 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3901 " could match");
Jim Grosbach65586fe2010-12-21 16:16:00 +00003902
3903
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003904 // Find all of the named values in the input and output, ensure they have the
3905 // same type.
Chris Lattnera7722b62010-02-23 06:55:24 +00003906 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn6b1db822018-06-14 20:32:58 +00003907 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3908 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003909
3910 // Scan all of the named values in the destination pattern, rejecting them if
3911 // they don't exist in the input pattern.
Craig Topper306cb122015-11-22 20:46:24 +00003912 for (const auto &Entry : DstNames) {
3913 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner94d3b0a2010-02-23 06:35:45 +00003914 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper306cb122015-11-22 20:46:24 +00003915 Entry.first);
Chris Lattner4b9225b2010-02-23 07:50:58 +00003916 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00003917
Chris Lattnera7722b62010-02-23 06:55:24 +00003918 // Scan all of the named values in the source pattern, rejecting them if the
3919 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper306cb122015-11-22 20:46:24 +00003920 for (const auto &Entry : SrcNames)
3921 if (DstNames[Entry.first].first == nullptr &&
3922 SrcNames[Entry.first].second == 1)
3923 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbach65586fe2010-12-21 16:16:00 +00003924
Florian Hahn0a2e0b62018-06-14 11:56:19 +00003925 PatternsToMatch.push_back(PTM);
Chris Lattner0c0baa92010-02-23 06:16:51 +00003926}
3927
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003928void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper28851b62016-02-01 01:33:42 +00003929 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattner918be522010-03-19 00:34:35 +00003930 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003931
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003932 unsigned Errors = 0;
Jakob Stoklund Olesend9444d42011-10-14 01:00:49 +00003933
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003934 // Try to infer flags from all patterns in PatternToMatch. These include
3935 // both the primary instruction patterns (which always come first) and
3936 // patterns defined outside the instruction.
Craig Toppere8a8e6a2017-06-20 16:34:35 +00003937 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003938 // We can only infer from single-instruction patterns, otherwise we won't
3939 // know which instruction should get the flags.
3940 SmallVector<Record*, 8> PatInstrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00003941 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003942 if (PatInstrs.size() != 1)
3943 continue;
3944
3945 // Get the single instruction.
3946 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3947
3948 // Only infer properties from the first pattern. We'll verify the others.
3949 if (InstInfo.InferredFrom)
3950 continue;
3951
3952 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00003953 PatInfo.Analyze(PTM);
Jakob Stoklund Olesenc2272df2012-08-24 22:46:53 +00003954 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3955 }
3956
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003957 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00003958 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen8a276c22012-08-24 17:08:41 +00003959
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003960 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003961 if (Target.guessInstructionProperties()) {
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003962 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3963 CodeGenInstruction *InstInfo =
3964 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003965 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003966 continue;
3967 // The mayLoad and mayStore flags default to false.
3968 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper306cb122015-11-22 20:46:24 +00003969 if (InstInfo->hasSideEffects_Unset)
3970 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003971 }
3972 return;
3973 }
3974
3975 // Complain about any flags that are still undefined.
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00003976 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3977 CodeGenInstruction *InstInfo =
3978 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper306cb122015-11-22 20:46:24 +00003979 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003980 continue;
Craig Topper306cb122015-11-22 20:46:24 +00003981 if (InstInfo->hasSideEffects_Unset)
3982 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003983 "Can't infer hasSideEffects from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003984 if (InstInfo->mayStore_Unset)
3985 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003986 "Can't infer mayStore from patterns");
Craig Topper306cb122015-11-22 20:46:24 +00003987 if (InstInfo->mayLoad_Unset)
3988 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen94ed4d42012-08-24 00:31:16 +00003989 "Can't infer mayLoad from patterns");
Dan Gohmanfc4ad7de2008-04-03 00:02:49 +00003990 }
3991}
3992
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00003993
3994/// Verify instruction flags against pattern node properties.
3995void CodeGenDAGPatterns::VerifyInstructionFlags() {
3996 unsigned Errors = 0;
3997 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3998 const PatternToMatch &PTM = *I;
3999 SmallVector<Record*, 8> Instrs;
Florian Hahn6b1db822018-06-14 20:32:58 +00004000 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004001 if (Instrs.empty())
4002 continue;
4003
4004 // Count the number of instructions with each flag set.
4005 unsigned NumSideEffects = 0;
4006 unsigned NumStores = 0;
4007 unsigned NumLoads = 0;
Craig Topper306cb122015-11-22 20:46:24 +00004008 for (const Record *Instr : Instrs) {
4009 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004010 NumSideEffects += InstInfo.hasSideEffects;
4011 NumStores += InstInfo.mayStore;
4012 NumLoads += InstInfo.mayLoad;
4013 }
4014
4015 // Analyze the source pattern.
4016 InstAnalyzer PatInfo(*this);
Craig Topper2a053a92017-06-20 16:34:37 +00004017 PatInfo.Analyze(PTM);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004018
4019 // Collect error messages.
4020 SmallVector<std::string, 4> Msgs;
4021
4022 // Check for missing flags in the output.
4023 // Permit extra flags for now at least.
4024 if (PatInfo.hasSideEffects && !NumSideEffects)
4025 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
4026
4027 // Don't verify store flags on instructions with side effects. At least for
4028 // intrinsics, side effects implies mayStore.
4029 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4030 Msgs.push_back("pattern may store, but mayStore isn't set");
4031
4032 // Similarly, mayStore implies mayLoad on intrinsics.
4033 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4034 Msgs.push_back("pattern may load, but mayLoad isn't set");
4035
4036 // Print error messages.
4037 if (Msgs.empty())
4038 continue;
4039 ++Errors;
4040
Craig Topper306cb122015-11-22 20:46:24 +00004041 for (const std::string &Msg : Msgs)
4042 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004043 (Instrs.size() == 1 ?
4044 "instruction" : "output instructions"));
4045 // Provide the location of the relevant instruction definitions.
Craig Topper306cb122015-11-22 20:46:24 +00004046 for (const Record *Instr : Instrs) {
4047 if (Instr != PTM.getSrcRecord())
4048 PrintError(Instr->getLoc(), "defined here");
4049 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004050 if (InstInfo.InferredFrom &&
4051 InstInfo.InferredFrom != InstInfo.TheDef &&
4052 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004053 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004054 }
4055 }
4056 if (Errors)
Joerg Sonnenberger635debe2012-10-25 20:33:17 +00004057 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesena9d322a2012-08-28 03:26:49 +00004058}
4059
Chris Lattnercabe0372010-03-15 06:00:16 +00004060/// Given a pattern result with an unresolved type, see if we can find one
4061/// instruction with an unresolved result type. Force this result type to an
4062/// arbitrary element if it's possible types to converge results.
Florian Hahn6b1db822018-06-14 20:32:58 +00004063static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
4064 if (N->isLeaf())
Chris Lattnercabe0372010-03-15 06:00:16 +00004065 return false;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004066
Chris Lattnercabe0372010-03-15 06:00:16 +00004067 // Analyze children.
Florian Hahn6b1db822018-06-14 20:32:58 +00004068 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4069 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattnercabe0372010-03-15 06:00:16 +00004070 return true;
4071
Florian Hahn6b1db822018-06-14 20:32:58 +00004072 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattnercabe0372010-03-15 06:00:16 +00004073 return false;
4074
4075 // If this type is already concrete or completely unknown we can't do
4076 // anything.
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004077 TypeInfer &TI = TP.getInfer();
Florian Hahn6b1db822018-06-14 20:32:58 +00004078 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
4079 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerf1447252010-03-19 21:37:09 +00004080 continue;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004081
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004082 // Otherwise, force its type to an arbitrary choice.
Florian Hahn6b1db822018-06-14 20:32:58 +00004083 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerf1447252010-03-19 21:37:09 +00004084 return true;
4085 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004086
Chris Lattnerf1447252010-03-19 21:37:09 +00004087 return false;
Chris Lattnercabe0372010-03-15 06:00:16 +00004088}
4089
Ulrich Weigand58a97862018-08-01 11:57:58 +00004090// Promote xform function to be an explicit node wherever set.
4091static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4092 if (Record *Xform = N->getTransformFn()) {
4093 N->setTransformFn(nullptr);
4094 std::vector<TreePatternNodePtr> Children;
4095 Children.push_back(PromoteXForms(N));
4096 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4097 N->getNumTypes());
4098 }
4099
4100 if (!N->isLeaf())
4101 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4102 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigandf989cd72018-08-01 12:07:32 +00004103 N->setChild(i, PromoteXForms(Child));
Ulrich Weigand58a97862018-08-01 11:57:58 +00004104 }
4105 return N;
4106}
4107
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004108void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4109 TreePattern &Pattern, TreePattern &Result,
4110 const std::vector<Record *> &InstImpResults) {
4111
4112 // Inline pattern fragments and expand multiple alternatives.
4113 Pattern.InlinePatternFragments();
4114 Result.InlinePatternFragments();
4115
4116 if (Result.getNumTrees() != 1)
4117 Result.error("Cannot use multi-alternative fragments in result pattern!");
4118
4119 // Infer types.
4120 bool IterateInference;
4121 bool InferredAllPatternTypes, InferredAllResultTypes;
4122 do {
4123 // Infer as many types as possible. If we cannot infer all of them, we
4124 // can never do anything with this pattern: report it to the user.
4125 InferredAllPatternTypes =
4126 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4127
4128 // Infer as many types as possible. If we cannot infer all of them, we
4129 // can never do anything with this pattern: report it to the user.
4130 InferredAllResultTypes =
4131 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4132
4133 IterateInference = false;
4134
4135 // Apply the type of the result to the source pattern. This helps us
4136 // resolve cases where the input type is known to be a pointer type (which
4137 // is considered resolved), but the result knows it needs to be 32- or
4138 // 64-bits. Infer the other way for good measure.
4139 for (auto T : Pattern.getTrees())
4140 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4141 T->getNumTypes());
4142 i != e; ++i) {
4143 IterateInference |= T->UpdateNodeType(
4144 i, Result.getOnlyTree()->getExtType(i), Result);
4145 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4146 i, T->getExtType(i), Result);
4147 }
4148
4149 // If our iteration has converged and the input pattern's types are fully
4150 // resolved but the result pattern is not fully resolved, we may have a
4151 // situation where we have two instructions in the result pattern and
4152 // the instructions require a common register class, but don't care about
4153 // what actual MVT is used. This is actually a bug in our modelling:
4154 // output patterns should have register classes, not MVTs.
4155 //
4156 // In any case, to handle this, we just go through and disambiguate some
4157 // arbitrary types to the result pattern's nodes.
4158 if (!IterateInference && InferredAllPatternTypes &&
4159 !InferredAllResultTypes)
4160 IterateInference =
4161 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4162 } while (IterateInference);
4163
4164 // Verify that we inferred enough types that we can do something with the
4165 // pattern and result. If these fire the user has to add type casts.
4166 if (!InferredAllPatternTypes)
4167 Pattern.error("Could not infer all types in pattern!");
4168 if (!InferredAllResultTypes) {
4169 Pattern.dump();
4170 Result.error("Could not infer all types in pattern result!");
4171 }
4172
Ulrich Weigand58a97862018-08-01 11:57:58 +00004173 // Promote xform function to be an explicit node wherever set.
4174 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004175
4176 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4177 Temp.InferAllTypes();
4178
4179 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4180 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4181
4182 if (PatternRewriter)
4183 PatternRewriter(&Pattern);
4184
4185 // A pattern may end up with an "impossible" type, i.e. a situation
4186 // where all types have been eliminated for some node in this pattern.
4187 // This could occur for intrinsics that only make sense for a specific
4188 // value type, and use a specific register class. If, for some mode,
4189 // that register class does not accept that type, the type inference
4190 // will lead to a contradiction, which is not an error however, but
4191 // a sign that this pattern will simply never match.
4192 if (Temp.getOnlyTree()->hasPossibleType())
4193 for (auto T : Pattern.getTrees())
4194 if (T->hasPossibleType())
4195 AddPatternToMatch(&Pattern,
4196 PatternToMatch(TheDef, makePredList(Preds),
4197 T, Temp.getOnlyTree(),
4198 InstImpResults, Complexity,
4199 TheDef->getID()));
4200}
4201
Chris Lattnerab3242f2008-01-06 01:10:31 +00004202void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner8cab0212008-01-05 22:25:12 +00004203 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4204
Craig Topper306cb122015-11-22 20:46:24 +00004205 for (Record *CurPattern : Patterns) {
David Greeneaf8ee2c2011-07-29 22:43:06 +00004206 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachab27c5e2012-07-17 18:39:36 +00004207
4208 // If the pattern references the null_frag, there's nothing to do.
4209 if (hasNullFragReference(Tree))
4210 continue;
4211
Florian Hahn75e87c32018-05-30 21:00:18 +00004212 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner8cab0212008-01-05 22:25:12 +00004213
David Greeneaf8ee2c2011-07-29 22:43:06 +00004214 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperec9072d2015-05-14 05:53:53 +00004215 if (LI->empty()) continue; // no pattern.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004216
Chris Lattner8cab0212008-01-05 22:25:12 +00004217 // Parse the instruction.
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004218 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004219
David Blaikie4ac0c0c2014-11-14 21:53:50 +00004220 if (Result.getNumTrees() != 1)
4221 Result.error("Cannot handle instructions producing instructions "
4222 "with temporaries yet!");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004223
Chris Lattner8cab0212008-01-05 22:25:12 +00004224 // Validate that the input pattern is correct.
Florian Hahn75e87c32018-05-30 21:00:18 +00004225 std::map<std::string, TreePatternNodePtr> InstInputs;
Craig Topperbd199f82018-12-05 00:47:59 +00004226 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4227 InstResults;
Chris Lattner8cab0212008-01-05 22:25:12 +00004228 std::vector<Record*> InstImpResults;
Florian Hahn75e87c32018-05-30 21:00:18 +00004229 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie19b22d42018-06-11 22:14:43 +00004230 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn75e87c32018-05-30 21:00:18 +00004231 InstResults, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004232
Ulrich Weigandc48aefb2018-07-13 13:18:00 +00004233 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner8cab0212008-01-05 22:25:12 +00004234 }
4235}
4236
Florian Hahn6b1db822018-06-14 20:32:58 +00004237static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004238 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4239 for (const auto &I : VTS)
4240 Modes.insert(I.first);
4241
4242 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn6b1db822018-06-14 20:32:58 +00004243 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004244}
4245
4246void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4247 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4248 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4249 std::vector<PatternToMatch> Copy = PatternsToMatch;
4250 PatternsToMatch.clear();
4251
Florian Hahn75e87c32018-05-30 21:00:18 +00004252 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4253 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4254 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004255 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004256 return;
4257 }
4258
4259 std::vector<Predicate> Preds = P.Predicates;
4260 const std::vector<Predicate> &MC = ModeChecks[Mode];
4261 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004262 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4263 std::move(NewDst), P.getDstRegs(),
4264 P.getAddedComplexity(), Record::getNewUID(),
4265 Mode);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004266 };
4267
4268 for (PatternToMatch &P : Copy) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004269 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn6b1db822018-06-14 20:32:58 +00004270 if (P.SrcPattern->hasProperTypeByHwMode())
4271 SrcP = P.SrcPattern;
4272 if (P.DstPattern->hasProperTypeByHwMode())
4273 DstP = P.DstPattern;
4274 if (!SrcP && !DstP) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004275 PatternsToMatch.push_back(P);
4276 continue;
4277 }
4278
4279 std::set<unsigned> Modes;
Florian Hahn6b1db822018-06-14 20:32:58 +00004280 if (SrcP)
4281 collectModes(Modes, SrcP.get());
4282 if (DstP)
4283 collectModes(Modes, DstP.get());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004284
4285 // The predicate for the default mode needs to be constructed for each
4286 // pattern separately.
4287 // Since not all modes must be present in each pattern, if a mode m is
4288 // absent, then there is no point in constructing a check for m. If such
4289 // a check was created, it would be equivalent to checking the default
4290 // mode, except not all modes' predicates would be a part of the checking
4291 // code. The subsequently generated check for the default mode would then
4292 // have the exact same patterns, but a different predicate code. To avoid
4293 // duplicated patterns with different predicate checks, construct the
4294 // default check as a negation of all predicates that are actually present
4295 // in the source/destination patterns.
4296 std::vector<Predicate> DefaultPred;
4297
4298 for (unsigned M : Modes) {
4299 if (M == DefaultMode)
4300 continue;
4301 if (ModeChecks.find(M) != ModeChecks.end())
4302 continue;
4303
4304 // Fill the map entry for this mode.
4305 const HwMode &HM = CGH.getMode(M);
4306 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4307
4308 // Add negations of the HM's predicates to the default predicate.
4309 DefaultPred.emplace_back(Predicate(HM.Features, false));
4310 }
4311
4312 for (unsigned M : Modes) {
4313 if (M == DefaultMode)
4314 continue;
4315 AppendPattern(P, M);
4316 }
4317
4318 bool HasDefault = Modes.count(DefaultMode);
4319 if (HasDefault)
4320 AppendPattern(P, DefaultMode);
4321 }
4322}
4323
4324/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turner249dc142017-09-20 18:01:40 +00004325typedef StringMap<int> DepVarMap;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004326
Florian Hahn6b1db822018-06-14 20:32:58 +00004327static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4328 if (N->isLeaf()) {
4329 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4330 DepMap[N->getName()]++;
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004331 } else {
Florian Hahn6b1db822018-06-14 20:32:58 +00004332 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4333 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004334 }
4335}
4336
4337/// Find dependent variables within child patterns
Florian Hahn6b1db822018-06-14 20:32:58 +00004338static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004339 DepVarMap depcounts;
4340 FindDepVarsOf(N, depcounts);
Zachary Turner249dc142017-09-20 18:01:40 +00004341 for (const auto &Pair : depcounts) {
4342 if (Pair.getValue() > 1)
4343 DepVars.insert(Pair.getKey());
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004344 }
4345}
4346
4347#ifndef NDEBUG
4348/// Dump the dependent variable set:
4349static void DumpDepVars(MultipleUseVarSet &DepVars) {
4350 if (DepVars.empty()) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004351 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004352 } else {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004353 LLVM_DEBUG(errs() << "[ ");
Zachary Turner249dc142017-09-20 18:01:40 +00004354 for (const auto &DepVar : DepVars) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004355 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004356 }
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004357 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszek779d98e2017-09-14 16:56:21 +00004358 }
4359}
4360#endif
4361
4362
Chris Lattner8cab0212008-01-05 22:25:12 +00004363/// CombineChildVariants - Given a bunch of permutations of each child of the
4364/// 'operator' node, put them together in all possible ways.
Florian Hahn75e87c32018-05-30 21:00:18 +00004365static void CombineChildVariants(
Florian Hahn6b1db822018-06-14 20:32:58 +00004366 TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004367 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4368 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4369 const MultipleUseVarSet &DepVars) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004370 // Make sure that each operand has at least one variant to choose from.
Craig Topper306cb122015-11-22 20:46:24 +00004371 for (const auto &Variants : ChildVariants)
4372 if (Variants.empty())
Chris Lattner8cab0212008-01-05 22:25:12 +00004373 return;
Jim Grosbach65586fe2010-12-21 16:16:00 +00004374
Chris Lattner8cab0212008-01-05 22:25:12 +00004375 // The end result is an all-pairs construction of the resultant pattern.
4376 std::vector<unsigned> Idxs;
4377 Idxs.resize(ChildVariants.size());
Scott Michel94420742008-03-05 17:49:05 +00004378 bool NotDone;
4379 do {
4380#ifndef NDEBUG
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004381 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004382 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004383 for (unsigned Idx : Idxs) {
4384 errs() << Idx << " ";
4385 }
4386 errs() << "]\n";
4387 });
Scott Michel94420742008-03-05 17:49:05 +00004388#endif
Chris Lattner8cab0212008-01-05 22:25:12 +00004389 // Create the variant and add it to the output list.
Florian Hahn75e87c32018-05-30 21:00:18 +00004390 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004391 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4392 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn75e87c32018-05-30 21:00:18 +00004393 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Topper26fc06352018-07-15 06:52:49 +00004394 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbach65586fe2010-12-21 16:16:00 +00004395
Chris Lattner8cab0212008-01-05 22:25:12 +00004396 // Copy over properties.
Florian Hahn6b1db822018-06-14 20:32:58 +00004397 R->setName(Orig->getName());
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004398 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4399 R->setPredicateCalls(Orig->getPredicateCalls());
Florian Hahn6b1db822018-06-14 20:32:58 +00004400 R->setTransformFn(Orig->getTransformFn());
4401 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4402 R->setType(i, Orig->getExtType(i));
Jim Grosbach65586fe2010-12-21 16:16:00 +00004403
Scott Michel94420742008-03-05 17:49:05 +00004404 // If this pattern cannot match, do not include it as a variant.
Chris Lattner8cab0212008-01-05 22:25:12 +00004405 std::string ErrString;
David Blaikiefda69dd2015-11-22 20:11:21 +00004406 // Scan to see if this pattern has already been emitted. We can get
4407 // duplication due to things like commuting:
4408 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4409 // which are the same pattern. Ignore the dups.
4410 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn75e87c32018-05-30 21:00:18 +00004411 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004412 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemer0a16c222016-08-11 21:15:00 +00004413 }))
Florian Hahn75e87c32018-05-30 21:00:18 +00004414 OutVariants.push_back(R);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004415
Scott Michel94420742008-03-05 17:49:05 +00004416 // Increment indices to the next permutation by incrementing the
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004417 // indices from last index backward, e.g., generate the sequence
Scott Michel94420742008-03-05 17:49:05 +00004418 // [0, 0], [0, 1], [1, 0], [1, 1].
4419 int IdxsIdx;
4420 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4421 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4422 Idxs[IdxsIdx] = 0;
4423 else
Chris Lattner8cab0212008-01-05 22:25:12 +00004424 break;
Chris Lattner8cab0212008-01-05 22:25:12 +00004425 }
Scott Michel94420742008-03-05 17:49:05 +00004426 NotDone = (IdxsIdx >= 0);
4427 } while (NotDone);
Chris Lattner8cab0212008-01-05 22:25:12 +00004428}
4429
4430/// CombineChildVariants - A helper function for binary operators.
4431///
Florian Hahn6b1db822018-06-14 20:32:58 +00004432static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn75e87c32018-05-30 21:00:18 +00004433 const std::vector<TreePatternNodePtr> &LHS,
4434 const std::vector<TreePatternNodePtr> &RHS,
4435 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004436 CodeGenDAGPatterns &CDP,
4437 const MultipleUseVarSet &DepVars) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004438 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004439 ChildVariants.push_back(LHS);
4440 ChildVariants.push_back(RHS);
Scott Michel94420742008-03-05 17:49:05 +00004441 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004442}
Chris Lattner8cab0212008-01-05 22:25:12 +00004443
Florian Hahn75e87c32018-05-30 21:00:18 +00004444static void
Florian Hahn6b1db822018-06-14 20:32:58 +00004445GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004446 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004447 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4448 Record *Operator = N->getOperator();
Jim Grosbach65586fe2010-12-21 16:16:00 +00004449
Chris Lattner8cab0212008-01-05 22:25:12 +00004450 // Only permit raw nodes.
Nicolai Haehnle445b0b62018-11-30 14:15:13 +00004451 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
Chris Lattner8cab0212008-01-05 22:25:12 +00004452 N->getTransformFn()) {
4453 Children.push_back(N);
4454 return;
4455 }
4456
Florian Hahn6b1db822018-06-14 20:32:58 +00004457 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004458 Children.push_back(N->getChildShared(0));
Chris Lattner8cab0212008-01-05 22:25:12 +00004459 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004460 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004461
Florian Hahn6b1db822018-06-14 20:32:58 +00004462 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn75e87c32018-05-30 21:00:18 +00004463 Children.push_back(N->getChildShared(1));
Chris Lattner8cab0212008-01-05 22:25:12 +00004464 else
Florian Hahn75e87c32018-05-30 21:00:18 +00004465 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner8cab0212008-01-05 22:25:12 +00004466}
4467
4468/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4469/// the (potentially recursive) pattern by using algebraic laws.
4470///
Florian Hahn6b1db822018-06-14 20:32:58 +00004471static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn75e87c32018-05-30 21:00:18 +00004472 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel94420742008-03-05 17:49:05 +00004473 CodeGenDAGPatterns &CDP,
4474 const MultipleUseVarSet &DepVars) {
Tim Northoverc807a172014-05-20 11:52:46 +00004475 // We cannot permute leaves or ComplexPattern uses.
4476 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004477 OutVariants.push_back(N);
4478 return;
4479 }
4480
4481 // Look up interesting info about the node.
4482 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4483
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004484 // If this node is associative, re-associate.
Chris Lattner8cab0212008-01-05 22:25:12 +00004485 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbach65586fe2010-12-21 16:16:00 +00004486 // Re-associate by pulling together all of the linked operators
Florian Hahn75e87c32018-05-30 21:00:18 +00004487 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner8cab0212008-01-05 22:25:12 +00004488 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4489
4490 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4491 // permutations.
4492 if (MaximalChildren.size() == 3) {
4493 // Find the variants of all of our maximal children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004494 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel94420742008-03-05 17:49:05 +00004495 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4496 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4497 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbach65586fe2010-12-21 16:16:00 +00004498
Chris Lattner8cab0212008-01-05 22:25:12 +00004499 // There are only two ways we can permute the tree:
4500 // (A op B) op C and A op (B op C)
4501 // Within these forms, we can also permute A/B/C.
Jim Grosbach65586fe2010-12-21 16:16:00 +00004502
Chris Lattner8cab0212008-01-05 22:25:12 +00004503 // Generate legal pair permutations of A/B/C.
Florian Hahn75e87c32018-05-30 21:00:18 +00004504 std::vector<TreePatternNodePtr> ABVariants;
4505 std::vector<TreePatternNodePtr> BAVariants;
4506 std::vector<TreePatternNodePtr> ACVariants;
4507 std::vector<TreePatternNodePtr> CAVariants;
4508 std::vector<TreePatternNodePtr> BCVariants;
4509 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004510 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4511 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4512 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4513 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4514 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4515 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004516
4517 // Combine those into the result: (x op x) op x
Florian Hahn6b1db822018-06-14 20:32:58 +00004518 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4519 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4520 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4521 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4522 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4523 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004524
4525 // Combine those into the result: x op (x op x)
Florian Hahn6b1db822018-06-14 20:32:58 +00004526 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4527 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4528 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4529 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4530 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4531 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004532 return;
4533 }
4534 }
Jim Grosbach65586fe2010-12-21 16:16:00 +00004535
Chris Lattner8cab0212008-01-05 22:25:12 +00004536 // Compute permutations of all children.
Florian Hahn75e87c32018-05-30 21:00:18 +00004537 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner8cab0212008-01-05 22:25:12 +00004538 ChildVariants.resize(N->getNumChildren());
4539 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn75e87c32018-05-30 21:00:18 +00004540 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004541
4542 // Build all permutations based on how the children were formed.
Florian Hahn6b1db822018-06-14 20:32:58 +00004543 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004544
4545 // If this node is commutative, consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004546 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4547 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper98a96282017-09-04 03:44:33 +00004548 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng49bad4c2008-06-16 20:29:38 +00004549 "Commutative but doesn't have 2 children!");
Chris Lattner8cab0212008-01-05 22:25:12 +00004550 // Don't count children which are actually register references.
4551 unsigned NC = 0;
4552 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004553 TreePatternNode *Child = N->getChild(i);
4554 if (Child->isLeaf())
4555 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner8cab0212008-01-05 22:25:12 +00004556 Record *RR = DI->getDef();
4557 if (RR->isSubClassOf("Register"))
4558 continue;
4559 }
4560 NC++;
4561 }
4562 // Consider the commuted order.
Evan Cheng49bad4c2008-06-16 20:29:38 +00004563 if (isCommIntrinsic) {
4564 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4565 // operands are the commutative operands, and there might be more operands
4566 // after those.
4567 assert(NC >= 3 &&
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00004568 "Commutative intrinsic should have at least 3 children!");
Florian Hahn75e87c32018-05-30 21:00:18 +00004569 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004570 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4571 Variants.push_back(std::move(ChildVariants[2]));
4572 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng49bad4c2008-06-16 20:29:38 +00004573 for (unsigned i = 3; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004574 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004575 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004576 } else if (NC == N->getNumChildren()) {
Florian Hahn75e87c32018-05-30 21:00:18 +00004577 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004578 Variants.push_back(std::move(ChildVariants[1]));
4579 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper98a96282017-09-04 03:44:33 +00004580 for (unsigned i = 2; i != NC; ++i)
Florian Hahn0a2e0b62018-06-14 11:56:19 +00004581 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn6b1db822018-06-14 20:32:58 +00004582 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper98a96282017-09-04 03:44:33 +00004583 }
Chris Lattner8cab0212008-01-05 22:25:12 +00004584 }
4585}
4586
4587
4588// GenerateVariants - Generate variants. For example, commutative patterns can
4589// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerab3242f2008-01-06 01:10:31 +00004590void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004591 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004592
Chris Lattner8cab0212008-01-05 22:25:12 +00004593 // Loop over all of the patterns we've collected, checking to see if we can
4594 // generate variants of the instruction, through the exploitation of
Jim Grosbach975c1cb2009-03-26 16:17:51 +00004595 // identities. This permits the target to provide aggressive matching without
Chris Lattner8cab0212008-01-05 22:25:12 +00004596 // the .td file having to contain tons of variants of instructions.
4597 //
4598 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4599 // intentionally do not reconsider these. Any variants of added patterns have
4600 // already been added.
4601 //
Simon Pilgrim0621f562018-09-18 11:30:30 +00004602 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4603 BitVector MatchedPatterns(NumOriginalPatterns);
4604 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4605 BitVector(NumOriginalPatterns));
4606
4607 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4608 DepsAndVariants;
4609 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4610
4611 // Collect patterns with more than one variant.
4612 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4613 MultipleUseVarSet DepVars;
Florian Hahn75e87c32018-05-30 21:00:18 +00004614 std::vector<TreePatternNodePtr> Variants;
Florian Hahn6b1db822018-06-14 20:32:58 +00004615 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004616 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4617 LLVM_DEBUG(DumpDepVars(DepVars));
4618 LLVM_DEBUG(errs() << "\n");
Florian Hahn75e87c32018-05-30 21:00:18 +00004619 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4620 *this, DepVars);
Chris Lattner8cab0212008-01-05 22:25:12 +00004621
4622 assert(!Variants.empty() && "Must create at least original variant!");
Simon Pilgrim0621f562018-09-18 11:30:30 +00004623 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner8cab0212008-01-05 22:25:12 +00004624 continue;
4625
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004626 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4627 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004628
Simon Pilgrim0621f562018-09-18 11:30:30 +00004629 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4630
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004631 // Cache matching predicates.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004632 if (MatchedPatterns[i])
4633 continue;
4634
4635 const std::vector<Predicate> &Predicates =
4636 PatternsToMatch[i].getPredicates();
4637
4638 BitVector &Matches = MatchedPredicates[i];
Simon Pilgrim6d706772018-09-19 12:23:50 +00004639 MatchedPatterns.set(i);
4640 Matches.set(i);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004641
4642 // Don't test patterns that have already been cached - it won't match.
4643 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4644 if (!MatchedPatterns[p])
4645 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4646
4647 // Copy this to all the matching patterns.
4648 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
Simon Pilgrime3c6f8d2018-09-18 12:01:25 +00004649 if (p != (int)i) {
Simon Pilgrim6d706772018-09-19 12:23:50 +00004650 MatchedPatterns.set(p);
Simon Pilgrim0621f562018-09-18 11:30:30 +00004651 MatchedPredicates[p] = Matches;
4652 }
4653 }
4654
4655 for (auto it : PatternsWithVariants) {
4656 unsigned i = it.first;
4657 const MultipleUseVarSet &DepVars = it.second.first;
4658 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
Simon Pilgrim6a92b5e2018-08-28 15:42:08 +00004659
Chris Lattner8cab0212008-01-05 22:25:12 +00004660 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn6b1db822018-06-14 20:32:58 +00004661 TreePatternNodePtr Variant = Variants[v];
Simon Pilgrim0621f562018-09-18 11:30:30 +00004662 BitVector &Matches = MatchedPredicates[i];
Chris Lattner8cab0212008-01-05 22:25:12 +00004663
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004664 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4665 errs() << "\n");
Jim Grosbach65586fe2010-12-21 16:16:00 +00004666
Chris Lattner8cab0212008-01-05 22:25:12 +00004667 // Scan to see if an instruction or explicit pattern already matches this.
4668 bool AlreadyExists = false;
Craig Topper2f70a7e2015-11-22 22:43:40 +00004669 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Cheng34c8c742009-06-26 05:59:16 +00004670 // Skip if the top level predicates do not match.
Simon Pilgrim0621f562018-09-18 11:30:30 +00004671 if (!Matches[p])
Evan Cheng34c8c742009-06-26 05:59:16 +00004672 continue;
Chris Lattner8cab0212008-01-05 22:25:12 +00004673 // Check to see if this variant already exists.
Florian Hahn6b1db822018-06-14 20:32:58 +00004674 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004675 DepVars)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004676 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004677 AlreadyExists = true;
4678 break;
4679 }
4680 }
4681 // If we already have it, ignore the variant.
4682 if (AlreadyExists) continue;
4683
4684 // Otherwise, add it to the list of patterns we have.
Ayman Musa40e3f192017-06-27 07:10:20 +00004685 PatternsToMatch.push_back(PatternToMatch(
Craig Topper2f70a7e2015-11-22 22:43:40 +00004686 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn75e87c32018-05-30 21:00:18 +00004687 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper2f70a7e2015-11-22 22:43:40 +00004688 PatternsToMatch[i].getDstRegs(),
Ayman Musa40e3f192017-06-27 07:10:20 +00004689 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Simon Pilgrim0621f562018-09-18 11:30:30 +00004690 MatchedPredicates.push_back(Matches);
4691
Simon Pilgrimb2444352018-09-18 14:05:07 +00004692 // Add a new match the same as this pattern.
Simon Pilgrimb2444352018-09-18 14:05:07 +00004693 for (auto &P : MatchedPredicates)
Simon Pilgrim429df292018-09-19 11:18:49 +00004694 P.push_back(P[i]);
Chris Lattner8cab0212008-01-05 22:25:12 +00004695 }
4696
Nicola Zaghend34e60c2018-05-14 12:53:11 +00004697 LLVM_DEBUG(errs() << "\n");
Chris Lattner8cab0212008-01-05 22:25:12 +00004698 }
4699}