blob: 96c90c9cf6bd84a979d38d946af35a3492bddea3 [file] [log] [blame]
Chris Lattnerfe718932008-01-06 01:10:31 +00001//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
Chris Lattnerfe718932008-01-06 01:10:31 +000010// This file implements the CodeGenDAGPatterns class, which is used to read and
Chris Lattner6cefb772008-01-05 22:25:12 +000011// represent the patterns present in a .td file for instructions.
12//
13//===----------------------------------------------------------------------===//
14
Chris Lattner93c7e412008-01-05 23:37:52 +000015#include "CodeGenDAGPatterns.h"
Simon Pilgrimac6174e2018-08-28 15:42:08 +000016#include "llvm/ADT/BitVector.h"
Zachary Turnere4442992017-09-20 18:01:40 +000017#include "llvm/ADT/DenseSet.h"
Craig Topper0f562fe2018-12-05 00:47:59 +000018#include "llvm/ADT/MapVector.h"
Chris Lattner2cacec52010-03-15 06:00:16 +000019#include "llvm/ADT/STLExtras.h"
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000020#include "llvm/ADT/SmallSet.h"
Craig Topperb51ae5e2015-11-28 08:23:02 +000021#include "llvm/ADT/SmallString.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000022#include "llvm/ADT/StringExtras.h"
Craig Topperc0faa7c2017-09-21 04:55:03 +000023#include "llvm/ADT/StringMap.h"
Jim Grosbach9b29ea42012-04-18 17:46:41 +000024#include "llvm/ADT/Twine.h"
Chris Lattner6cefb772008-01-05 22:25:12 +000025#include "llvm/Support/Debug.h"
David Blaikiefdebc382012-01-17 04:43:56 +000026#include "llvm/Support/ErrorHandling.h"
Chandler Carruth4ffd89f2012-12-04 10:37:14 +000027#include "llvm/TableGen/Error.h"
28#include "llvm/TableGen/Record.h"
Chuck Rose III9a79de32008-01-15 21:43:17 +000029#include <algorithm>
Benjamin Kramer901b8582012-03-23 11:35:30 +000030#include <cstdio>
Craig Topper0f562fe2018-12-05 00:47:59 +000031#include <iterator>
Benjamin Kramer901b8582012-03-23 11:35:30 +000032#include <set>
Chris Lattner6cefb772008-01-05 22:25:12 +000033using namespace llvm;
34
Chandler Carruth283b3992014-04-21 22:55:11 +000035#define DEBUG_TYPE "dag-patterns"
36
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000037static inline bool isIntegerOrPtr(MVT VT) {
38 return VT.isInteger() || VT == MVT::iPTR;
Duncan Sands83ec4b62008-06-06 12:08:01 +000039}
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000040static inline bool isFloatingPoint(MVT VT) {
41 return VT.isFloatingPoint();
Duncan Sands83ec4b62008-06-06 12:08:01 +000042}
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000043static inline bool isVector(MVT VT) {
44 return VT.isVector();
Duncan Sands83ec4b62008-06-06 12:08:01 +000045}
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000046static inline bool isScalar(MVT VT) {
47 return !VT.isVector();
Chris Lattner774ce292010-03-19 17:41:26 +000048}
Duncan Sands83ec4b62008-06-06 12:08:01 +000049
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +000050template <typename Predicate>
51static bool berase_if(MachineValueTypeSet &S, Predicate P) {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000052 bool Erased = false;
Krzysztof Parzyszek7e1bf432017-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 Lattner2cacec52010-03-15 06:00:16 +000060 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000061 return Erased;
Chris Lattner6cefb772008-01-05 22:25:12 +000062}
63
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000064// --- TypeSetByHwMode
Chris Lattner2cacec52010-03-15 06:00:16 +000065
Krzysztof Parzyszekdb815642017-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 Grosbachfbadcd02010-12-21 16:16:00 +000069
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000070TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
71 for (const ValueTypeByHwMode &VVT : VTList)
72 insert(VVT);
Chris Lattner6cefb772008-01-05 22:25:12 +000073}
74
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000075bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
76 for (const auto &I : *this) {
77 if (I.second.size() > 1)
78 return false;
79 if (!AllowEmpty && I.second.empty())
80 return false;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +000081 }
Chris Lattner5a9b8fb2010-03-19 04:54:36 +000082 return true;
83}
Chris Lattner2cacec52010-03-15 06:00:16 +000084
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000085ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode() const {
86 assert(isValueTypeByHwMode(true) &&
87 "The type set has multiple types for at least one HW mode");
88 ValueTypeByHwMode VVT;
89 for (const auto &I : *this) {
90 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
91 VVT.getOrCreateTypeForMode(I.first, T);
Chris Lattner2cacec52010-03-15 06:00:16 +000092 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000093 return VVT;
Bob Wilson61fc4cf2009-08-11 01:14:02 +000094}
Chris Lattner2cacec52010-03-15 06:00:16 +000095
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +000096bool TypeSetByHwMode::isPossible() const {
97 for (const auto &I : *this)
98 if (!I.second.empty())
99 return true;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000100 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +0000101}
102
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000103bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
104 bool Changed = false;
Simon Pilgrime1166b22018-08-17 13:03:17 +0000105 bool ContainsDefault = false;
106 MVT DT = MVT::Other;
107
Zachary Turnere4442992017-09-20 18:01:40 +0000108 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000109 for (const auto &P : VVT) {
110 unsigned M = P.first;
111 Modes.insert(M);
112 // Make sure there exists a set for each specific mode from VVT.
113 Changed |= getOrCreate(M).insert(P.second).second;
Simon Pilgrime1166b22018-08-17 13:03:17 +0000114 // Cache VVT's default mode.
115 if (DefaultMode == M) {
116 ContainsDefault = true;
117 DT = P.second;
118 }
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000119 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000120
121 // If VVT has a default mode, add the corresponding type to all
122 // modes in "this" that do not exist in VVT.
Simon Pilgrime1166b22018-08-17 13:03:17 +0000123 if (ContainsDefault)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000124 for (auto &I : *this)
125 if (!Modes.count(I.first))
126 Changed |= I.second.insert(DT).second;
Simon Pilgrime1166b22018-08-17 13:03:17 +0000127
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000128 return Changed;
Chris Lattner2cacec52010-03-15 06:00:16 +0000129}
130
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000131// Constrain the type set to be the intersection with VTS.
132bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
133 bool Changed = false;
134 if (hasDefault()) {
135 for (const auto &I : VTS) {
136 unsigned M = I.first;
137 if (M == DefaultMode || hasMode(M))
138 continue;
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000139 Map.insert({M, Map.at(DefaultMode)});
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000140 Changed = true;
141 }
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000142 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000143
144 for (auto &I : *this) {
145 unsigned M = I.first;
146 SetType &S = I.second;
147 if (VTS.hasMode(M) || VTS.hasDefault()) {
148 Changed |= intersect(I.second, VTS.get(M));
149 } else if (!S.empty()) {
150 S.clear();
151 Changed = true;
152 }
153 }
154 return Changed;
Chris Lattner2cacec52010-03-15 06:00:16 +0000155}
156
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000157template <typename Predicate>
158bool TypeSetByHwMode::constrain(Predicate P) {
159 bool Changed = false;
160 for (auto &I : *this)
Benjamin Kramer4bca09d2017-09-17 11:19:53 +0000161 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000162 return Changed;
Chris Lattner2cacec52010-03-15 06:00:16 +0000163}
164
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000165template <typename Predicate>
166bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
167 assert(empty());
168 for (const auto &I : VTS) {
169 SetType &S = getOrCreate(I.first);
170 for (auto J : I.second)
171 if (P(J))
172 S.insert(J);
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000173 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000174 return !empty();
Chris Lattner2cacec52010-03-15 06:00:16 +0000175}
176
Zachary Turnere4442992017-09-20 18:01:40 +0000177void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
178 SmallVector<unsigned, 4> Modes;
179 Modes.reserve(Map.size());
Chris Lattner2cacec52010-03-15 06:00:16 +0000180
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000181 for (const auto &I : *this)
182 Modes.push_back(I.first);
Zachary Turnere4442992017-09-20 18:01:40 +0000183 if (Modes.empty()) {
184 OS << "{}";
185 return;
186 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000187 array_pod_sort(Modes.begin(), Modes.end());
Chris Lattner5a9b8fb2010-03-19 04:54:36 +0000188
Zachary Turnere4442992017-09-20 18:01:40 +0000189 OS << '{';
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000190 for (unsigned M : Modes) {
Zachary Turnere4442992017-09-20 18:01:40 +0000191 OS << ' ' << getModeName(M) << ':';
192 writeToStream(get(M), OS);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000193 }
Zachary Turnere4442992017-09-20 18:01:40 +0000194 OS << " }";
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000195}
196
Zachary Turnere4442992017-09-20 18:01:40 +0000197void TypeSetByHwMode::writeToStream(const SetType &S, raw_ostream &OS) {
198 SmallVector<MVT, 4> Types(S.begin(), S.end());
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000199 array_pod_sort(Types.begin(), Types.end());
200
Zachary Turnere4442992017-09-20 18:01:40 +0000201 OS << '[';
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000202 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
Zachary Turnere4442992017-09-20 18:01:40 +0000203 OS << ValueTypeByHwMode::getMVTName(Types[i]);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000204 if (i != e-1)
Zachary Turnere4442992017-09-20 18:01:40 +0000205 OS << ' ';
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000206 }
Zachary Turnere4442992017-09-20 18:01:40 +0000207 OS << ']';
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000208}
209
210bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
Simon Pilgrimfc96bec2018-08-16 16:16:28 +0000211 // The isSimple call is much quicker than hasDefault - check this first.
212 bool IsSimple = isSimple();
213 bool VTSIsSimple = VTS.isSimple();
214 if (IsSimple && VTSIsSimple)
215 return *begin() == *VTS.begin();
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +0000216
Simon Pilgrimfc96bec2018-08-16 16:16:28 +0000217 // Speedup: We have a default if the set is simple.
218 bool HaveDefault = IsSimple || hasDefault();
219 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
220 if (HaveDefault != VTSHaveDefault)
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000221 return false;
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000222
Zachary Turnere4442992017-09-20 18:01:40 +0000223 SmallDenseSet<unsigned, 4> Modes;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000224 for (auto &I : *this)
225 Modes.insert(I.first);
226 for (const auto &I : VTS)
227 Modes.insert(I.first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +0000228
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000229 if (HaveDefault) {
230 // Both sets have default mode.
231 for (unsigned M : Modes) {
232 if (get(M) != VTS.get(M))
David Majnemer5d08e372016-08-12 04:32:37 +0000233 return false;
Craig Topper20faa142015-11-24 08:20:47 +0000234 }
Scott Michel327d0652008-03-05 17:49:05 +0000235 } else {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000236 // Neither set has default mode.
237 for (unsigned M : Modes) {
238 // If there is no default mode, an empty set is equivalent to not having
239 // the corresponding mode.
240 bool NoModeThis = !hasMode(M) || get(M).empty();
241 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(M).empty();
242 if (NoModeThis != NoModeVTS)
243 return false;
244 if (!NoModeThis)
245 if (get(M) != VTS.get(M))
246 return false;
247 }
Scott Michel327d0652008-03-05 17:49:05 +0000248 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000249
250 return true;
Scott Michel327d0652008-03-05 17:49:05 +0000251}
252
Krzysztof Parzyszekbbd7d722017-09-22 18:29:37 +0000253namespace llvm {
254 raw_ostream &operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
255 T.writeToStream(OS);
256 return OS;
257 }
258}
259
Krzysztof Parzyszek2ea93a22017-09-12 15:31:26 +0000260LLVM_DUMP_METHOD
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000261void TypeSetByHwMode::dump() const {
Krzysztof Parzyszekbbd7d722017-09-22 18:29:37 +0000262 dbgs() << *this << '\n';
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000263}
264
265bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
266 bool OutP = Out.count(MVT::iPTR), InP = In.count(MVT::iPTR);
267 auto Int = [&In](MVT T) -> bool { return !In.count(T); };
268
269 if (OutP == InP)
270 return berase_if(Out, Int);
271
272 // Compute the intersection of scalars separately to account for only
273 // one set containing iPTR.
274 // The itersection of iPTR with a set of integer scalar types that does not
275 // include iPTR will result in the most specific scalar type:
276 // - iPTR is more specific than any set with two elements or more
277 // - iPTR is less specific than any single integer scalar type.
278 // For example
279 // { iPTR } * { i32 } -> { i32 }
280 // { iPTR } * { i32 i64 } -> { iPTR }
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000281 // and
282 // { iPTR i32 } * { i32 } -> { i32 }
283 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
284 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000285
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000286 // Compute the difference between the two sets in such a way that the
287 // iPTR is in the set that is being subtracted. This is to see if there
288 // are any extra scalars in the set without iPTR that are not in the
289 // set containing iPTR. Then the iPTR could be considered a "wildcard"
290 // matching these scalars. If there is only one such scalar, it would
291 // replace the iPTR, if there are more, the iPTR would be retained.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000292 SetType Diff;
293 if (InP) {
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000294 Diff = Out;
295 berase_if(Diff, [&In](MVT T) { return In.count(T); });
296 // Pre-remove these elements and rely only on InP/OutP to determine
297 // whether a change has been made.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000298 berase_if(Out, [&Diff](MVT T) { return Diff.count(T); });
Scott Michel327d0652008-03-05 17:49:05 +0000299 } else {
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000300 Diff = In;
301 berase_if(Diff, [&Out](MVT T) { return Out.count(T); });
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000302 Out.erase(MVT::iPTR);
303 }
304
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000305 // The actual intersection.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000306 bool Changed = berase_if(Out, Int);
307 unsigned NumD = Diff.size();
308 if (NumD == 0)
309 return Changed;
310
311 if (NumD == 1) {
312 Out.insert(*Diff.begin());
313 // This is a change only if Out was the one with iPTR (which is now
314 // being replaced).
315 Changed |= OutP;
316 } else {
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000317 // Multiple elements from Out are now replaced with iPTR.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000318 Out.insert(MVT::iPTR);
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000319 Changed |= !OutP;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000320 }
321 return Changed;
322}
323
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000324bool TypeSetByHwMode::validate() const {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000325#ifndef NDEBUG
326 if (empty())
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000327 return true;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000328 bool AllEmpty = true;
329 for (const auto &I : *this)
330 AllEmpty &= I.second.empty();
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000331 return !AllEmpty;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000332#endif
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000333 return true;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000334}
335
336// --- TypeInfer
337
338bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
339 const TypeSetByHwMode &In) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000340 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000341 In.validate();
342 if (In.empty() || Out == In || TP.hasError())
343 return false;
344 if (Out.empty()) {
345 Out = In;
346 return true;
347 }
348
349 bool Changed = Out.constrain(In);
350 if (Changed && Out.empty())
351 TP.error("Type contradiction");
352
353 return Changed;
354}
355
356bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000357 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000358 if (TP.hasError())
359 return false;
360 assert(!Out.empty() && "cannot pick from an empty set");
361
362 bool Changed = false;
363 for (auto &I : Out) {
364 TypeSetByHwMode::SetType &S = I.second;
365 if (S.size() <= 1)
366 continue;
367 MVT T = *S.begin(); // Pick the first element.
368 S.clear();
369 S.insert(T);
370 Changed = true;
371 }
372 return Changed;
373}
374
375bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000376 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000377 if (TP.hasError())
378 return false;
379 if (!Out.empty())
380 return Out.constrain(isIntegerOrPtr);
381
382 return Out.assign_if(getLegalTypes(), isIntegerOrPtr);
383}
384
385bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000386 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000387 if (TP.hasError())
388 return false;
389 if (!Out.empty())
390 return Out.constrain(isFloatingPoint);
391
392 return Out.assign_if(getLegalTypes(), isFloatingPoint);
393}
394
395bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000396 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000397 if (TP.hasError())
398 return false;
399 if (!Out.empty())
400 return Out.constrain(isScalar);
401
402 return Out.assign_if(getLegalTypes(), isScalar);
403}
404
405bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000406 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000407 if (TP.hasError())
408 return false;
409 if (!Out.empty())
410 return Out.constrain(isVector);
411
412 return Out.assign_if(getLegalTypes(), isVector);
413}
414
415bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000416 ValidateOnExit _1(Out, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000417 if (TP.hasError() || !Out.empty())
418 return false;
419
420 Out = getLegalTypes();
421 return true;
422}
423
424template <typename Iter, typename Pred, typename Less>
425static Iter min_if(Iter B, Iter E, Pred P, Less L) {
426 if (B == E)
427 return E;
428 Iter Min = E;
429 for (Iter I = B; I != E; ++I) {
430 if (!P(*I))
431 continue;
432 if (Min == E || L(*I, *Min))
433 Min = I;
434 }
435 return Min;
436}
437
438template <typename Iter, typename Pred, typename Less>
439static Iter max_if(Iter B, Iter E, Pred P, Less L) {
440 if (B == E)
441 return E;
442 Iter Max = E;
443 for (Iter I = B; I != E; ++I) {
444 if (!P(*I))
445 continue;
446 if (Max == E || L(*Max, *I))
447 Max = I;
448 }
449 return Max;
450}
451
452/// Make sure that for each type in Small, there exists a larger type in Big.
453bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small,
454 TypeSetByHwMode &Big) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000455 ValidateOnExit _1(Small, *this), _2(Big, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000456 if (TP.hasError())
457 return false;
458 bool Changed = false;
459
460 if (Small.empty())
461 Changed |= EnforceAny(Small);
462 if (Big.empty())
463 Changed |= EnforceAny(Big);
464
465 assert(Small.hasDefault() && Big.hasDefault());
466
467 std::vector<unsigned> Modes = union_modes(Small, Big);
468
469 // 1. Only allow integer or floating point types and make sure that
470 // both sides are both integer or both floating point.
471 // 2. Make sure that either both sides have vector types, or neither
472 // of them does.
473 for (unsigned M : Modes) {
474 TypeSetByHwMode::SetType &S = Small.get(M);
475 TypeSetByHwMode::SetType &B = Big.get(M);
476
477 if (any_of(S, isIntegerOrPtr) && any_of(S, isIntegerOrPtr)) {
Benjamin Kramer4bca09d2017-09-17 11:19:53 +0000478 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000479 Changed |= berase_if(S, NotInt) |
480 berase_if(B, NotInt);
481 } else if (any_of(S, isFloatingPoint) && any_of(B, isFloatingPoint)) {
Benjamin Kramer4bca09d2017-09-17 11:19:53 +0000482 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000483 Changed |= berase_if(S, NotFP) |
484 berase_if(B, NotFP);
485 } else if (S.empty() || B.empty()) {
486 Changed = !S.empty() || !B.empty();
487 S.clear();
488 B.clear();
489 } else {
490 TP.error("Incompatible types");
491 return Changed;
Scott Michel327d0652008-03-05 17:49:05 +0000492 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000493
494 if (none_of(S, isVector) || none_of(B, isVector)) {
495 Changed |= berase_if(S, isVector) |
496 berase_if(B, isVector);
497 }
498 }
499
500 auto LT = [](MVT A, MVT B) -> bool {
501 return A.getScalarSizeInBits() < B.getScalarSizeInBits() ||
502 (A.getScalarSizeInBits() == B.getScalarSizeInBits() &&
503 A.getSizeInBits() < B.getSizeInBits());
504 };
505 auto LE = [](MVT A, MVT B) -> bool {
506 // This function is used when removing elements: when a vector is compared
507 // to a non-vector, it should return false (to avoid removal).
508 if (A.isVector() != B.isVector())
509 return false;
510
511 // Note on the < comparison below:
512 // X86 has patterns like
513 // (set VR128X:$dst, (v16i8 (X86vtrunc (v4i32 VR128X:$src1)))),
514 // where the truncated vector is given a type v16i8, while the source
515 // vector has type v4i32. They both have the same size in bits.
516 // The minimal type in the result is obviously v16i8, and when we remove
517 // all types from the source that are smaller-or-equal than v8i16, the
518 // only source type would also be removed (since it's equal in size).
519 return A.getScalarSizeInBits() <= B.getScalarSizeInBits() ||
520 A.getSizeInBits() < B.getSizeInBits();
521 };
522
523 for (unsigned M : Modes) {
524 TypeSetByHwMode::SetType &S = Small.get(M);
525 TypeSetByHwMode::SetType &B = Big.get(M);
526 // MinS = min scalar in Small, remove all scalars from Big that are
527 // smaller-or-equal than MinS.
528 auto MinS = min_if(S.begin(), S.end(), isScalar, LT);
Krzysztof Parzyszek8cc053e2017-10-15 15:39:56 +0000529 if (MinS != S.end())
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000530 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinS));
Krzysztof Parzyszek8cc053e2017-10-15 15:39:56 +0000531
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000532 // MaxS = max scalar in Big, remove all scalars from Small that are
533 // larger than MaxS.
534 auto MaxS = max_if(B.begin(), B.end(), isScalar, LT);
Krzysztof Parzyszek8cc053e2017-10-15 15:39:56 +0000535 if (MaxS != B.end())
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000536 Changed |= berase_if(S, std::bind(LE, *MaxS, std::placeholders::_1));
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000537
538 // MinV = min vector in Small, remove all vectors from Big that are
539 // smaller-or-equal than MinV.
540 auto MinV = min_if(S.begin(), S.end(), isVector, LT);
Krzysztof Parzyszek8cc053e2017-10-15 15:39:56 +0000541 if (MinV != S.end())
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000542 Changed |= berase_if(B, std::bind(LE, std::placeholders::_1, *MinV));
Krzysztof Parzyszek8cc053e2017-10-15 15:39:56 +0000543
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000544 // MaxV = max vector in Big, remove all vectors from Small that are
545 // larger than MaxV.
546 auto MaxV = max_if(B.begin(), B.end(), isVector, LT);
Krzysztof Parzyszek8cc053e2017-10-15 15:39:56 +0000547 if (MaxV != B.end())
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000548 Changed |= berase_if(S, std::bind(LE, *MaxV, std::placeholders::_1));
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000549 }
550
551 return Changed;
552}
553
554/// 1. Ensure that for each type T in Vec, T is a vector type, and that
555/// for each type U in Elem, U is a scalar type.
556/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
557/// type T in Vec, such that U is the element type of T.
558bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
559 TypeSetByHwMode &Elem) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000560 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000561 if (TP.hasError())
562 return false;
563 bool Changed = false;
564
565 if (Vec.empty())
566 Changed |= EnforceVector(Vec);
567 if (Elem.empty())
568 Changed |= EnforceScalar(Elem);
569
570 for (unsigned M : union_modes(Vec, Elem)) {
571 TypeSetByHwMode::SetType &V = Vec.get(M);
572 TypeSetByHwMode::SetType &E = Elem.get(M);
573
574 Changed |= berase_if(V, isScalar); // Scalar = !vector
575 Changed |= berase_if(E, isVector); // Vector = !scalar
576 assert(!V.empty() && !E.empty());
577
578 SmallSet<MVT,4> VT, ST;
579 // Collect element types from the "vector" set.
580 for (MVT T : V)
581 VT.insert(T.getVectorElementType());
582 // Collect scalar types from the "element" set.
583 for (MVT T : E)
584 ST.insert(T);
585
586 // Remove from V all (vector) types whose element type is not in S.
587 Changed |= berase_if(V, [&ST](MVT T) -> bool {
588 return !ST.count(T.getVectorElementType());
589 });
590 // Remove from E all (scalar) types, for which there is no corresponding
591 // type in V.
592 Changed |= berase_if(E, [&VT](MVT T) -> bool { return !VT.count(T); });
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000593 }
594
595 return Changed;
596}
597
598bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
599 const ValueTypeByHwMode &VVT) {
600 TypeSetByHwMode Tmp(VVT);
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000601 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000602 return EnforceVectorEltTypeIs(Vec, Tmp);
603}
604
605/// Ensure that for each type T in Sub, T is a vector type, and there
606/// exists a type U in Vec such that U is a vector type with the same
607/// element type as T and at least as many elements as T.
608bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
609 TypeSetByHwMode &Sub) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000610 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000611 if (TP.hasError())
612 return false;
613
614 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
615 auto IsSubVec = [](MVT B, MVT P) -> bool {
616 if (!B.isVector() || !P.isVector())
617 return false;
Florian Hahn8aa5d0f2017-11-07 10:43:56 +0000618 // Logically a <4 x i32> is a valid subvector of <n x 4 x i32>
619 // but until there are obvious use-cases for this, keep the
620 // types separate.
621 if (B.isScalableVector() != P.isScalableVector())
622 return false;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000623 if (B.getVectorElementType() != P.getVectorElementType())
624 return false;
625 return B.getVectorNumElements() < P.getVectorNumElements();
626 };
627
628 /// Return true if S has no element (vector type) that T is a sub-vector of,
629 /// i.e. has the same element type as T and more elements.
630 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
631 for (const auto &I : S)
632 if (IsSubVec(T, I))
633 return false;
634 return true;
635 };
636
637 /// Return true if S has no element (vector type) that T is a super-vector
638 /// of, i.e. has the same element type as T and fewer elements.
639 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
640 for (const auto &I : S)
641 if (IsSubVec(I, T))
642 return false;
643 return true;
644 };
645
646 bool Changed = false;
647
648 if (Vec.empty())
649 Changed |= EnforceVector(Vec);
650 if (Sub.empty())
651 Changed |= EnforceVector(Sub);
652
653 for (unsigned M : union_modes(Vec, Sub)) {
654 TypeSetByHwMode::SetType &S = Sub.get(M);
655 TypeSetByHwMode::SetType &V = Vec.get(M);
656
657 Changed |= berase_if(S, isScalar);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000658
659 // Erase all types from S that are not sub-vectors of a type in V.
660 Changed |= berase_if(S, std::bind(NoSubV, V, std::placeholders::_1));
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000661
662 // Erase all types from V that are not super-vectors of a type in S.
663 Changed |= berase_if(V, std::bind(NoSupV, S, std::placeholders::_1));
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000664 }
665
666 return Changed;
667}
668
669/// 1. Ensure that V has a scalar type iff W has a scalar type.
670/// 2. Ensure that for each vector type T in V, there exists a vector
671/// type U in W, such that T and U have the same number of elements.
672/// 3. Ensure that for each vector type U in W, there exists a vector
673/// type T in V, such that T and U have the same number of elements
674/// (reverse of 2).
675bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000676 ValidateOnExit _1(V, *this), _2(W, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000677 if (TP.hasError())
678 return false;
679
680 bool Changed = false;
681 if (V.empty())
682 Changed |= EnforceAny(V);
683 if (W.empty())
684 Changed |= EnforceAny(W);
685
686 // An actual vector type cannot have 0 elements, so we can treat scalars
687 // as zero-length vectors. This way both vectors and scalars can be
688 // processed identically.
689 auto NoLength = [](const SmallSet<unsigned,2> &Lengths, MVT T) -> bool {
690 return !Lengths.count(T.isVector() ? T.getVectorNumElements() : 0);
691 };
692
693 for (unsigned M : union_modes(V, W)) {
694 TypeSetByHwMode::SetType &VS = V.get(M);
695 TypeSetByHwMode::SetType &WS = W.get(M);
696
697 SmallSet<unsigned,2> VN, WN;
698 for (MVT T : VS)
699 VN.insert(T.isVector() ? T.getVectorNumElements() : 0);
700 for (MVT T : WS)
701 WN.insert(T.isVector() ? T.getVectorNumElements() : 0);
702
703 Changed |= berase_if(VS, std::bind(NoLength, WN, std::placeholders::_1));
704 Changed |= berase_if(WS, std::bind(NoLength, VN, std::placeholders::_1));
705 }
706 return Changed;
707}
708
709/// 1. Ensure that for each type T in A, there exists a type U in B,
710/// such that T and U have equal size in bits.
711/// 2. Ensure that for each type U in B, there exists a type T in A
712/// such that T and U have equal size in bits (reverse of 1).
713bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000714 ValidateOnExit _1(A, *this), _2(B, *this);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000715 if (TP.hasError())
716 return false;
717 bool Changed = false;
718 if (A.empty())
719 Changed |= EnforceAny(A);
720 if (B.empty())
721 Changed |= EnforceAny(B);
722
723 auto NoSize = [](const SmallSet<unsigned,2> &Sizes, MVT T) -> bool {
724 return !Sizes.count(T.getSizeInBits());
725 };
726
727 for (unsigned M : union_modes(A, B)) {
728 TypeSetByHwMode::SetType &AS = A.get(M);
729 TypeSetByHwMode::SetType &BS = B.get(M);
730 SmallSet<unsigned,2> AN, BN;
731
732 for (MVT T : AS)
733 AN.insert(T.getSizeInBits());
734 for (MVT T : BS)
735 BN.insert(T.getSizeInBits());
736
737 Changed |= berase_if(AS, std::bind(NoSize, BN, std::placeholders::_1));
738 Changed |= berase_if(BS, std::bind(NoSize, AN, std::placeholders::_1));
739 }
740
741 return Changed;
742}
743
744void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000745 ValidateOnExit _1(VTS, *this);
Simon Pilgrim8f783892018-08-17 15:54:07 +0000746 const TypeSetByHwMode &Legal = getLegalTypes();
747 assert(Legal.isDefaultOnly() && "Default-mode only expected");
748 const TypeSetByHwMode::SetType &LegalTypes = Legal.get(DefaultMode);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000749
Simon Pilgrim8f783892018-08-17 15:54:07 +0000750 for (auto &I : VTS)
751 expandOverloads(I.second, LegalTypes);
Scott Michel327d0652008-03-05 17:49:05 +0000752}
Daniel Dunbar6aa526b2010-10-08 02:07:22 +0000753
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000754void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
755 const TypeSetByHwMode::SetType &Legal) {
756 std::set<MVT> Ovs;
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000757 for (MVT T : Out) {
758 if (!T.isOverloaded())
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000759 continue;
Zachary Turnere4442992017-09-20 18:01:40 +0000760
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000761 Ovs.insert(T);
762 // MachineValueTypeSet allows iteration and erasing.
763 Out.erase(T);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000764 }
765
766 for (MVT Ov : Ovs) {
767 switch (Ov.SimpleTy) {
768 case MVT::iPTRAny:
769 Out.insert(MVT::iPTR);
770 return;
771 case MVT::iAny:
772 for (MVT T : MVT::integer_valuetypes())
773 if (Legal.count(T))
774 Out.insert(T);
775 for (MVT T : MVT::integer_vector_valuetypes())
776 if (Legal.count(T))
777 Out.insert(T);
778 return;
779 case MVT::fAny:
780 for (MVT T : MVT::fp_valuetypes())
781 if (Legal.count(T))
782 Out.insert(T);
783 for (MVT T : MVT::fp_vector_valuetypes())
784 if (Legal.count(T))
785 Out.insert(T);
786 return;
787 case MVT::vAny:
788 for (MVT T : MVT::vector_valuetypes())
789 if (Legal.count(T))
790 Out.insert(T);
791 return;
792 case MVT::Any:
793 for (MVT T : MVT::all_valuetypes())
794 if (Legal.count(T))
795 Out.insert(T);
796 return;
797 default:
798 break;
799 }
800 }
801}
802
Simon Pilgrim8f783892018-08-17 15:54:07 +0000803const TypeSetByHwMode &TypeInfer::getLegalTypes() {
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000804 if (!LegalTypesCached) {
Simon Pilgrim8f783892018-08-17 15:54:07 +0000805 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(DefaultMode);
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000806 // Stuff all types from all modes into the default mode.
807 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
808 for (const auto &I : LTS)
Simon Pilgrim8f783892018-08-17 15:54:07 +0000809 LegalTypes.insert(I.second);
Krzysztof Parzyszek7e1bf432017-09-19 18:42:34 +0000810 LegalTypesCached = true;
811 }
Simon Pilgrim8f783892018-08-17 15:54:07 +0000812 assert(LegalCache.isDefaultOnly() && "Default-mode only expected");
813 return LegalCache;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +0000814}
Chris Lattner54379062011-04-17 21:38:24 +0000815
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000816#ifndef NDEBUG
817TypeInfer::ValidateOnExit::~ValidateOnExit() {
Ulrich Weigandc62320c2018-07-13 16:42:15 +0000818 if (Infer.Validate && !VTS.validate()) {
Krzysztof Parzyszek5de0a982017-12-21 17:12:43 +0000819 dbgs() << "Type set is empty for each HW mode:\n"
820 "possible type contradiction in the pattern below "
821 "(use -print-records with llvm-tblgen to see all "
822 "expanded records).\n";
823 Infer.TP.dump();
824 llvm_unreachable(nullptr);
825 }
826}
827#endif
828
Nicolai Haehnle98272e42018-11-30 14:15:13 +0000829
830//===----------------------------------------------------------------------===//
831// ScopedName Implementation
832//===----------------------------------------------------------------------===//
833
834bool ScopedName::operator==(const ScopedName &o) const {
835 return Scope == o.Scope && Identifier == o.Identifier;
836}
837
838bool ScopedName::operator!=(const ScopedName &o) const {
839 return !(*this == o);
840}
841
842
Chris Lattner54379062011-04-17 21:38:24 +0000843//===----------------------------------------------------------------------===//
844// TreePredicateFn Implementation
845//===----------------------------------------------------------------------===//
846
Chris Lattner7ed13912011-04-17 22:05:17 +0000847/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
848TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
Daniel Sandersb10e0a22017-10-15 19:01:32 +0000849 assert(
850 (!hasPredCode() || !hasImmCode()) &&
851 ".td file corrupt: can't have a node predicate *and* an imm predicate");
852}
853
854bool TreePredicateFn::hasPredCode() const {
Daniel Sanders438d60f2017-11-13 22:26:13 +0000855 return isLoad() || isStore() || isAtomic() ||
Daniel Sandersb10e0a22017-10-15 19:01:32 +0000856 !PatFragRec->getRecord()->getValueAsString("PredicateCode").empty();
Chris Lattner7ed13912011-04-17 22:05:17 +0000857}
858
Daniel Sanders91007462017-10-15 02:06:44 +0000859std::string TreePredicateFn::getPredCode() const {
860 std::string Code = "";
861
Daniel Sanders438d60f2017-11-13 22:26:13 +0000862 if (!isLoad() && !isStore() && !isAtomic()) {
863 Record *MemoryVT = getMemoryVT();
864
865 if (MemoryVT)
866 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
867 "MemoryVT requires IsLoad or IsStore");
868 }
869
Daniel Sanders91007462017-10-15 02:06:44 +0000870 if (!isLoad() && !isStore()) {
871 if (isUnindexed())
872 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
873 "IsUnindexed requires IsLoad or IsStore");
874
Daniel Sanders91007462017-10-15 02:06:44 +0000875 Record *ScalarMemoryVT = getScalarMemoryVT();
876
Daniel Sanders91007462017-10-15 02:06:44 +0000877 if (ScalarMemoryVT)
878 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
879 "ScalarMemoryVT requires IsLoad or IsStore");
880 }
881
Daniel Sanders438d60f2017-11-13 22:26:13 +0000882 if (isLoad() + isStore() + isAtomic() > 1)
Daniel Sanders91007462017-10-15 02:06:44 +0000883 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
Daniel Sanders438d60f2017-11-13 22:26:13 +0000884 "IsLoad, IsStore, and IsAtomic are mutually exclusive");
Daniel Sanders91007462017-10-15 02:06:44 +0000885
886 if (isLoad()) {
887 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
888 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
889 getScalarMemoryVT() == nullptr)
890 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
891 "IsLoad cannot be used by itself");
892 } else {
893 if (isNonExtLoad())
894 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
895 "IsNonExtLoad requires IsLoad");
896 if (isAnyExtLoad())
897 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
898 "IsAnyExtLoad requires IsLoad");
899 if (isSignExtLoad())
900 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
901 "IsSignExtLoad requires IsLoad");
902 if (isZeroExtLoad())
903 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
904 "IsZeroExtLoad requires IsLoad");
905 }
906
907 if (isStore()) {
908 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
909 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr)
910 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
911 "IsStore cannot be used by itself");
912 } else {
913 if (isNonTruncStore())
914 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
915 "IsNonTruncStore requires IsStore");
916 if (isTruncStore())
917 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
918 "IsTruncStore requires IsStore");
919 }
920
Daniel Sanders438d60f2017-11-13 22:26:13 +0000921 if (isAtomic()) {
Daniel Sanders22434af2017-11-13 23:03:47 +0000922 if (getMemoryVT() == nullptr && !isAtomicOrderingMonotonic() &&
923 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
924 !isAtomicOrderingAcquireRelease() &&
Daniel Sanders053346d2017-11-30 21:05:59 +0000925 !isAtomicOrderingSequentiallyConsistent() &&
926 !isAtomicOrderingAcquireOrStronger() &&
927 !isAtomicOrderingReleaseOrStronger() &&
928 !isAtomicOrderingWeakerThanAcquire() &&
929 !isAtomicOrderingWeakerThanRelease())
Daniel Sanders438d60f2017-11-13 22:26:13 +0000930 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
931 "IsAtomic cannot be used by itself");
Daniel Sanders22434af2017-11-13 23:03:47 +0000932 } else {
933 if (isAtomicOrderingMonotonic())
934 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
935 "IsAtomicOrderingMonotonic requires IsAtomic");
936 if (isAtomicOrderingAcquire())
937 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
938 "IsAtomicOrderingAcquire requires IsAtomic");
939 if (isAtomicOrderingRelease())
940 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
941 "IsAtomicOrderingRelease requires IsAtomic");
942 if (isAtomicOrderingAcquireRelease())
943 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
944 "IsAtomicOrderingAcquireRelease requires IsAtomic");
945 if (isAtomicOrderingSequentiallyConsistent())
946 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
947 "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
Daniel Sanders053346d2017-11-30 21:05:59 +0000948 if (isAtomicOrderingAcquireOrStronger())
949 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
950 "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
951 if (isAtomicOrderingReleaseOrStronger())
952 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
953 "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
954 if (isAtomicOrderingWeakerThanAcquire())
955 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
956 "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
Daniel Sanders438d60f2017-11-13 22:26:13 +0000957 }
Daniel Sanders22434af2017-11-13 23:03:47 +0000958
Daniel Sanders438d60f2017-11-13 22:26:13 +0000959 if (isLoad() || isStore() || isAtomic()) {
960 StringRef SDNodeName =
961 isLoad() ? "LoadSDNode" : isStore() ? "StoreSDNode" : "AtomicSDNode";
962
963 Record *MemoryVT = getMemoryVT();
964
965 if (MemoryVT)
966 Code += ("if (cast<" + SDNodeName + ">(N)->getMemoryVT() != MVT::" +
967 MemoryVT->getName() + ") return false;\n")
968 .str();
969 }
970
Daniel Sanders22434af2017-11-13 23:03:47 +0000971 if (isAtomic() && isAtomicOrderingMonotonic())
972 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
973 "AtomicOrdering::Monotonic) return false;\n";
974 if (isAtomic() && isAtomicOrderingAcquire())
975 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
976 "AtomicOrdering::Acquire) return false;\n";
977 if (isAtomic() && isAtomicOrderingRelease())
978 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
979 "AtomicOrdering::Release) return false;\n";
980 if (isAtomic() && isAtomicOrderingAcquireRelease())
981 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
982 "AtomicOrdering::AcquireRelease) return false;\n";
983 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
984 Code += "if (cast<AtomicSDNode>(N)->getOrdering() != "
985 "AtomicOrdering::SequentiallyConsistent) return false;\n";
986
Daniel Sanders053346d2017-11-30 21:05:59 +0000987 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
988 Code += "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
989 "return false;\n";
990 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
991 Code += "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
992 "return false;\n";
993
994 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
995 Code += "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
996 "return false;\n";
997 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
998 Code += "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getOrdering())) "
999 "return false;\n";
1000
Daniel Sanders91007462017-10-15 02:06:44 +00001001 if (isLoad() || isStore()) {
1002 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1003
1004 if (isUnindexed())
1005 Code += ("if (cast<" + SDNodeName +
1006 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1007 "return false;\n")
1008 .str();
1009
1010 if (isLoad()) {
1011 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1012 isZeroExtLoad()) > 1)
1013 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1014 "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1015 "IsZeroExtLoad are mutually exclusive");
1016 if (isNonExtLoad())
1017 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1018 "ISD::NON_EXTLOAD) return false;\n";
1019 if (isAnyExtLoad())
1020 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1021 "return false;\n";
1022 if (isSignExtLoad())
1023 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1024 "return false;\n";
1025 if (isZeroExtLoad())
1026 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1027 "return false;\n";
1028 } else {
1029 if ((isNonTruncStore() + isTruncStore()) > 1)
1030 PrintFatalError(
1031 getOrigPatFragRecord()->getRecord()->getLoc(),
1032 "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1033 if (isNonTruncStore())
1034 Code +=
1035 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1036 if (isTruncStore())
1037 Code +=
1038 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1039 }
1040
Daniel Sanders91007462017-10-15 02:06:44 +00001041 Record *ScalarMemoryVT = getScalarMemoryVT();
1042
Daniel Sanders91007462017-10-15 02:06:44 +00001043 if (ScalarMemoryVT)
1044 Code += ("if (cast<" + SDNodeName +
1045 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1046 ScalarMemoryVT->getName() + ") return false;\n")
1047 .str();
1048 }
1049
1050 std::string PredicateCode = PatFragRec->getRecord()->getValueAsString("PredicateCode");
1051
1052 Code += PredicateCode;
1053
1054 if (PredicateCode.empty() && !Code.empty())
1055 Code += "return true;\n";
1056
1057 return Code;
Chris Lattner54379062011-04-17 21:38:24 +00001058}
1059
Daniel Sandersb10e0a22017-10-15 19:01:32 +00001060bool TreePredicateFn::hasImmCode() const {
1061 return !PatFragRec->getRecord()->getValueAsString("ImmediateCode").empty();
1062}
1063
Daniel Sanders91007462017-10-15 02:06:44 +00001064std::string TreePredicateFn::getImmCode() const {
Jakob Stoklund Olesen8dd6f0c2012-01-13 03:38:34 +00001065 return PatFragRec->getRecord()->getValueAsString("ImmediateCode");
Chris Lattner7ed13912011-04-17 22:05:17 +00001066}
1067
Daniel Sanders5cd5b632017-10-13 20:42:18 +00001068bool TreePredicateFn::immCodeUsesAPInt() const {
1069 return getOrigPatFragRecord()->getRecord()->getValueAsBit("IsAPInt");
1070}
1071
1072bool TreePredicateFn::immCodeUsesAPFloat() const {
1073 bool Unset;
1074 // The return value will be false when IsAPFloat is unset.
1075 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset("IsAPFloat",
1076 Unset);
1077}
1078
Daniel Sanders91007462017-10-15 02:06:44 +00001079bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1080 bool Value) const {
1081 bool Unset;
1082 bool Result =
1083 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(Field, Unset);
1084 if (Unset)
1085 return false;
1086 return Result == Value;
1087}
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001088bool TreePredicateFn::usesOperands() const {
1089 return isPredefinedPredicateEqualTo("PredicateCodeUsesOperands", true);
1090}
Daniel Sanders91007462017-10-15 02:06:44 +00001091bool TreePredicateFn::isLoad() const {
1092 return isPredefinedPredicateEqualTo("IsLoad", true);
1093}
1094bool TreePredicateFn::isStore() const {
1095 return isPredefinedPredicateEqualTo("IsStore", true);
1096}
Daniel Sanders438d60f2017-11-13 22:26:13 +00001097bool TreePredicateFn::isAtomic() const {
1098 return isPredefinedPredicateEqualTo("IsAtomic", true);
1099}
Daniel Sanders91007462017-10-15 02:06:44 +00001100bool TreePredicateFn::isUnindexed() const {
1101 return isPredefinedPredicateEqualTo("IsUnindexed", true);
1102}
1103bool TreePredicateFn::isNonExtLoad() const {
1104 return isPredefinedPredicateEqualTo("IsNonExtLoad", true);
1105}
1106bool TreePredicateFn::isAnyExtLoad() const {
1107 return isPredefinedPredicateEqualTo("IsAnyExtLoad", true);
1108}
1109bool TreePredicateFn::isSignExtLoad() const {
1110 return isPredefinedPredicateEqualTo("IsSignExtLoad", true);
1111}
1112bool TreePredicateFn::isZeroExtLoad() const {
1113 return isPredefinedPredicateEqualTo("IsZeroExtLoad", true);
1114}
1115bool TreePredicateFn::isNonTruncStore() const {
1116 return isPredefinedPredicateEqualTo("IsTruncStore", false);
1117}
1118bool TreePredicateFn::isTruncStore() const {
1119 return isPredefinedPredicateEqualTo("IsTruncStore", true);
1120}
Daniel Sanders22434af2017-11-13 23:03:47 +00001121bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1122 return isPredefinedPredicateEqualTo("IsAtomicOrderingMonotonic", true);
1123}
1124bool TreePredicateFn::isAtomicOrderingAcquire() const {
1125 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquire", true);
1126}
1127bool TreePredicateFn::isAtomicOrderingRelease() const {
1128 return isPredefinedPredicateEqualTo("IsAtomicOrderingRelease", true);
1129}
1130bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1131 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireRelease", true);
1132}
1133bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1134 return isPredefinedPredicateEqualTo("IsAtomicOrderingSequentiallyConsistent",
1135 true);
1136}
Daniel Sanders053346d2017-11-30 21:05:59 +00001137bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1138 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", true);
1139}
1140bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1141 return isPredefinedPredicateEqualTo("IsAtomicOrderingAcquireOrStronger", false);
1142}
1143bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1144 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", true);
1145}
1146bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1147 return isPredefinedPredicateEqualTo("IsAtomicOrderingReleaseOrStronger", false);
1148}
Daniel Sanders91007462017-10-15 02:06:44 +00001149Record *TreePredicateFn::getMemoryVT() const {
1150 Record *R = getOrigPatFragRecord()->getRecord();
1151 if (R->isValueUnset("MemoryVT"))
1152 return nullptr;
1153 return R->getValueAsDef("MemoryVT");
1154}
1155Record *TreePredicateFn::getScalarMemoryVT() const {
1156 Record *R = getOrigPatFragRecord()->getRecord();
1157 if (R->isValueUnset("ScalarMemoryVT"))
1158 return nullptr;
1159 return R->getValueAsDef("ScalarMemoryVT");
1160}
Daniel Sandersa2824b62018-06-15 23:13:43 +00001161bool TreePredicateFn::hasGISelPredicateCode() const {
1162 return !PatFragRec->getRecord()
1163 ->getValueAsString("GISelPredicateCode")
1164 .empty();
1165}
1166std::string TreePredicateFn::getGISelPredicateCode() const {
1167 return PatFragRec->getRecord()->getValueAsString("GISelPredicateCode");
1168}
Daniel Sanders91007462017-10-15 02:06:44 +00001169
Simon Pilgrime4d6a6e2017-10-14 21:27:53 +00001170StringRef TreePredicateFn::getImmType() const {
Daniel Sanders5cd5b632017-10-13 20:42:18 +00001171 if (immCodeUsesAPInt())
1172 return "const APInt &";
1173 if (immCodeUsesAPFloat())
1174 return "const APFloat &";
1175 return "int64_t";
1176}
Chris Lattner54379062011-04-17 21:38:24 +00001177
Simon Pilgrime4d6a6e2017-10-14 21:27:53 +00001178StringRef TreePredicateFn::getImmTypeIdentifier() const {
Daniel Sanders94aa10e2017-10-13 21:28:03 +00001179 if (immCodeUsesAPInt())
1180 return "APInt";
1181 else if (immCodeUsesAPFloat())
1182 return "APFloat";
1183 return "I64";
1184}
1185
Chris Lattner54379062011-04-17 21:38:24 +00001186/// isAlwaysTrue - Return true if this is a noop predicate.
1187bool TreePredicateFn::isAlwaysTrue() const {
Daniel Sandersb10e0a22017-10-15 19:01:32 +00001188 return !hasPredCode() && !hasImmCode();
Chris Lattner54379062011-04-17 21:38:24 +00001189}
1190
1191/// Return the name to use in the generated code to reference this, this is
1192/// "Predicate_foo" if from a pattern fragment "foo".
1193std::string TreePredicateFn::getFnName() const {
Matthias Braun0c517c82016-12-04 05:48:16 +00001194 return "Predicate_" + PatFragRec->getRecord()->getName().str();
Chris Lattner54379062011-04-17 21:38:24 +00001195}
1196
1197/// getCodeToRunOnSDNode - Return the code for the function body that
1198/// evaluates this predicate. The argument is expected to be in "Node",
1199/// not N. This handles casting and conversion to a concrete node type as
1200/// appropriate.
1201std::string TreePredicateFn::getCodeToRunOnSDNode() const {
Chris Lattner7ed13912011-04-17 22:05:17 +00001202 // Handle immediate predicates first.
Daniel Sanders91007462017-10-15 02:06:44 +00001203 std::string ImmCode = getImmCode();
Chris Lattner7ed13912011-04-17 22:05:17 +00001204 if (!ImmCode.empty()) {
Daniel Sanders91007462017-10-15 02:06:44 +00001205 if (isLoad())
1206 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1207 "IsLoad cannot be used with ImmLeaf or its subclasses");
1208 if (isStore())
1209 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1210 "IsStore cannot be used with ImmLeaf or its subclasses");
1211 if (isUnindexed())
1212 PrintFatalError(
1213 getOrigPatFragRecord()->getRecord()->getLoc(),
1214 "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1215 if (isNonExtLoad())
1216 PrintFatalError(
1217 getOrigPatFragRecord()->getRecord()->getLoc(),
1218 "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1219 if (isAnyExtLoad())
1220 PrintFatalError(
1221 getOrigPatFragRecord()->getRecord()->getLoc(),
1222 "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1223 if (isSignExtLoad())
1224 PrintFatalError(
1225 getOrigPatFragRecord()->getRecord()->getLoc(),
1226 "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1227 if (isZeroExtLoad())
1228 PrintFatalError(
1229 getOrigPatFragRecord()->getRecord()->getLoc(),
1230 "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1231 if (isNonTruncStore())
1232 PrintFatalError(
1233 getOrigPatFragRecord()->getRecord()->getLoc(),
1234 "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1235 if (isTruncStore())
1236 PrintFatalError(
1237 getOrigPatFragRecord()->getRecord()->getLoc(),
1238 "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1239 if (getMemoryVT())
1240 PrintFatalError(getOrigPatFragRecord()->getRecord()->getLoc(),
1241 "MemoryVT cannot be used with ImmLeaf or its subclasses");
1242 if (getScalarMemoryVT())
1243 PrintFatalError(
1244 getOrigPatFragRecord()->getRecord()->getLoc(),
1245 "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1246
1247 std::string Result = (" " + getImmType() + " Imm = ").str();
Daniel Sanders5cd5b632017-10-13 20:42:18 +00001248 if (immCodeUsesAPFloat())
1249 Result += "cast<ConstantFPSDNode>(Node)->getValueAPF();\n";
1250 else if (immCodeUsesAPInt())
1251 Result += "cast<ConstantSDNode>(Node)->getAPIntValue();\n";
1252 else
1253 Result += "cast<ConstantSDNode>(Node)->getSExtValue();\n";
Daniel Sanders91007462017-10-15 02:06:44 +00001254 return Result + ImmCode;
Chris Lattner7ed13912011-04-17 22:05:17 +00001255 }
Simon Pilgrim4f7a8122017-09-22 16:57:28 +00001256
Chris Lattner7ed13912011-04-17 22:05:17 +00001257 // Handle arbitrary node predicates.
Daniel Sandersb10e0a22017-10-15 19:01:32 +00001258 assert(hasPredCode() && "Don't have any predicate code!");
Simon Pilgrime4d6a6e2017-10-14 21:27:53 +00001259 StringRef ClassName;
Chris Lattner54379062011-04-17 21:38:24 +00001260 if (PatFragRec->getOnlyTree()->isLeaf())
1261 ClassName = "SDNode";
1262 else {
1263 Record *Op = PatFragRec->getOnlyTree()->getOperator();
1264 ClassName = PatFragRec->getDAGPatterns().getSDNodeInfo(Op).getSDClassName();
1265 }
1266 std::string Result;
1267 if (ClassName == "SDNode")
1268 Result = " SDNode *N = Node;\n";
1269 else
Simon Pilgrime4d6a6e2017-10-14 21:27:53 +00001270 Result = " auto *N = cast<" + ClassName.str() + ">(Node);\n";
Simon Pilgrim4f7a8122017-09-22 16:57:28 +00001271
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001272 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
Scott Michel327d0652008-03-05 17:49:05 +00001273}
1274
Chris Lattner6cefb772008-01-05 22:25:12 +00001275//===----------------------------------------------------------------------===//
Dan Gohman22bb3112008-08-22 00:20:26 +00001276// PatternToMatch implementation
1277//
1278
Chris Lattner48e86db2010-03-29 01:40:38 +00001279/// getPatternSize - Return the 'size' of this pattern. We want to match large
1280/// patterns before small ones. This is used to determine the size of a
1281/// pattern.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001282static unsigned getPatternSize(const TreePatternNode *P,
Chris Lattner48e86db2010-03-29 01:40:38 +00001283 const CodeGenDAGPatterns &CGP) {
1284 unsigned Size = 3; // The node itself.
1285 // If the root node is a ConstantSDNode, increases its size.
1286 // e.g. (set R32:$dst, 0).
Florian Hahn74dff3b2018-06-14 20:32:58 +00001287 if (P->isLeaf() && isa<IntInit>(P->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +00001288 Size += 2;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001289
Florian Hahn74dff3b2018-06-14 20:32:58 +00001290 if (const ComplexPattern *AM = P->getComplexPatternInfo(CGP)) {
Peter Collingbourne027f4d02016-11-09 23:53:43 +00001291 Size += AM->getComplexity();
Tim Northoveree8d5c32014-05-20 11:52:46 +00001292 // We don't want to count any children twice, so return early.
1293 return Size;
1294 }
1295
Chris Lattner48e86db2010-03-29 01:40:38 +00001296 // If this node has some predicate function that must match, it adds to the
1297 // complexity of this node.
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001298 if (!P->getPredicateCalls().empty())
Chris Lattner48e86db2010-03-29 01:40:38 +00001299 ++Size;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001300
Chris Lattner48e86db2010-03-29 01:40:38 +00001301 // Count children in the count if they are also nodes.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001302 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
1303 const TreePatternNode *Child = P->getChild(i);
1304 if (!Child->isLeaf() && Child->getNumTypes()) {
Simon Pilgrim1cdda232018-08-15 20:41:19 +00001305 const TypeSetByHwMode &T0 = Child->getExtType(0);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001306 // At this point, all variable type sets should be simple, i.e. only
1307 // have a default mode.
1308 if (T0.getMachineValueType() != MVT::Other) {
1309 Size += getPatternSize(Child, CGP);
1310 continue;
1311 }
1312 }
Florian Hahn74dff3b2018-06-14 20:32:58 +00001313 if (Child->isLeaf()) {
1314 if (isa<IntInit>(Child->getLeafValue()))
Chris Lattner48e86db2010-03-29 01:40:38 +00001315 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Florian Hahn74dff3b2018-06-14 20:32:58 +00001316 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner48e86db2010-03-29 01:40:38 +00001317 Size += getPatternSize(Child, CGP);
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001318 else if (!Child->getPredicateCalls().empty())
Chris Lattner48e86db2010-03-29 01:40:38 +00001319 ++Size;
1320 }
1321 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001322
Chris Lattner48e86db2010-03-29 01:40:38 +00001323 return Size;
1324}
1325
1326/// Compute the complexity metric for the input pattern. This roughly
1327/// corresponds to the number of nodes that are covered.
Tom Stellardf3b62df2014-08-01 00:32:36 +00001328int PatternToMatch::
Chris Lattner48e86db2010-03-29 01:40:38 +00001329getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
Florian Hahn74dff3b2018-06-14 20:32:58 +00001330 return getPatternSize(getSrcPattern(), CGP) + getAddedComplexity();
Chris Lattner48e86db2010-03-29 01:40:38 +00001331}
1332
Dan Gohman22bb3112008-08-22 00:20:26 +00001333/// getPredicateCheck - Return a single string containing all of this
1334/// pattern's predicates concatenated with "&&" operators.
1335///
1336std::string PatternToMatch::getPredicateCheck() const {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001337 SmallVector<const Predicate*,4> PredList;
1338 for (const Predicate &P : Predicates)
1339 PredList.push_back(&P);
Fangrui Song3b35e172018-09-27 02:13:45 +00001340 llvm::sort(PredList, deref<llvm::less>());
Craig Topper5476e442015-11-27 05:44:04 +00001341
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001342 std::string Check;
1343 for (unsigned i = 0, e = PredList.size(); i != e; ++i) {
1344 if (i != 0)
1345 Check += " && ";
1346 Check += '(' + PredList[i]->getCondString() + ')';
Craig Topper5476e442015-11-27 05:44:04 +00001347 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001348 return Check;
Dan Gohman22bb3112008-08-22 00:20:26 +00001349}
1350
1351//===----------------------------------------------------------------------===//
Chris Lattner6cefb772008-01-05 22:25:12 +00001352// SDTypeConstraint implementation
1353//
1354
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001355SDTypeConstraint::SDTypeConstraint(Record *R, const CodeGenHwModes &CGH) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001356 OperandNo = R->getValueAsInt("OperandNum");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001357
Chris Lattner6cefb772008-01-05 22:25:12 +00001358 if (R->isSubClassOf("SDTCisVT")) {
1359 ConstraintType = SDTCisVT;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001360 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1361 for (const auto &P : VVT)
1362 if (P.second == MVT::isVoid)
1363 PrintFatalError(R->getLoc(), "Cannot use 'Void' as type to SDTCisVT");
Chris Lattner6cefb772008-01-05 22:25:12 +00001364 } else if (R->isSubClassOf("SDTCisPtrTy")) {
1365 ConstraintType = SDTCisPtrTy;
1366 } else if (R->isSubClassOf("SDTCisInt")) {
1367 ConstraintType = SDTCisInt;
1368 } else if (R->isSubClassOf("SDTCisFP")) {
1369 ConstraintType = SDTCisFP;
Bob Wilson36e3e662009-08-12 22:30:59 +00001370 } else if (R->isSubClassOf("SDTCisVec")) {
1371 ConstraintType = SDTCisVec;
Chris Lattner6cefb772008-01-05 22:25:12 +00001372 } else if (R->isSubClassOf("SDTCisSameAs")) {
1373 ConstraintType = SDTCisSameAs;
1374 x.SDTCisSameAs_Info.OtherOperandNum = R->getValueAsInt("OtherOperandNum");
1375 } else if (R->isSubClassOf("SDTCisVTSmallerThanOp")) {
1376 ConstraintType = SDTCisVTSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001377 x.SDTCisVTSmallerThanOp_Info.OtherOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +00001378 R->getValueAsInt("OtherOperandNum");
1379 } else if (R->isSubClassOf("SDTCisOpSmallerThanOp")) {
1380 ConstraintType = SDTCisOpSmallerThanOp;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001381 x.SDTCisOpSmallerThanOp_Info.BigOperandNum =
Chris Lattner6cefb772008-01-05 22:25:12 +00001382 R->getValueAsInt("BigOperandNum");
Nate Begemanb5af3342008-02-09 01:37:05 +00001383 } else if (R->isSubClassOf("SDTCisEltOfVec")) {
1384 ConstraintType = SDTCisEltOfVec;
Chris Lattner2cacec52010-03-15 06:00:16 +00001385 x.SDTCisEltOfVec_Info.OtherOperandNum = R->getValueAsInt("OtherOpNum");
David Greene60322692011-01-24 20:53:18 +00001386 } else if (R->isSubClassOf("SDTCisSubVecOfVec")) {
1387 ConstraintType = SDTCisSubVecOfVec;
1388 x.SDTCisSubVecOfVec_Info.OtherOperandNum =
1389 R->getValueAsInt("OtherOpNum");
Craig Topper8ad519f2015-03-05 07:11:34 +00001390 } else if (R->isSubClassOf("SDTCVecEltisVT")) {
1391 ConstraintType = SDTCVecEltisVT;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001392 VVT = getValueTypeByHwMode(R->getValueAsDef("VT"), CGH);
1393 for (const auto &P : VVT) {
1394 MVT T = P.second;
1395 if (T.isVector())
1396 PrintFatalError(R->getLoc(),
1397 "Cannot use vector type as SDTCVecEltisVT");
1398 if (!T.isInteger() && !T.isFloatingPoint())
1399 PrintFatalError(R->getLoc(), "Must use integer or floating point type "
1400 "as SDTCVecEltisVT");
1401 }
Craig Topper8ad519f2015-03-05 07:11:34 +00001402 } else if (R->isSubClassOf("SDTCisSameNumEltsAs")) {
1403 ConstraintType = SDTCisSameNumEltsAs;
1404 x.SDTCisSameNumEltsAs_Info.OtherOperandNum =
1405 R->getValueAsInt("OtherOperandNum");
Craig Topperce6f7432015-11-26 07:02:18 +00001406 } else if (R->isSubClassOf("SDTCisSameSizeAs")) {
1407 ConstraintType = SDTCisSameSizeAs;
1408 x.SDTCisSameSizeAs_Info.OtherOperandNum =
1409 R->getValueAsInt("OtherOperandNum");
Chris Lattner6cefb772008-01-05 22:25:12 +00001410 } else {
James Y Knightaeda4902015-05-11 22:17:13 +00001411 PrintFatalError("Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00001412 }
1413}
1414
1415/// getOperandNum - Return the node corresponding to operand #OpNo in tree
Chris Lattner2e68a022010-03-19 21:56:21 +00001416/// N, and the result number in ResNo.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001417static TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
Chris Lattner2e68a022010-03-19 21:56:21 +00001418 const SDNodeInfo &NodeInfo,
1419 unsigned &ResNo) {
1420 unsigned NumResults = NodeInfo.getNumResults();
1421 if (OpNo < NumResults) {
1422 ResNo = OpNo;
1423 return N;
1424 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001425
Chris Lattner2e68a022010-03-19 21:56:21 +00001426 OpNo -= NumResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001427
Florian Hahn74dff3b2018-06-14 20:32:58 +00001428 if (OpNo >= N->getNumChildren()) {
James Y Knightaeda4902015-05-11 22:17:13 +00001429 std::string S;
1430 raw_string_ostream OS(S);
1431 OS << "Invalid operand number in type constraint "
Chris Lattner2e68a022010-03-19 21:56:21 +00001432 << (OpNo+NumResults) << " ";
Florian Hahn74dff3b2018-06-14 20:32:58 +00001433 N->print(OS);
James Y Knightaeda4902015-05-11 22:17:13 +00001434 PrintFatalError(OS.str());
Chris Lattner6cefb772008-01-05 22:25:12 +00001435 }
1436
Florian Hahn74dff3b2018-06-14 20:32:58 +00001437 return N->getChild(OpNo);
Chris Lattner6cefb772008-01-05 22:25:12 +00001438}
1439
1440/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1441/// constraint to the nodes operands. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001442/// change, false otherwise. If a type contradiction is found, flag an error.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001443bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode *N,
Chris Lattner6cefb772008-01-05 22:25:12 +00001444 const SDNodeInfo &NodeInfo,
1445 TreePattern &TP) const {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001446 if (TP.hasError())
1447 return false;
1448
Chris Lattner2e68a022010-03-19 21:56:21 +00001449 unsigned ResNo = 0; // The result number being referenced.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001450 TreePatternNode *NodeToApply = getOperandNum(OperandNo, N, NodeInfo, ResNo);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001451 TypeInfer &TI = TP.getInfer();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001452
Chris Lattner6cefb772008-01-05 22:25:12 +00001453 switch (ConstraintType) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001454 case SDTCisVT:
1455 // Operand must be a particular type.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001456 return NodeToApply->UpdateNodeType(ResNo, VVT, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001457 case SDTCisPtrTy:
Chris Lattner6cefb772008-01-05 22:25:12 +00001458 // Operand must be same as target pointer type.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001459 return NodeToApply->UpdateNodeType(ResNo, MVT::iPTR, TP);
Chris Lattner2cacec52010-03-15 06:00:16 +00001460 case SDTCisInt:
1461 // Require it to be one of the legal integer VTs.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001462 return TI.EnforceInteger(NodeToApply->getExtType(ResNo));
Chris Lattner2cacec52010-03-15 06:00:16 +00001463 case SDTCisFP:
1464 // Require it to be one of the legal fp VTs.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001465 return TI.EnforceFloatingPoint(NodeToApply->getExtType(ResNo));
Chris Lattner2cacec52010-03-15 06:00:16 +00001466 case SDTCisVec:
1467 // Require it to be one of the legal vector VTs.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001468 return TI.EnforceVector(NodeToApply->getExtType(ResNo));
Chris Lattner6cefb772008-01-05 22:25:12 +00001469 case SDTCisSameAs: {
Chris Lattner2e68a022010-03-19 21:56:21 +00001470 unsigned OResNo = 0;
Florian Hahn74dff3b2018-06-14 20:32:58 +00001471 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +00001472 getOperandNum(x.SDTCisSameAs_Info.OtherOperandNum, N, NodeInfo, OResNo);
Florian Hahn74dff3b2018-06-14 20:32:58 +00001473 return NodeToApply->UpdateNodeType(ResNo, OtherNode->getExtType(OResNo),TP)|
1474 OtherNode->UpdateNodeType(OResNo,NodeToApply->getExtType(ResNo),TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00001475 }
1476 case SDTCisVTSmallerThanOp: {
1477 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1478 // have an integer type that is smaller than the VT.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001479 if (!NodeToApply->isLeaf() ||
1480 !isa<DefInit>(NodeToApply->getLeafValue()) ||
1481 !static_cast<DefInit*>(NodeToApply->getLeafValue())->getDef()
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001482 ->isSubClassOf("ValueType")) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00001483 TP.error(N->getOperator()->getName() + " expects a VT operand!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001484 return false;
1485 }
Florian Hahn74dff3b2018-06-14 20:32:58 +00001486 DefInit *DI = static_cast<DefInit*>(NodeToApply->getLeafValue());
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001487 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1488 auto VVT = getValueTypeByHwMode(DI->getDef(), T.getHwModes());
1489 TypeSetByHwMode TypeListTmp(VVT);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001490
Chris Lattner2e68a022010-03-19 21:56:21 +00001491 unsigned OResNo = 0;
Florian Hahn74dff3b2018-06-14 20:32:58 +00001492 TreePatternNode *OtherNode =
Chris Lattner2e68a022010-03-19 21:56:21 +00001493 getOperandNum(x.SDTCisVTSmallerThanOp_Info.OtherOperandNum, N, NodeInfo,
1494 OResNo);
Chris Lattner2cacec52010-03-15 06:00:16 +00001495
Florian Hahn74dff3b2018-06-14 20:32:58 +00001496 return TI.EnforceSmallerThan(TypeListTmp, OtherNode->getExtType(OResNo));
Chris Lattner6cefb772008-01-05 22:25:12 +00001497 }
1498 case SDTCisOpSmallerThanOp: {
Chris Lattner2e68a022010-03-19 21:56:21 +00001499 unsigned BResNo = 0;
Florian Hahn74dff3b2018-06-14 20:32:58 +00001500 TreePatternNode *BigOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +00001501 getOperandNum(x.SDTCisOpSmallerThanOp_Info.BigOperandNum, N, NodeInfo,
1502 BResNo);
Florian Hahn74dff3b2018-06-14 20:32:58 +00001503 return TI.EnforceSmallerThan(NodeToApply->getExtType(ResNo),
1504 BigOperand->getExtType(BResNo));
Chris Lattner6cefb772008-01-05 22:25:12 +00001505 }
Nate Begemanb5af3342008-02-09 01:37:05 +00001506 case SDTCisEltOfVec: {
Chris Lattner2e68a022010-03-19 21:56:21 +00001507 unsigned VResNo = 0;
Florian Hahn74dff3b2018-06-14 20:32:58 +00001508 TreePatternNode *VecOperand =
Chris Lattner2e68a022010-03-19 21:56:21 +00001509 getOperandNum(x.SDTCisEltOfVec_Info.OtherOperandNum, N, NodeInfo,
1510 VResNo);
Chris Lattner66fb9d22010-03-24 00:01:16 +00001511 // Filter vector types out of VecOperand that don't have the right element
1512 // type.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001513 return TI.EnforceVectorEltTypeIs(VecOperand->getExtType(VResNo),
1514 NodeToApply->getExtType(ResNo));
Nate Begemanb5af3342008-02-09 01:37:05 +00001515 }
David Greene60322692011-01-24 20:53:18 +00001516 case SDTCisSubVecOfVec: {
1517 unsigned VResNo = 0;
Florian Hahn74dff3b2018-06-14 20:32:58 +00001518 TreePatternNode *BigVecOperand =
David Greene60322692011-01-24 20:53:18 +00001519 getOperandNum(x.SDTCisSubVecOfVec_Info.OtherOperandNum, N, NodeInfo,
1520 VResNo);
1521
1522 // Filter vector types out of BigVecOperand that don't have the
1523 // right subvector type.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001524 return TI.EnforceVectorSubVectorTypeIs(BigVecOperand->getExtType(VResNo),
1525 NodeToApply->getExtType(ResNo));
David Greene60322692011-01-24 20:53:18 +00001526 }
Craig Topper8ad519f2015-03-05 07:11:34 +00001527 case SDTCVecEltisVT: {
Florian Hahn74dff3b2018-06-14 20:32:58 +00001528 return TI.EnforceVectorEltTypeIs(NodeToApply->getExtType(ResNo), VVT);
Craig Topper8ad519f2015-03-05 07:11:34 +00001529 }
1530 case SDTCisSameNumEltsAs: {
1531 unsigned OResNo = 0;
Florian Hahn74dff3b2018-06-14 20:32:58 +00001532 TreePatternNode *OtherNode =
Craig Topper8ad519f2015-03-05 07:11:34 +00001533 getOperandNum(x.SDTCisSameNumEltsAs_Info.OtherOperandNum,
1534 N, NodeInfo, OResNo);
Florian Hahn74dff3b2018-06-14 20:32:58 +00001535 return TI.EnforceSameNumElts(OtherNode->getExtType(OResNo),
1536 NodeToApply->getExtType(ResNo));
Craig Topper8ad519f2015-03-05 07:11:34 +00001537 }
Craig Topperce6f7432015-11-26 07:02:18 +00001538 case SDTCisSameSizeAs: {
1539 unsigned OResNo = 0;
Florian Hahn74dff3b2018-06-14 20:32:58 +00001540 TreePatternNode *OtherNode =
Craig Topperce6f7432015-11-26 07:02:18 +00001541 getOperandNum(x.SDTCisSameSizeAs_Info.OtherOperandNum,
1542 N, NodeInfo, OResNo);
Florian Hahn74dff3b2018-06-14 20:32:58 +00001543 return TI.EnforceSameSize(OtherNode->getExtType(OResNo),
1544 NodeToApply->getExtType(ResNo));
Craig Topperce6f7432015-11-26 07:02:18 +00001545 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001546 }
David Blaikie58bd1512012-01-17 07:00:13 +00001547 llvm_unreachable("Invalid ConstraintType!");
Chris Lattner6cefb772008-01-05 22:25:12 +00001548}
1549
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001550// Update the node type to match an instruction operand or result as specified
1551// in the ins or outs lists on the instruction definition. Return true if the
1552// type was actually changed.
1553bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1554 Record *Operand,
1555 TreePattern &TP) {
1556 // The 'unknown' operand indicates that types should be inferred from the
1557 // context.
1558 if (Operand->isSubClassOf("unknown_class"))
1559 return false;
1560
1561 // The Operand class specifies a type directly.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001562 if (Operand->isSubClassOf("Operand")) {
1563 Record *R = Operand->getValueAsDef("Type");
1564 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1565 return UpdateNodeType(ResNo, getValueTypeByHwMode(R, T.getHwModes()), TP);
1566 }
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001567
1568 // PointerLikeRegClass has a type that is determined at runtime.
1569 if (Operand->isSubClassOf("PointerLikeRegClass"))
1570 return UpdateNodeType(ResNo, MVT::iPTR, TP);
1571
1572 // Both RegisterClass and RegisterOperand operands derive their types from a
1573 // register class def.
Craig Topper095734c2014-04-15 07:20:03 +00001574 Record *RC = nullptr;
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001575 if (Operand->isSubClassOf("RegisterClass"))
1576 RC = Operand;
1577 else if (Operand->isSubClassOf("RegisterOperand"))
1578 RC = Operand->getValueAsDef("RegClass");
1579
1580 assert(RC && "Unknown operand type");
1581 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1582 return UpdateNodeType(ResNo, Tgt.getRegisterClass(RC).getValueTypes(), TP);
1583}
1584
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001585bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1586 for (unsigned i = 0, e = Types.size(); i != e; ++i)
1587 if (!TP.getInfer().isConcrete(Types[i], true))
1588 return true;
1589 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00001590 if (getChild(i)->ContainsUnresolvedType(TP))
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001591 return true;
1592 return false;
1593}
1594
1595bool TreePatternNode::hasProperTypeByHwMode() const {
1596 for (const TypeSetByHwMode &S : Types)
1597 if (!S.isDefaultOnly())
1598 return true;
Florian Hahn0b596f02018-05-30 21:00:18 +00001599 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001600 if (C->hasProperTypeByHwMode())
1601 return true;
1602 return false;
1603}
1604
1605bool TreePatternNode::hasPossibleType() const {
1606 for (const TypeSetByHwMode &S : Types)
1607 if (!S.isPossible())
1608 return false;
Florian Hahn0b596f02018-05-30 21:00:18 +00001609 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001610 if (!C->hasPossibleType())
1611 return false;
1612 return true;
1613}
1614
1615bool TreePatternNode::setDefaultMode(unsigned Mode) {
1616 for (TypeSetByHwMode &S : Types) {
1617 S.makeSimple(Mode);
1618 // Check if the selected mode had a type conflict.
1619 if (S.get(DefaultMode).empty())
1620 return false;
1621 }
Florian Hahn0b596f02018-05-30 21:00:18 +00001622 for (const TreePatternNodePtr &C : Children)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001623 if (!C->setDefaultMode(Mode))
1624 return false;
1625 return true;
1626}
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00001627
Chris Lattner6cefb772008-01-05 22:25:12 +00001628//===----------------------------------------------------------------------===//
1629// SDNodeInfo implementation
1630//
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001631SDNodeInfo::SDNodeInfo(Record *R, const CodeGenHwModes &CGH) : Def(R) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001632 EnumName = R->getValueAsString("Opcode");
1633 SDClassName = R->getValueAsString("SDClass");
1634 Record *TypeProfile = R->getValueAsDef("TypeProfile");
1635 NumResults = TypeProfile->getValueAsInt("NumResults");
1636 NumOperands = TypeProfile->getValueAsInt("NumOperands");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001637
Chris Lattner6cefb772008-01-05 22:25:12 +00001638 // Parse the properties.
Matt Arsenault082879a2017-12-20 19:36:28 +00001639 Properties = parseSDPatternOperatorProperties(R);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001640
Chris Lattner6cefb772008-01-05 22:25:12 +00001641 // Parse the type constraints.
1642 std::vector<Record*> ConstraintList =
1643 TypeProfile->getValueAsListOfDefs("Constraints");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001644 for (Record *R : ConstraintList)
1645 TypeConstraints.emplace_back(R, CGH);
Chris Lattner6cefb772008-01-05 22:25:12 +00001646}
1647
Chris Lattner22579812010-02-28 00:22:30 +00001648/// getKnownType - If the type constraints on this node imply a fixed type
1649/// (e.g. all stores return void, etc), then return it as an
Chris Lattneraac5b5b2010-03-19 01:14:27 +00001650/// MVT::SimpleValueType. Otherwise, return EEVT::Other.
Chris Lattner084df622010-03-24 00:41:19 +00001651MVT::SimpleValueType SDNodeInfo::getKnownType(unsigned ResNo) const {
Chris Lattner22579812010-02-28 00:22:30 +00001652 unsigned NumResults = getNumResults();
1653 assert(NumResults <= 1 &&
1654 "We only work with nodes with zero or one result so far!");
Chris Lattner084df622010-03-24 00:41:19 +00001655 assert(ResNo == 0 && "Only handles single result nodes so far");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001656
Craig Topper16642322015-11-22 20:46:24 +00001657 for (const SDTypeConstraint &Constraint : TypeConstraints) {
Chris Lattner22579812010-02-28 00:22:30 +00001658 // Make sure that this applies to the correct node result.
Craig Topper16642322015-11-22 20:46:24 +00001659 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
Chris Lattner22579812010-02-28 00:22:30 +00001660 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001661
Craig Topper16642322015-11-22 20:46:24 +00001662 switch (Constraint.ConstraintType) {
Chris Lattner22579812010-02-28 00:22:30 +00001663 default: break;
1664 case SDTypeConstraint::SDTCisVT:
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001665 if (Constraint.VVT.isSimple())
1666 return Constraint.VVT.getSimple().SimpleTy;
1667 break;
Chris Lattner22579812010-02-28 00:22:30 +00001668 case SDTypeConstraint::SDTCisPtrTy:
1669 return MVT::iPTR;
1670 }
1671 }
Chris Lattneraac5b5b2010-03-19 01:14:27 +00001672 return MVT::Other;
Chris Lattner22579812010-02-28 00:22:30 +00001673}
1674
Chris Lattner6cefb772008-01-05 22:25:12 +00001675//===----------------------------------------------------------------------===//
1676// TreePatternNode implementation
1677//
1678
Chris Lattnerd7349192010-03-19 21:37:09 +00001679static unsigned GetNumNodeResults(Record *Operator, CodeGenDAGPatterns &CDP) {
1680 if (Operator->getName() == "set" ||
Chris Lattner310adf12010-03-27 02:53:27 +00001681 Operator->getName() == "implicit")
Chris Lattnerd7349192010-03-19 21:37:09 +00001682 return 0; // All return nothing.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001683
Chris Lattner93dc92e2010-03-22 20:56:36 +00001684 if (Operator->isSubClassOf("Intrinsic"))
1685 return CDP.getIntrinsic(Operator).IS.RetVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001686
Chris Lattnerd7349192010-03-19 21:37:09 +00001687 if (Operator->isSubClassOf("SDNode"))
1688 return CDP.getSDNodeInfo(Operator).getNumResults();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001689
Ulrich Weigand3a904262018-07-13 13:18:00 +00001690 if (Operator->isSubClassOf("PatFrags")) {
Chris Lattnerd7349192010-03-19 21:37:09 +00001691 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1692 // the forward reference case where one pattern fragment references another
1693 // before it is processed.
Ulrich Weigand3a904262018-07-13 13:18:00 +00001694 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(Operator)) {
1695 // The number of results of a fragment with alternative records is the
1696 // maximum number of results across all alternatives.
1697 unsigned NumResults = 0;
1698 for (auto T : PFRec->getTrees())
1699 NumResults = std::max(NumResults, T->getNumTypes());
1700 return NumResults;
1701 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001702
Ulrich Weigand3a904262018-07-13 13:18:00 +00001703 ListInit *LI = Operator->getValueAsListInit("Fragments");
1704 assert(LI && "Invalid Fragment");
1705 unsigned NumResults = 0;
1706 for (Init *I : LI->getValues()) {
1707 Record *Op = nullptr;
1708 if (DagInit *Dag = dyn_cast<DagInit>(I))
1709 if (DefInit *DI = dyn_cast<DefInit>(Dag->getOperator()))
1710 Op = DI->getDef();
1711 assert(Op && "Invalid Fragment");
1712 NumResults = std::max(NumResults, GetNumNodeResults(Op, CDP));
1713 }
1714 return NumResults;
Chris Lattnerd7349192010-03-19 21:37:09 +00001715 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001716
Chris Lattnerd7349192010-03-19 21:37:09 +00001717 if (Operator->isSubClassOf("Instruction")) {
1718 CodeGenInstruction &InstInfo = CDP.getTargetInfo().getInstruction(Operator);
Chris Lattner0be6fe72010-03-27 19:15:02 +00001719
Craig Topper3220d112015-03-20 05:09:06 +00001720 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
1721
1722 // Subtract any defaulted outputs.
1723 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
1724 Record *OperandNode = InstInfo.Operands[i].Rec;
1725
1726 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
1727 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
1728 --NumDefsToAdd;
1729 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001730
Chris Lattner9414ae52010-03-27 20:09:24 +00001731 // Add on one implicit def if it has a resolvable type.
1732 if (InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo()) !=MVT::Other)
1733 ++NumDefsToAdd;
Chris Lattner0be6fe72010-03-27 19:15:02 +00001734 return NumDefsToAdd;
Chris Lattnerd7349192010-03-19 21:37:09 +00001735 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001736
Chris Lattnerd7349192010-03-19 21:37:09 +00001737 if (Operator->isSubClassOf("SDNodeXForm"))
1738 return 1; // FIXME: Generalize SDNodeXForm
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001739
Hal Finkel6fa99612014-01-02 20:47:05 +00001740 if (Operator->isSubClassOf("ValueType"))
1741 return 1; // A type-cast of one result.
1742
Tim Northoveree8d5c32014-05-20 11:52:46 +00001743 if (Operator->isSubClassOf("ComplexPattern"))
1744 return 1;
1745
Matthias Braun88d20752017-01-28 02:02:38 +00001746 errs() << *Operator;
James Y Knightaeda4902015-05-11 22:17:13 +00001747 PrintFatalError("Unhandled node in GetNumNodeResults");
Chris Lattnerd7349192010-03-19 21:37:09 +00001748}
1749
1750void TreePatternNode::print(raw_ostream &OS) const {
1751 if (isLeaf())
1752 OS << *getLeafValue();
1753 else
1754 OS << '(' << getOperator()->getName();
1755
Zachary Turnere4442992017-09-20 18:01:40 +00001756 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
1757 OS << ':';
1758 getExtType(i).writeToStream(OS);
1759 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001760
1761 if (!isLeaf()) {
1762 if (getNumChildren() != 0) {
1763 OS << " ";
Florian Hahn74dff3b2018-06-14 20:32:58 +00001764 getChild(0)->print(OS);
Chris Lattner6cefb772008-01-05 22:25:12 +00001765 for (unsigned i = 1, e = getNumChildren(); i != e; ++i) {
1766 OS << ", ";
Florian Hahn74dff3b2018-06-14 20:32:58 +00001767 getChild(i)->print(OS);
Chris Lattner6cefb772008-01-05 22:25:12 +00001768 }
1769 }
1770 OS << ")";
1771 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001772
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001773 for (const TreePredicateCall &Pred : PredicateCalls) {
1774 OS << "<<P:";
1775 if (Pred.Scope)
1776 OS << Pred.Scope << ":";
1777 OS << Pred.Fn.getFnName() << ">>";
1778 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001779 if (TransformFn)
1780 OS << "<<X:" << TransformFn->getName() << ">>";
1781 if (!getName().empty())
1782 OS << ":$" << getName();
1783
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001784 for (const ScopedName &Name : NamesAsPredicateArg)
1785 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
Chris Lattner6cefb772008-01-05 22:25:12 +00001786}
1787void TreePatternNode::dump() const {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001788 print(errs());
Chris Lattner6cefb772008-01-05 22:25:12 +00001789}
1790
Scott Michel327d0652008-03-05 17:49:05 +00001791/// isIsomorphicTo - Return true if this node is recursively
1792/// isomorphic to the specified node. For this comparison, the node's
1793/// entire state is considered. The assigned name is ignored, since
1794/// nodes with differing names are considered isomorphic. However, if
1795/// the assigned name is present in the dependent variable set, then
1796/// the assigned name is considered significant and the node is
1797/// isomorphic if the names match.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001798bool TreePatternNode::isIsomorphicTo(const TreePatternNode *N,
Scott Michel327d0652008-03-05 17:49:05 +00001799 const MultipleUseVarSet &DepVars) const {
Florian Hahn74dff3b2018-06-14 20:32:58 +00001800 if (N == this) return true;
1801 if (N->isLeaf() != isLeaf() || getExtTypes() != N->getExtTypes() ||
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001802 getPredicateCalls() != N->getPredicateCalls() ||
Florian Hahn74dff3b2018-06-14 20:32:58 +00001803 getTransformFn() != N->getTransformFn())
Chris Lattner6cefb772008-01-05 22:25:12 +00001804 return false;
1805
1806 if (isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00001807 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00001808 if (DefInit *NDI = dyn_cast<DefInit>(N->getLeafValue())) {
Chris Lattner71a2cb22008-03-20 01:22:40 +00001809 return ((DI->getDef() == NDI->getDef())
1810 && (DepVars.find(getName()) == DepVars.end()
Florian Hahn74dff3b2018-06-14 20:32:58 +00001811 || getName() == N->getName()));
Scott Michel327d0652008-03-05 17:49:05 +00001812 }
1813 }
Florian Hahn74dff3b2018-06-14 20:32:58 +00001814 return getLeafValue() == N->getLeafValue();
Chris Lattner6cefb772008-01-05 22:25:12 +00001815 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001816
Florian Hahn74dff3b2018-06-14 20:32:58 +00001817 if (N->getOperator() != getOperator() ||
1818 N->getNumChildren() != getNumChildren()) return false;
Chris Lattner6cefb772008-01-05 22:25:12 +00001819 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00001820 if (!getChild(i)->isIsomorphicTo(N->getChild(i), DepVars))
Chris Lattner6cefb772008-01-05 22:25:12 +00001821 return false;
1822 return true;
1823}
1824
1825/// clone - Make a copy of this tree and all of its children.
1826///
Florian Hahn0b596f02018-05-30 21:00:18 +00001827TreePatternNodePtr TreePatternNode::clone() const {
1828 TreePatternNodePtr New;
Chris Lattner6cefb772008-01-05 22:25:12 +00001829 if (isLeaf()) {
Florian Hahn0b596f02018-05-30 21:00:18 +00001830 New = std::make_shared<TreePatternNode>(getLeafValue(), getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001831 } else {
Florian Hahn0b596f02018-05-30 21:00:18 +00001832 std::vector<TreePatternNodePtr> CChildren;
Chris Lattner6cefb772008-01-05 22:25:12 +00001833 CChildren.reserve(Children.size());
1834 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00001835 CChildren.push_back(getChild(i)->clone());
Craig Toppercfe3c912018-07-15 06:52:49 +00001836 New = std::make_shared<TreePatternNode>(getOperator(), std::move(CChildren),
Florian Hahn0b596f02018-05-30 21:00:18 +00001837 getNumTypes());
Chris Lattner6cefb772008-01-05 22:25:12 +00001838 }
1839 New->setName(getName());
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001840 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
Chris Lattnerd7349192010-03-19 21:37:09 +00001841 New->Types = Types;
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001842 New->setPredicateCalls(getPredicateCalls());
Chris Lattner6cefb772008-01-05 22:25:12 +00001843 New->setTransformFn(getTransformFn());
1844 return New;
1845}
1846
Chris Lattner47661322010-02-14 22:22:58 +00001847/// RemoveAllTypes - Recursively strip all the types of this tree.
1848void TreePatternNode::RemoveAllTypes() {
Craig Topper5f579032015-11-22 20:46:22 +00001849 // Reset to unknown type.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00001850 std::fill(Types.begin(), Types.end(), TypeSetByHwMode());
Chris Lattner47661322010-02-14 22:22:58 +00001851 if (isLeaf()) return;
1852 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00001853 getChild(i)->RemoveAllTypes();
Chris Lattner47661322010-02-14 22:22:58 +00001854}
1855
1856
Chris Lattner6cefb772008-01-05 22:25:12 +00001857/// SubstituteFormalArguments - Replace the formal arguments in this tree
1858/// with actual values specified by ArgMap.
Florian Hahn0b596f02018-05-30 21:00:18 +00001859void TreePatternNode::SubstituteFormalArguments(
1860 std::map<std::string, TreePatternNodePtr> &ArgMap) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001861 if (isLeaf()) return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001862
Chris Lattner6cefb772008-01-05 22:25:12 +00001863 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00001864 TreePatternNode *Child = getChild(i);
1865 if (Child->isLeaf()) {
1866 Init *Val = Child->getLeafValue();
Hal Finkelc72cf872014-02-28 00:26:56 +00001867 // Note that, when substituting into an output pattern, Val might be an
1868 // UnsetInit.
1869 if (isa<UnsetInit>(Val) || (isa<DefInit>(Val) &&
1870 cast<DefInit>(Val)->getDef()->getName() == "node")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001871 // We found a use of a formal argument, replace it with its value.
Florian Hahn74dff3b2018-06-14 20:32:58 +00001872 TreePatternNodePtr NewChild = ArgMap[Child->getName()];
Dan Gohman0540e172008-10-15 06:17:21 +00001873 assert(NewChild && "Couldn't find formal argument!");
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001874 assert((Child->getPredicateCalls().empty() ||
1875 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Dan Gohman0540e172008-10-15 06:17:21 +00001876 "Non-empty child predicate clobbered!");
Florian Hahn5cd96b72018-06-14 11:56:19 +00001877 setChild(i, std::move(NewChild));
Chris Lattner6cefb772008-01-05 22:25:12 +00001878 }
1879 } else {
Florian Hahn74dff3b2018-06-14 20:32:58 +00001880 getChild(i)->SubstituteFormalArguments(ArgMap);
Chris Lattner6cefb772008-01-05 22:25:12 +00001881 }
1882 }
1883}
1884
1885
1886/// InlinePatternFragments - If this pattern refers to any pattern
Ulrich Weigand3a904262018-07-13 13:18:00 +00001887/// fragments, return the set of inlined versions (this can be more than
1888/// one if a PatFrags record has multiple alternatives).
1889void TreePatternNode::InlinePatternFragments(
1890 TreePatternNodePtr T, TreePattern &TP,
1891 std::vector<TreePatternNodePtr> &OutAlternatives) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001892
Ulrich Weigand3a904262018-07-13 13:18:00 +00001893 if (TP.hasError())
1894 return;
1895
1896 if (isLeaf()) {
1897 OutAlternatives.push_back(T); // nothing to do.
1898 return;
1899 }
1900
Chris Lattner6cefb772008-01-05 22:25:12 +00001901 Record *Op = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001902
Ulrich Weigand3a904262018-07-13 13:18:00 +00001903 if (!Op->isSubClassOf("PatFrags")) {
1904 if (getNumChildren() == 0) {
1905 OutAlternatives.push_back(T);
1906 return;
1907 }
1908
1909 // Recursively inline children nodes.
1910 std::vector<std::vector<TreePatternNodePtr> > ChildAlternatives;
1911 ChildAlternatives.resize(getNumChildren());
Dan Gohman0540e172008-10-15 06:17:21 +00001912 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
Florian Hahn0b596f02018-05-30 21:00:18 +00001913 TreePatternNodePtr Child = getChildShared(i);
Ulrich Weigand3a904262018-07-13 13:18:00 +00001914 Child->InlinePatternFragments(Child, TP, ChildAlternatives[i]);
1915 // If there are no alternatives for any child, there are no
1916 // alternatives for this expression as whole.
1917 if (ChildAlternatives[i].empty())
1918 return;
Dan Gohman0540e172008-10-15 06:17:21 +00001919
Ulrich Weigand3a904262018-07-13 13:18:00 +00001920 for (auto NewChild : ChildAlternatives[i])
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001921 assert((Child->getPredicateCalls().empty() ||
1922 NewChild->getPredicateCalls() == Child->getPredicateCalls()) &&
Ulrich Weigand3a904262018-07-13 13:18:00 +00001923 "Non-empty child predicate clobbered!");
Dan Gohman0540e172008-10-15 06:17:21 +00001924 }
Ulrich Weigand3a904262018-07-13 13:18:00 +00001925
1926 // The end result is an all-pairs construction of the resultant pattern.
1927 std::vector<unsigned> Idxs;
1928 Idxs.resize(ChildAlternatives.size());
1929 bool NotDone;
1930 do {
1931 // Create the variant and add it to the output list.
1932 std::vector<TreePatternNodePtr> NewChildren;
1933 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
1934 NewChildren.push_back(ChildAlternatives[i][Idxs[i]]);
1935 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Toppercfe3c912018-07-15 06:52:49 +00001936 getOperator(), std::move(NewChildren), getNumTypes());
Ulrich Weigand3a904262018-07-13 13:18:00 +00001937
1938 // Copy over properties.
1939 R->setName(getName());
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001940 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
1941 R->setPredicateCalls(getPredicateCalls());
Ulrich Weigand3a904262018-07-13 13:18:00 +00001942 R->setTransformFn(getTransformFn());
1943 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
1944 R->setType(i, getExtType(i));
Craig Topper0f562fe2018-12-05 00:47:59 +00001945 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
1946 R->setResultIndex(i, getResultIndex(i));
Ulrich Weigand3a904262018-07-13 13:18:00 +00001947
1948 // Register alternative.
1949 OutAlternatives.push_back(R);
1950
1951 // Increment indices to the next permutation by incrementing the
1952 // indices from last index backward, e.g., generate the sequence
1953 // [0, 0], [0, 1], [1, 0], [1, 1].
1954 int IdxsIdx;
1955 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
1956 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
1957 Idxs[IdxsIdx] = 0;
1958 else
1959 break;
1960 }
1961 NotDone = (IdxsIdx >= 0);
1962 } while (NotDone);
1963
1964 return;
Chris Lattner6cefb772008-01-05 22:25:12 +00001965 }
1966
1967 // Otherwise, we found a reference to a fragment. First, look up its
1968 // TreePattern record.
1969 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(Op);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001970
Chris Lattner6cefb772008-01-05 22:25:12 +00001971 // Verify that we are passing the right number of operands.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001972 if (Frag->getNumArgs() != Children.size()) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001973 TP.error("'" + Op->getName() + "' fragment requires " +
Benjamin Kramerca5092a2017-12-28 16:58:54 +00001974 Twine(Frag->getNumArgs()) + " operands!");
Ulrich Weigand3a904262018-07-13 13:18:00 +00001975 return;
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00001976 }
Chris Lattner6cefb772008-01-05 22:25:12 +00001977
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001978 TreePredicateFn PredFn(Frag);
1979 unsigned Scope = 0;
1980 if (TreePredicateFn(Frag).usesOperands())
1981 Scope = TP.getDAGPatterns().allocateScope();
1982
Ulrich Weigand3a904262018-07-13 13:18:00 +00001983 // Compute the map of formal to actual arguments.
1984 std::map<std::string, TreePatternNodePtr> ArgMap;
1985 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001986 TreePatternNodePtr Child = getChildShared(i);
1987 if (Scope != 0) {
1988 Child = Child->clone();
1989 Child->addNameAsPredicateArg(ScopedName(Scope, Frag->getArgName(i)));
1990 }
Ulrich Weigand3a904262018-07-13 13:18:00 +00001991 ArgMap[Frag->getArgName(i)] = Child;
Chris Lattner6cefb772008-01-05 22:25:12 +00001992 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00001993
Ulrich Weigand3a904262018-07-13 13:18:00 +00001994 // Loop over all fragment alternatives.
1995 for (auto Alternative : Frag->getTrees()) {
1996 TreePatternNodePtr FragTree = Alternative->clone();
Dan Gohman0540e172008-10-15 06:17:21 +00001997
Ulrich Weigand3a904262018-07-13 13:18:00 +00001998 if (!PredFn.isAlwaysTrue())
Nicolai Haehnle98272e42018-11-30 14:15:13 +00001999 FragTree->addPredicateCall(PredFn, Scope);
Dan Gohman0540e172008-10-15 06:17:21 +00002000
Ulrich Weigand3a904262018-07-13 13:18:00 +00002001 // Resolve formal arguments to their actual value.
2002 if (Frag->getNumArgs())
2003 FragTree->SubstituteFormalArguments(ArgMap);
2004
2005 // Transfer types. Note that the resolved alternative may have fewer
2006 // (but not more) results than the PatFrags node.
2007 FragTree->setName(getName());
2008 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2009 FragTree->UpdateNodeType(i, getExtType(i), TP);
2010
2011 // Transfer in the old predicates.
Nicolai Haehnle98272e42018-11-30 14:15:13 +00002012 for (const TreePredicateCall &Pred : getPredicateCalls())
2013 FragTree->addPredicateCall(Pred);
Ulrich Weigand3a904262018-07-13 13:18:00 +00002014
2015 // The fragment we inlined could have recursive inlining that is needed. See
2016 // if there are any pattern fragments in it and inline them as needed.
2017 FragTree->InlinePatternFragments(FragTree, TP, OutAlternatives);
2018 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002019}
2020
2021/// getImplicitType - Check to see if the specified record has an implicit
Nick Lewyckyfc4c2552009-06-17 04:23:52 +00002022/// type which should be applied to it. This will infer the type of register
Chris Lattner6cefb772008-01-05 22:25:12 +00002023/// references from the register file information, for example.
2024///
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00002025/// When Unnamed is set, return the type of a DAG operand with no name, such as
2026/// the F8RC register class argument in:
2027///
2028/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2029///
2030/// When Unnamed is false, return the type of a named DAG operand such as the
2031/// GPR:$src operand above.
2032///
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002033static TypeSetByHwMode getImplicitType(Record *R, unsigned ResNo,
2034 bool NotRegisters,
2035 bool Unnamed,
2036 TreePattern &TP) {
2037 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2038
Owen Andersonbea6f612011-06-27 21:06:21 +00002039 // Check to see if this is a register operand.
2040 if (R->isSubClassOf("RegisterOperand")) {
2041 assert(ResNo == 0 && "Regoperand ref only has one result!");
2042 if (NotRegisters)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002043 return TypeSetByHwMode(); // Unknown.
Owen Andersonbea6f612011-06-27 21:06:21 +00002044 Record *RegClass = R->getValueAsDef("RegClass");
2045 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002046 return TypeSetByHwMode(T.getRegisterClass(RegClass).getValueTypes());
Owen Andersonbea6f612011-06-27 21:06:21 +00002047 }
2048
Chris Lattner2cacec52010-03-15 06:00:16 +00002049 // Check to see if this is a register or a register class.
Chris Lattner6cefb772008-01-05 22:25:12 +00002050 if (R->isSubClassOf("RegisterClass")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00002051 assert(ResNo == 0 && "Regclass ref only has one result!");
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00002052 // An unnamed register class represents itself as an i32 immediate, for
2053 // example on a COPY_TO_REGCLASS instruction.
2054 if (Unnamed)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002055 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00002056
2057 // In a named operand, the register class provides the possible set of
2058 // types.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002059 if (NotRegisters)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002060 return TypeSetByHwMode(); // Unknown.
Chris Lattner2cacec52010-03-15 06:00:16 +00002061 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002062 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
Chris Lattner640a3f52010-03-23 23:50:31 +00002063 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002064
Ulrich Weigand3a904262018-07-13 13:18:00 +00002065 if (R->isSubClassOf("PatFrags")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00002066 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
Chris Lattner6cefb772008-01-05 22:25:12 +00002067 // Pattern fragment types will be resolved when they are inlined.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002068 return TypeSetByHwMode(); // Unknown.
Chris Lattner640a3f52010-03-23 23:50:31 +00002069 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002070
Chris Lattner640a3f52010-03-23 23:50:31 +00002071 if (R->isSubClassOf("Register")) {
2072 assert(ResNo == 0 && "Registers only produce one result!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002073 if (NotRegisters)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002074 return TypeSetByHwMode(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00002075 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002076 return TypeSetByHwMode(T.getRegisterVTs(R));
Chris Lattner640a3f52010-03-23 23:50:31 +00002077 }
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00002078
2079 if (R->isSubClassOf("SubRegIndex")) {
2080 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002081 return TypeSetByHwMode(MVT::i32);
Jakob Stoklund Olesen73ea7bf2010-05-24 14:48:12 +00002082 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002083
Jakob Stoklund Olesenf0a804d2013-03-23 20:35:01 +00002084 if (R->isSubClassOf("ValueType")) {
Chris Lattner640a3f52010-03-23 23:50:31 +00002085 assert(ResNo == 0 && "This node only has one result!");
Jakob Stoklund Olesenf0a804d2013-03-23 20:35:01 +00002086 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2087 //
2088 // (sext_inreg GPR:$src, i16)
2089 // ~~~
2090 if (Unnamed)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002091 return TypeSetByHwMode(MVT::Other);
Jakob Stoklund Olesenf0a804d2013-03-23 20:35:01 +00002092 // With a name, the ValueType simply provides the type of the named
2093 // variable.
2094 //
2095 // (sext_inreg i32:$src, i16)
2096 // ~~~~~~~~
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00002097 if (NotRegisters)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002098 return TypeSetByHwMode(); // Unknown.
2099 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2100 return TypeSetByHwMode(getValueTypeByHwMode(R, CGH));
Jakob Stoklund Olesenf0a804d2013-03-23 20:35:01 +00002101 }
2102
2103 if (R->isSubClassOf("CondCode")) {
2104 assert(ResNo == 0 && "This node only has one result!");
2105 // Using a CondCodeSDNode.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002106 return TypeSetByHwMode(MVT::Other);
Chris Lattner640a3f52010-03-23 23:50:31 +00002107 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002108
Chris Lattner640a3f52010-03-23 23:50:31 +00002109 if (R->isSubClassOf("ComplexPattern")) {
2110 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002111 if (NotRegisters)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002112 return TypeSetByHwMode(); // Unknown.
2113 return TypeSetByHwMode(CDP.getComplexPattern(R).getValueType());
Chris Lattner640a3f52010-03-23 23:50:31 +00002114 }
2115 if (R->isSubClassOf("PointerLikeRegClass")) {
2116 assert(ResNo == 0 && "Regclass can only have one result!");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002117 TypeSetByHwMode VTS(MVT::iPTR);
2118 TP.getInfer().expandOverloads(VTS);
2119 return VTS;
Chris Lattner640a3f52010-03-23 23:50:31 +00002120 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002121
Chris Lattner640a3f52010-03-23 23:50:31 +00002122 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2123 R->getName() == "zero_reg") {
Chris Lattner6cefb772008-01-05 22:25:12 +00002124 // Placeholder.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002125 return TypeSetByHwMode(); // Unknown.
Chris Lattner6cefb772008-01-05 22:25:12 +00002126 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002127
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002128 if (R->isSubClassOf("Operand")) {
2129 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2130 Record *T = R->getValueAsDef("Type");
2131 return TypeSetByHwMode(getValueTypeByHwMode(T, CGH));
2132 }
Tim Northoveree8d5c32014-05-20 11:52:46 +00002133
Chris Lattner6cefb772008-01-05 22:25:12 +00002134 TP.error("Unknown node flavor used in pattern: " + R->getName());
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002135 return TypeSetByHwMode(MVT::Other);
Chris Lattner6cefb772008-01-05 22:25:12 +00002136}
2137
Chris Lattnere67bde52008-01-06 05:36:50 +00002138
2139/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2140/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2141const CodeGenIntrinsic *TreePatternNode::
2142getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2143 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2144 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2145 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
Craig Topper095734c2014-04-15 07:20:03 +00002146 return nullptr;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002147
Florian Hahn74dff3b2018-06-14 20:32:58 +00002148 unsigned IID = cast<IntInit>(getChild(0)->getLeafValue())->getValue();
Chris Lattnere67bde52008-01-06 05:36:50 +00002149 return &CDP.getIntrinsicInfo(IID);
2150}
2151
Chris Lattner47661322010-02-14 22:22:58 +00002152/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2153/// return the ComplexPattern information, otherwise return null.
2154const ComplexPattern *
2155TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
Tim Northoveree8d5c32014-05-20 11:52:46 +00002156 Record *Rec;
2157 if (isLeaf()) {
2158 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2159 if (!DI)
2160 return nullptr;
2161 Rec = DI->getDef();
2162 } else
2163 Rec = getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002164
Tim Northoveree8d5c32014-05-20 11:52:46 +00002165 if (!Rec->isSubClassOf("ComplexPattern"))
2166 return nullptr;
2167 return &CGP.getComplexPattern(Rec);
2168}
2169
2170unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2171 // A ComplexPattern specifically declares how many results it fills in.
2172 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2173 return CP->getNumOperands();
2174
2175 // If MIOperandInfo is specified, that gives the count.
2176 if (isLeaf()) {
2177 DefInit *DI = dyn_cast<DefInit>(getLeafValue());
2178 if (DI && DI->getDef()->isSubClassOf("Operand")) {
2179 DagInit *MIOps = DI->getDef()->getValueAsDag("MIOperandInfo");
2180 if (MIOps->getNumArgs())
2181 return MIOps->getNumArgs();
2182 }
2183 }
2184
2185 // Otherwise there is just one result.
2186 return 1;
Chris Lattner47661322010-02-14 22:22:58 +00002187}
2188
2189/// NodeHasProperty - Return true if this node has the specified property.
2190bool TreePatternNode::NodeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00002191 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00002192 if (isLeaf()) {
2193 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2194 return CP->hasProperty(Property);
Matt Arsenault082879a2017-12-20 19:36:28 +00002195
Chris Lattner47661322010-02-14 22:22:58 +00002196 return false;
2197 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002198
Matt Arsenault082879a2017-12-20 19:36:28 +00002199 if (Property != SDNPHasChain) {
2200 // The chain proprety is already present on the different intrinsic node
2201 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2202 // on the intrinsic. Anything else is specific to the individual intrinsic.
2203 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CGP))
2204 return Int->hasProperty(Property);
2205 }
2206
2207 if (!Operator->isSubClassOf("SDPatternOperator"))
2208 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002209
Chris Lattner47661322010-02-14 22:22:58 +00002210 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
2211}
2212
2213
2214
2215
2216/// TreeHasProperty - Return true if any node in this tree has the specified
2217/// property.
2218bool TreePatternNode::TreeHasProperty(SDNP Property,
Chris Lattner751d5aa2010-02-14 22:33:49 +00002219 const CodeGenDAGPatterns &CGP) const {
Chris Lattner47661322010-02-14 22:22:58 +00002220 if (NodeHasProperty(Property, CGP))
2221 return true;
2222 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00002223 if (getChild(i)->TreeHasProperty(Property, CGP))
Chris Lattner47661322010-02-14 22:22:58 +00002224 return true;
2225 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002226}
Chris Lattner47661322010-02-14 22:22:58 +00002227
Evan Cheng6bd95672008-06-16 20:29:38 +00002228/// isCommutativeIntrinsic - Return true if the node corresponds to a
2229/// commutative intrinsic.
2230bool
2231TreePatternNode::isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const {
2232 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2233 return Int->isCommutative;
2234 return false;
2235}
2236
Florian Hahn74dff3b2018-06-14 20:32:58 +00002237static bool isOperandClass(const TreePatternNode *N, StringRef Class) {
2238 if (!N->isLeaf())
2239 return N->getOperator()->isSubClassOf(Class);
Chris Lattnere67bde52008-01-06 05:36:50 +00002240
Florian Hahn74dff3b2018-06-14 20:32:58 +00002241 DefInit *DI = dyn_cast<DefInit>(N->getLeafValue());
Matt Arsenault22204082014-11-02 23:46:51 +00002242 if (DI && DI->getDef()->isSubClassOf(Class))
2243 return true;
2244
2245 return false;
2246}
Matt Arsenault9dd31e82014-12-11 22:27:14 +00002247
2248static void emitTooManyOperandsError(TreePattern &TP,
2249 StringRef InstName,
2250 unsigned Expected,
2251 unsigned Actual) {
2252 TP.error("Instruction '" + InstName + "' was provided " + Twine(Actual) +
2253 " operands but expected only " + Twine(Expected) + "!");
2254}
2255
2256static void emitTooFewOperandsError(TreePattern &TP,
2257 StringRef InstName,
2258 unsigned Actual) {
2259 TP.error("Instruction '" + InstName +
2260 "' expects more than the provided " + Twine(Actual) + " operands!");
2261}
2262
Bob Wilson6c01ca92009-01-05 17:23:09 +00002263/// ApplyTypeConstraints - Apply all of the type constraints relevant to
Chris Lattner6cefb772008-01-05 22:25:12 +00002264/// this node and its children in the tree. This returns true if it makes a
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002265/// change, false otherwise. If a type contradiction is found, flag an error.
Chris Lattner6cefb772008-01-05 22:25:12 +00002266bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002267 if (TP.hasError())
2268 return false;
2269
Chris Lattnerfe718932008-01-06 01:10:31 +00002270 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
Chris Lattner6cefb772008-01-05 22:25:12 +00002271 if (isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002272 if (DefInit *DI = dyn_cast<DefInit>(getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002273 // If it's a regclass or something else known, include the type.
Chris Lattnerd7349192010-03-19 21:37:09 +00002274 bool MadeChange = false;
2275 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2276 MadeChange |= UpdateNodeType(i, getImplicitType(DI->getDef(), i,
Jakob Stoklund Olesen7a42fb32013-03-23 18:08:44 +00002277 NotRegisters,
2278 !hasName(), TP), TP);
Chris Lattnerd7349192010-03-19 21:37:09 +00002279 return MadeChange;
Chris Lattner523f6a52010-02-14 21:10:15 +00002280 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002281
Sean Silva6cfc8062012-10-10 20:24:43 +00002282 if (IntInit *II = dyn_cast<IntInit>(getLeafValue())) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002283 assert(Types.size() == 1 && "Invalid IntInit");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002284
Chris Lattnerd7349192010-03-19 21:37:09 +00002285 // Int inits are always integers. :)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002286 bool MadeChange = TP.getInfer().EnforceInteger(Types[0]);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002287
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002288 if (!TP.getInfer().isConcrete(Types[0], false))
Chris Lattner2cacec52010-03-15 06:00:16 +00002289 return MadeChange;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002290
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002291 ValueTypeByHwMode VVT = TP.getInfer().getConcrete(Types[0], false);
2292 for (auto &P : VVT) {
2293 MVT::SimpleValueType VT = P.second.SimpleTy;
2294 if (VT == MVT::iPTR || VT == MVT::iPTRAny)
2295 continue;
2296 unsigned Size = MVT(VT).getSizeInBits();
2297 // Make sure that the value is representable for this type.
2298 if (Size >= 32)
2299 continue;
2300 // Check that the value doesn't use more bits than we have. It must
2301 // either be a sign- or zero-extended equivalent of the original.
2302 int64_t SignBitAndAbove = II->getValue() >> (Size - 1);
2303 if (SignBitAndAbove == -1 || SignBitAndAbove == 0 ||
2304 SignBitAndAbove == 1)
2305 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002306
Benjamin Kramerca5092a2017-12-28 16:58:54 +00002307 TP.error("Integer value '" + Twine(II->getValue()) +
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002308 "' is out of range for type '" + getEnumName(VT) + "'!");
2309 break;
2310 }
2311 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00002312 }
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002313
Chris Lattner6cefb772008-01-05 22:25:12 +00002314 return false;
2315 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002316
Chris Lattner6eb30122010-02-23 05:51:07 +00002317 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002318 bool MadeChange = false;
Duncan Sands83ec4b62008-06-06 12:08:01 +00002319
Chris Lattner6cefb772008-01-05 22:25:12 +00002320 // Apply the result type to the node.
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00002321 unsigned NumRetVTs = Int->IS.RetVTs.size();
2322 unsigned NumParamVTs = Int->IS.ParamVTs.size();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002323
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00002324 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
Chris Lattnerd7349192010-03-19 21:37:09 +00002325 MadeChange |= UpdateNodeType(i, Int->IS.RetVTs[i], TP);
Bill Wendlingcdcc3e62008-11-13 09:08:33 +00002326
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002327 if (getNumChildren() != NumParamVTs + 1) {
Benjamin Kramerca5092a2017-12-28 16:58:54 +00002328 TP.error("Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2329 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002330 return false;
2331 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002332
2333 // Apply type info to the intrinsic ID.
Florian Hahn74dff3b2018-06-14 20:32:58 +00002334 MadeChange |= getChild(0)->UpdateNodeType(0, MVT::iPTR, TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002335
Chris Lattnerd7349192010-03-19 21:37:09 +00002336 for (unsigned i = 0, e = getNumChildren()-1; i != e; ++i) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00002337 MadeChange |= getChild(i+1)->ApplyTypeConstraints(TP, NotRegisters);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002338
Chris Lattnerd7349192010-03-19 21:37:09 +00002339 MVT::SimpleValueType OpVT = Int->IS.ParamVTs[i];
Florian Hahn74dff3b2018-06-14 20:32:58 +00002340 assert(getChild(i+1)->getNumTypes() == 1 && "Unhandled case");
2341 MadeChange |= getChild(i+1)->UpdateNodeType(0, OpVT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00002342 }
2343 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00002344 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002345
Chris Lattner6eb30122010-02-23 05:51:07 +00002346 if (getOperator()->isSubClassOf("SDNode")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002347 const SDNodeInfo &NI = CDP.getSDNodeInfo(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002348
Chris Lattner2a22cdc2010-03-28 08:48:47 +00002349 // Check that the number of operands is sane. Negative operands -> varargs.
2350 if (NI.getNumOperands() >= 0 &&
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002351 getNumChildren() != (unsigned)NI.getNumOperands()) {
Chris Lattner2a22cdc2010-03-28 08:48:47 +00002352 TP.error(getOperator()->getName() + " node requires exactly " +
Benjamin Kramerca5092a2017-12-28 16:58:54 +00002353 Twine(NI.getNumOperands()) + " operands!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002354 return false;
2355 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002356
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002357 bool MadeChange = false;
Chris Lattner6cefb772008-01-05 22:25:12 +00002358 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00002359 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
2360 MadeChange |= NI.ApplyTypeConstraints(this, TP);
Chris Lattnerd7349192010-03-19 21:37:09 +00002361 return MadeChange;
Chris Lattner6eb30122010-02-23 05:51:07 +00002362 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002363
Chris Lattner6eb30122010-02-23 05:51:07 +00002364 if (getOperator()->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002365 const DAGInstruction &Inst = CDP.getInstruction(getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002366 CodeGenInstruction &InstInfo =
Chris Lattnerf30187a2010-03-19 00:07:20 +00002367 CDP.getTargetInfo().getInstruction(getOperator());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002368
Chris Lattner0be6fe72010-03-27 19:15:02 +00002369 bool MadeChange = false;
2370
2371 // Apply the result types to the node, these come from the things in the
2372 // (outs) list of the instruction.
Craig Topper3220d112015-03-20 05:09:06 +00002373 unsigned NumResultsToAdd = std::min(InstInfo.Operands.NumDefs,
2374 Inst.getNumResults());
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00002375 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2376 MadeChange |= UpdateNodeTypeFromInst(ResNo, Inst.getResult(ResNo), TP);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002377
Chris Lattner0be6fe72010-03-27 19:15:02 +00002378 // If the instruction has implicit defs, we apply the first one as a result.
2379 // FIXME: This sucks, it should apply all implicit defs.
2380 if (!InstInfo.ImplicitDefs.empty()) {
2381 unsigned ResNo = NumResultsToAdd;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002382
Chris Lattner9414ae52010-03-27 20:09:24 +00002383 // FIXME: Generalize to multiple possible types and multiple possible
2384 // ImplicitDefs.
2385 MVT::SimpleValueType VT =
2386 InstInfo.HasOneImplicitDefWithKnownVT(CDP.getTargetInfo());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002387
Chris Lattner9414ae52010-03-27 20:09:24 +00002388 if (VT != MVT::Other)
2389 MadeChange |= UpdateNodeType(ResNo, VT, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00002390 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002391
Chris Lattner2cacec52010-03-15 06:00:16 +00002392 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2393 // be the same.
2394 if (getOperator()->getName() == "INSERT_SUBREG") {
Florian Hahn74dff3b2018-06-14 20:32:58 +00002395 assert(getChild(0)->getNumTypes() == 1 && "FIXME: Unhandled");
2396 MadeChange |= UpdateNodeType(0, getChild(0)->getExtType(0), TP);
2397 MadeChange |= getChild(0)->UpdateNodeType(0, getExtType(0), TP);
Matt Arsenault22204082014-11-02 23:46:51 +00002398 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2399 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2400 // variadic.
2401
2402 unsigned NChild = getNumChildren();
2403 if (NChild < 3) {
2404 TP.error("REG_SEQUENCE requires at least 3 operands!");
2405 return false;
2406 }
2407
2408 if (NChild % 2 == 0) {
2409 TP.error("REG_SEQUENCE requires an odd number of operands!");
2410 return false;
2411 }
2412
2413 if (!isOperandClass(getChild(0), "RegisterClass")) {
2414 TP.error("REG_SEQUENCE requires a RegisterClass for first operand!");
2415 return false;
2416 }
2417
2418 for (unsigned I = 1; I < NChild; I += 2) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00002419 TreePatternNode *SubIdxChild = getChild(I + 1);
Matt Arsenault22204082014-11-02 23:46:51 +00002420 if (!isOperandClass(SubIdxChild, "SubRegIndex")) {
2421 TP.error("REG_SEQUENCE requires a SubRegIndex for operand " +
Benjamin Kramerca5092a2017-12-28 16:58:54 +00002422 Twine(I + 1) + "!");
Matt Arsenault22204082014-11-02 23:46:51 +00002423 return false;
2424 }
2425 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002426 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002427
2428 unsigned ChildNo = 0;
2429 for (unsigned i = 0, e = Inst.getNumOperands(); i != e; ++i) {
2430 Record *OperandNode = Inst.getOperand(i);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002431
Chris Lattner6cefb772008-01-05 22:25:12 +00002432 // If the instruction expects a predicate or optional def operand, we
2433 // codegen this by setting the operand to it's default value if it has a
2434 // non-empty DefaultOps field.
Tom Stellard6d3d7652012-09-06 14:15:52 +00002435 if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00002436 !CDP.getDefaultOperand(OperandNode).DefaultOps.empty())
2437 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002438
Chris Lattner6cefb772008-01-05 22:25:12 +00002439 // Verify that we didn't run out of provided operands.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002440 if (ChildNo >= getNumChildren()) {
Matt Arsenault9dd31e82014-12-11 22:27:14 +00002441 emitTooFewOperandsError(TP, getOperator()->getName(), getNumChildren());
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002442 return false;
2443 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002444
Florian Hahn74dff3b2018-06-14 20:32:58 +00002445 TreePatternNode *Child = getChild(ChildNo++);
Chris Lattner0be6fe72010-03-27 19:15:02 +00002446 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00002447
2448 // If the operand has sub-operands, they may be provided by distinct
2449 // child patterns, so attempt to match each sub-operand separately.
2450 if (OperandNode->isSubClassOf("Operand")) {
2451 DagInit *MIOpInfo = OperandNode->getValueAsDag("MIOperandInfo");
2452 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2453 // But don't do that if the whole operand is being provided by
Tim Northovere072ed72014-05-22 11:56:09 +00002454 // a single ComplexPattern-related Operand.
2455
2456 if (Child->getNumMIResults(CDP) < NumArgs) {
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00002457 // Match first sub-operand against the child we already have.
2458 Record *SubRec = cast<DefInit>(MIOpInfo->getArg(0))->getDef();
2459 MadeChange |=
2460 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2461
2462 // And the remaining sub-operands against subsequent children.
2463 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2464 if (ChildNo >= getNumChildren()) {
Matt Arsenault9dd31e82014-12-11 22:27:14 +00002465 emitTooFewOperandsError(TP, getOperator()->getName(),
2466 getNumChildren());
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00002467 return false;
2468 }
Florian Hahn74dff3b2018-06-14 20:32:58 +00002469 Child = getChild(ChildNo++);
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00002470
2471 SubRec = cast<DefInit>(MIOpInfo->getArg(Arg))->getDef();
2472 MadeChange |=
2473 Child->UpdateNodeTypeFromInst(ChildResNo, SubRec, TP);
2474 }
2475 continue;
2476 }
2477 }
2478 }
2479
2480 // If we didn't match by pieces above, attempt to match the whole
2481 // operand now.
Jakob Stoklund Olesen4c169162013-03-18 04:08:07 +00002482 MadeChange |= Child->UpdateNodeTypeFromInst(ChildResNo, OperandNode, TP);
Chris Lattner6cefb772008-01-05 22:25:12 +00002483 }
Christopher Lamb5b415372008-03-11 09:33:47 +00002484
Matt Arsenault22204082014-11-02 23:46:51 +00002485 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
Matt Arsenault9dd31e82014-12-11 22:27:14 +00002486 emitTooManyOperandsError(TP, getOperator()->getName(),
2487 ChildNo, getNumChildren());
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002488 return false;
2489 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002490
Ulrich Weigandec8d1a52013-03-19 19:51:09 +00002491 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00002492 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner6cefb772008-01-05 22:25:12 +00002493 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00002494 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002495
Tim Northoveree8d5c32014-05-20 11:52:46 +00002496 if (getOperator()->isSubClassOf("ComplexPattern")) {
2497 bool MadeChange = false;
2498
2499 for (unsigned i = 0; i < getNumChildren(); ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00002500 MadeChange |= getChild(i)->ApplyTypeConstraints(TP, NotRegisters);
Tim Northoveree8d5c32014-05-20 11:52:46 +00002501
2502 return MadeChange;
2503 }
2504
Chris Lattner6eb30122010-02-23 05:51:07 +00002505 assert(getOperator()->isSubClassOf("SDNodeXForm") && "Unknown node type!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002506
Chris Lattner6eb30122010-02-23 05:51:07 +00002507 // Node transforms always take one operand.
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002508 if (getNumChildren() != 1) {
Chris Lattner6eb30122010-02-23 05:51:07 +00002509 TP.error("Node transform '" + getOperator()->getName() +
2510 "' requires one operand!");
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002511 return false;
2512 }
Chris Lattner6eb30122010-02-23 05:51:07 +00002513
Florian Hahn74dff3b2018-06-14 20:32:58 +00002514 bool MadeChange = getChild(0)->ApplyTypeConstraints(TP, NotRegisters);
Chris Lattner2cacec52010-03-15 06:00:16 +00002515 return MadeChange;
Chris Lattner6cefb772008-01-05 22:25:12 +00002516}
2517
2518/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2519/// RHS of a commutative operation, not the on LHS.
Florian Hahn74dff3b2018-06-14 20:32:58 +00002520static bool OnlyOnRHSOfCommutative(TreePatternNode *N) {
2521 if (!N->isLeaf() && N->getOperator()->getName() == "imm")
Chris Lattner6cefb772008-01-05 22:25:12 +00002522 return true;
Florian Hahn74dff3b2018-06-14 20:32:58 +00002523 if (N->isLeaf() && isa<IntInit>(N->getLeafValue()))
Chris Lattner6cefb772008-01-05 22:25:12 +00002524 return true;
2525 return false;
2526}
2527
2528
2529/// canPatternMatch - If it is impossible for this pattern to match on this
2530/// target, fill in Reason and return false. Otherwise, return true. This is
Jim Grosbachda4231f2009-03-26 16:17:51 +00002531/// used as a sanity check for .td files (to prevent people from writing stuff
Chris Lattner6cefb772008-01-05 22:25:12 +00002532/// that can never possibly work), and to prevent the pattern permuter from
2533/// generating stuff that is useless.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002534bool TreePatternNode::canPatternMatch(std::string &Reason,
Dan Gohmanee4fa192008-04-03 00:02:49 +00002535 const CodeGenDAGPatterns &CDP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002536 if (isLeaf()) return true;
2537
2538 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00002539 if (!getChild(i)->canPatternMatch(Reason, CDP))
Chris Lattner6cefb772008-01-05 22:25:12 +00002540 return false;
2541
2542 // If this is an intrinsic, handle cases that would make it not match. For
2543 // example, if an operand is required to be an immediate.
2544 if (getOperator()->isSubClassOf("Intrinsic")) {
2545 // TODO:
2546 return true;
2547 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002548
Tim Northoveree8d5c32014-05-20 11:52:46 +00002549 if (getOperator()->isSubClassOf("ComplexPattern"))
2550 return true;
2551
Chris Lattner6cefb772008-01-05 22:25:12 +00002552 // If this node is a commutative operator, check that the LHS isn't an
2553 // immediate.
2554 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(getOperator());
Evan Cheng6bd95672008-06-16 20:29:38 +00002555 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2556 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002557 // Scan all of the operands of the node and make sure that only the last one
2558 // is a constant node, unless the RHS also is.
2559 if (!OnlyOnRHSOfCommutative(getChild(getNumChildren()-1))) {
Craig Topper7e2d9b02016-12-19 08:35:08 +00002560 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
Evan Cheng6bd95672008-06-16 20:29:38 +00002561 for (unsigned i = Skip, e = getNumChildren()-1; i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +00002562 if (OnlyOnRHSOfCommutative(getChild(i))) {
2563 Reason="Immediate value must be on the RHS of commutative operators!";
2564 return false;
2565 }
2566 }
2567 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002568
Chris Lattner6cefb772008-01-05 22:25:12 +00002569 return true;
2570}
2571
2572//===----------------------------------------------------------------------===//
2573// TreePattern implementation
2574//
2575
David Greene05bce0b2011-07-29 22:43:06 +00002576TreePattern::TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002577 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002578 isInputPattern(isInput), HasError(false),
2579 Infer(*this) {
Craig Toppera1bedd72015-06-02 04:15:51 +00002580 for (Init *I : RawPat->getValues())
2581 Trees.push_back(ParseTreePattern(I, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00002582}
2583
David Greene05bce0b2011-07-29 22:43:06 +00002584TreePattern::TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002585 CodeGenDAGPatterns &cdp) : TheRecord(TheRec), CDP(cdp),
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002586 isInputPattern(isInput), HasError(false),
2587 Infer(*this) {
Chris Lattnerc2173052010-03-28 06:50:34 +00002588 Trees.push_back(ParseTreePattern(Pat, ""));
Chris Lattner6cefb772008-01-05 22:25:12 +00002589}
2590
Florian Hahn0b596f02018-05-30 21:00:18 +00002591TreePattern::TreePattern(Record *TheRec, TreePatternNodePtr Pat, bool isInput,
2592 CodeGenDAGPatterns &cdp)
2593 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2594 Infer(*this) {
David Blaikie9e092ac2014-11-17 22:55:41 +00002595 Trees.push_back(Pat);
Chris Lattner6cefb772008-01-05 22:25:12 +00002596}
2597
Matt Arsenaulta735d522014-11-11 23:48:11 +00002598void TreePattern::error(const Twine &Msg) {
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002599 if (HasError)
2600 return;
Chris Lattner6cefb772008-01-05 22:25:12 +00002601 dump();
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002602 PrintError(TheRecord->getLoc(), "In " + TheRecord->getName() + ": " + Msg);
2603 HasError = true;
Chris Lattner6cefb772008-01-05 22:25:12 +00002604}
2605
Chris Lattner2cacec52010-03-15 06:00:16 +00002606void TreePattern::ComputeNamedNodes() {
Florian Hahn74dff3b2018-06-14 20:32:58 +00002607 for (TreePatternNodePtr &Tree : Trees)
2608 ComputeNamedNodes(Tree.get());
Chris Lattner2cacec52010-03-15 06:00:16 +00002609}
2610
Florian Hahn74dff3b2018-06-14 20:32:58 +00002611void TreePattern::ComputeNamedNodes(TreePatternNode *N) {
Chris Lattner2cacec52010-03-15 06:00:16 +00002612 if (!N->getName().empty())
Florian Hahn74dff3b2018-06-14 20:32:58 +00002613 NamedNodes[N->getName()].push_back(N);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002614
Chris Lattner2cacec52010-03-15 06:00:16 +00002615 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00002616 ComputeNamedNodes(N->getChild(i));
Chris Lattner2cacec52010-03-15 06:00:16 +00002617}
2618
Florian Hahn0b596f02018-05-30 21:00:18 +00002619TreePatternNodePtr TreePattern::ParseTreePattern(Init *TheInit,
2620 StringRef OpName) {
Sean Silva6cfc8062012-10-10 20:24:43 +00002621 if (DefInit *DI = dyn_cast<DefInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00002622 Record *R = DI->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002623
Chris Lattnerc2173052010-03-28 06:50:34 +00002624 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
Jim Grosbach66c9ee72011-07-06 23:38:13 +00002625 // TreePatternNode of its own. For example:
Chris Lattnerc2173052010-03-28 06:50:34 +00002626 /// (foo GPR, imm) -> (foo GPR, (imm))
Ulrich Weigand3a904262018-07-13 13:18:00 +00002627 if (R->isSubClassOf("SDNode") || R->isSubClassOf("PatFrags"))
David Greenedcd35c72011-07-29 19:07:07 +00002628 return ParseTreePattern(
Matthias Braun205e95012016-12-05 06:00:41 +00002629 DagInit::get(DI, nullptr,
Matthias Braunddbd6db2016-12-05 06:00:46 +00002630 std::vector<std::pair<Init*, StringInit*> >()),
David Greenedcd35c72011-07-29 19:07:07 +00002631 OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002632
Chris Lattnerc2173052010-03-28 06:50:34 +00002633 // Input argument?
Florian Hahn0b596f02018-05-30 21:00:18 +00002634 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(DI, 1);
Chris Lattner2a22cdc2010-03-28 08:48:47 +00002635 if (R->getName() == "node" && !OpName.empty()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00002636 if (OpName.empty())
2637 error("'node' argument requires a name to match with operand list");
2638 Args.push_back(OpName);
2639 }
2640
2641 Res->setName(OpName);
2642 return Res;
2643 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002644
Jakob Stoklund Olesen8e3cb3e2013-03-24 19:37:00 +00002645 // ?:$name or just $name.
Craig Topperf8012eb2015-04-22 02:09:45 +00002646 if (isa<UnsetInit>(TheInit)) {
Jakob Stoklund Olesen8e3cb3e2013-03-24 19:37:00 +00002647 if (OpName.empty())
2648 error("'?' argument requires a name to match with operand list");
Florian Hahn0b596f02018-05-30 21:00:18 +00002649 TreePatternNodePtr Res = std::make_shared<TreePatternNode>(TheInit, 1);
Jakob Stoklund Olesen8e3cb3e2013-03-24 19:37:00 +00002650 Args.push_back(OpName);
2651 Res->setName(OpName);
2652 return Res;
2653 }
2654
Nicolai Haehnle6f256bc2018-06-04 14:45:12 +00002655 if (isa<IntInit>(TheInit) || isa<BitInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00002656 if (!OpName.empty())
Nicolai Haehnle6f256bc2018-06-04 14:45:12 +00002657 error("Constant int or bit argument should not have a name!");
2658 if (isa<BitInit>(TheInit))
2659 TheInit = TheInit->convertInitializerTo(IntRecTy::get());
2660 return std::make_shared<TreePatternNode>(TheInit, 1);
Chris Lattnerc2173052010-03-28 06:50:34 +00002661 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002662
Sean Silva6cfc8062012-10-10 20:24:43 +00002663 if (BitsInit *BI = dyn_cast<BitsInit>(TheInit)) {
Chris Lattnerc2173052010-03-28 06:50:34 +00002664 // Turn this into an IntInit.
David Greene05bce0b2011-07-29 22:43:06 +00002665 Init *II = BI->convertInitializerTo(IntRecTy::get());
Craig Topper095734c2014-04-15 07:20:03 +00002666 if (!II || !isa<IntInit>(II))
Chris Lattnerc2173052010-03-28 06:50:34 +00002667 error("Bits value must be constants!");
Chris Lattnerb775b1e2010-03-28 06:57:56 +00002668 return ParseTreePattern(II, OpName);
Chris Lattnerc2173052010-03-28 06:50:34 +00002669 }
2670
Sean Silva6cfc8062012-10-10 20:24:43 +00002671 DagInit *Dag = dyn_cast<DagInit>(TheInit);
Chris Lattnerc2173052010-03-28 06:50:34 +00002672 if (!Dag) {
Matthias Braun88d20752017-01-28 02:02:38 +00002673 TheInit->print(errs());
Chris Lattnerc2173052010-03-28 06:50:34 +00002674 error("Pattern has unexpected init kind!");
2675 }
Sean Silva6cfc8062012-10-10 20:24:43 +00002676 DefInit *OpDef = dyn_cast<DefInit>(Dag->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00002677 if (!OpDef) error("Pattern has unexpected operator type!");
2678 Record *Operator = OpDef->getDef();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002679
Chris Lattner6cefb772008-01-05 22:25:12 +00002680 if (Operator->isSubClassOf("ValueType")) {
2681 // If the operator is a ValueType, then this must be "type cast" of a leaf
2682 // node.
2683 if (Dag->getNumArgs() != 1)
2684 error("Type cast only takes one operand!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002685
Florian Hahn0b596f02018-05-30 21:00:18 +00002686 TreePatternNodePtr New =
2687 ParseTreePattern(Dag->getArg(0), Dag->getArgNameStr(0));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002688
Chris Lattner6cefb772008-01-05 22:25:12 +00002689 // Apply the type cast.
Chris Lattnerd7349192010-03-19 21:37:09 +00002690 assert(New->getNumTypes() == 1 && "FIXME: Unhandled");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002691 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
2692 New->UpdateNodeType(0, getValueTypeByHwMode(Operator, CGH), *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002693
Chris Lattnerc2173052010-03-28 06:50:34 +00002694 if (!OpName.empty())
2695 error("ValueType cast should not have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00002696 return New;
2697 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002698
Chris Lattner6cefb772008-01-05 22:25:12 +00002699 // Verify that this is something that makes sense for an operator.
Ulrich Weigand3a904262018-07-13 13:18:00 +00002700 if (!Operator->isSubClassOf("PatFrags") &&
Nate Begeman7cee8172009-03-19 05:21:56 +00002701 !Operator->isSubClassOf("SDNode") &&
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002702 !Operator->isSubClassOf("Instruction") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00002703 !Operator->isSubClassOf("SDNodeXForm") &&
2704 !Operator->isSubClassOf("Intrinsic") &&
Tim Northoveree8d5c32014-05-20 11:52:46 +00002705 !Operator->isSubClassOf("ComplexPattern") &&
Chris Lattner6cefb772008-01-05 22:25:12 +00002706 Operator->getName() != "set" &&
Chris Lattner310adf12010-03-27 02:53:27 +00002707 Operator->getName() != "implicit")
Chris Lattner6cefb772008-01-05 22:25:12 +00002708 error("Unrecognized node '" + Operator->getName() + "'!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002709
Chris Lattner6cefb772008-01-05 22:25:12 +00002710 // Check to see if this is something that is illegal in an input pattern.
Chris Lattnerb775b1e2010-03-28 06:57:56 +00002711 if (isInputPattern) {
2712 if (Operator->isSubClassOf("Instruction") ||
2713 Operator->isSubClassOf("SDNodeXForm"))
2714 error("Cannot use '" + Operator->getName() + "' in an input pattern!");
2715 } else {
2716 if (Operator->isSubClassOf("Intrinsic"))
2717 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002718
Chris Lattnerb775b1e2010-03-28 06:57:56 +00002719 if (Operator->isSubClassOf("SDNode") &&
2720 Operator->getName() != "imm" &&
2721 Operator->getName() != "fpimm" &&
2722 Operator->getName() != "tglobaltlsaddr" &&
2723 Operator->getName() != "tconstpool" &&
2724 Operator->getName() != "tjumptable" &&
2725 Operator->getName() != "tframeindex" &&
2726 Operator->getName() != "texternalsym" &&
2727 Operator->getName() != "tblockaddress" &&
2728 Operator->getName() != "tglobaladdr" &&
2729 Operator->getName() != "bb" &&
Rafael Espindola09bbd162015-06-22 17:46:53 +00002730 Operator->getName() != "vt" &&
2731 Operator->getName() != "mcsym")
Chris Lattnerb775b1e2010-03-28 06:57:56 +00002732 error("Cannot use '" + Operator->getName() + "' in an output pattern!");
2733 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002734
Florian Hahn0b596f02018-05-30 21:00:18 +00002735 std::vector<TreePatternNodePtr> Children;
Chris Lattnerc2173052010-03-28 06:50:34 +00002736
2737 // Parse all the operands.
2738 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i)
Matthias Braunddbd6db2016-12-05 06:00:46 +00002739 Children.push_back(ParseTreePattern(Dag->getArg(i), Dag->getArgNameStr(i)));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002740
Hal Finkelb52179d2018-01-03 11:35:09 +00002741 // Get the actual number of results before Operator is converted to an intrinsic
2742 // node (which is hard-coded to have either zero or one result).
2743 unsigned NumResults = GetNumNodeResults(Operator, CDP);
2744
Fangrui Song73d8dbf2018-03-30 22:22:31 +00002745 // If the operator is an intrinsic, then this is just syntactic sugar for
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002746 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
Chris Lattner6cefb772008-01-05 22:25:12 +00002747 // convert the intrinsic name to a number.
2748 if (Operator->isSubClassOf("Intrinsic")) {
2749 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(Operator);
2750 unsigned IID = getDAGPatterns().getIntrinsicID(Operator)+1;
2751
2752 // If this intrinsic returns void, it must have side-effects and thus a
2753 // chain.
Chris Lattnerc2173052010-03-28 06:50:34 +00002754 if (Int.IS.RetVTs.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00002755 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00002756 else if (Int.ModRef != CodeGenIntrinsic::NoMem)
Chris Lattner6cefb772008-01-05 22:25:12 +00002757 // Has side-effects, requires chain.
2758 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
Chris Lattnerc2173052010-03-28 06:50:34 +00002759 else // Otherwise, no chain.
Chris Lattner6cefb772008-01-05 22:25:12 +00002760 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002761
Florian Hahn5cd96b72018-06-14 11:56:19 +00002762 Children.insert(Children.begin(),
2763 std::make_shared<TreePatternNode>(IntInit::get(IID), 1));
Chris Lattner6cefb772008-01-05 22:25:12 +00002764 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002765
Tim Northoveree8d5c32014-05-20 11:52:46 +00002766 if (Operator->isSubClassOf("ComplexPattern")) {
2767 for (unsigned i = 0; i < Children.size(); ++i) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00002768 TreePatternNodePtr Child = Children[i];
Tim Northoveree8d5c32014-05-20 11:52:46 +00002769
2770 if (Child->getName().empty())
2771 error("All arguments to a ComplexPattern must be named");
2772
2773 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
2774 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
2775 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
2776 auto OperandId = std::make_pair(Operator, i);
2777 auto PrevOp = ComplexPatternOperands.find(Child->getName());
2778 if (PrevOp != ComplexPatternOperands.end()) {
2779 if (PrevOp->getValue() != OperandId)
2780 error("All ComplexPattern operands must appear consistently: "
2781 "in the same order in just one ComplexPattern instance.");
2782 } else
2783 ComplexPatternOperands[Child->getName()] = OperandId;
2784 }
2785 }
2786
Florian Hahn74dff3b2018-06-14 20:32:58 +00002787 TreePatternNodePtr Result =
Craig Toppercfe3c912018-07-15 06:52:49 +00002788 std::make_shared<TreePatternNode>(Operator, std::move(Children),
2789 NumResults);
Chris Lattnerc2173052010-03-28 06:50:34 +00002790 Result->setName(OpName);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002791
Matthias Braun205e95012016-12-05 06:00:41 +00002792 if (Dag->getName()) {
Chris Lattnerc2173052010-03-28 06:50:34 +00002793 assert(Result->getName().empty());
Matthias Braun205e95012016-12-05 06:00:41 +00002794 Result->setName(Dag->getNameStr());
Chris Lattnerc2173052010-03-28 06:50:34 +00002795 }
Nate Begeman7cee8172009-03-19 05:21:56 +00002796 return Result;
Chris Lattner6cefb772008-01-05 22:25:12 +00002797}
2798
Chris Lattner7a0eb912010-03-28 08:38:32 +00002799/// SimplifyTree - See if we can simplify this tree to eliminate something that
2800/// will never match in favor of something obvious that will. This is here
2801/// strictly as a convenience to target authors because it allows them to write
2802/// more type generic things and have useless type casts fold away.
2803///
2804/// This returns true if any change is made.
Florian Hahn0b596f02018-05-30 21:00:18 +00002805static bool SimplifyTree(TreePatternNodePtr &N) {
Chris Lattner7a0eb912010-03-28 08:38:32 +00002806 if (N->isLeaf())
2807 return false;
2808
2809 // If we have a bitconvert with a resolved type and if the source and
2810 // destination types are the same, then the bitconvert is useless, remove it.
2811 if (N->getOperator()->getName() == "bitconvert" &&
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002812 N->getExtType(0).isValueTypeByHwMode(false) &&
Florian Hahn74dff3b2018-06-14 20:32:58 +00002813 N->getExtType(0) == N->getChild(0)->getExtType(0) &&
Chris Lattner7a0eb912010-03-28 08:38:32 +00002814 N->getName().empty()) {
Florian Hahn0b596f02018-05-30 21:00:18 +00002815 N = N->getChildShared(0);
Chris Lattner7a0eb912010-03-28 08:38:32 +00002816 SimplifyTree(N);
2817 return true;
2818 }
2819
2820 // Walk all children.
2821 bool MadeChange = false;
2822 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn0b596f02018-05-30 21:00:18 +00002823 TreePatternNodePtr Child = N->getChildShared(i);
Chris Lattner7a0eb912010-03-28 08:38:32 +00002824 MadeChange |= SimplifyTree(Child);
Florian Hahn5cd96b72018-06-14 11:56:19 +00002825 N->setChild(i, std::move(Child));
Chris Lattner7a0eb912010-03-28 08:38:32 +00002826 }
2827 return MadeChange;
2828}
2829
2830
2831
Chris Lattner6cefb772008-01-05 22:25:12 +00002832/// InferAllTypes - Infer/propagate as many types throughout the expression
Jim Grosbachda4231f2009-03-26 16:17:51 +00002833/// patterns as possible. Return true if all types are inferred, false
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00002834/// otherwise. Flags an error if a type contradiction is found.
Chris Lattner2cacec52010-03-15 06:00:16 +00002835bool TreePattern::
2836InferAllTypes(const StringMap<SmallVector<TreePatternNode*,1> > *InNamedTypes) {
2837 if (NamedNodes.empty())
2838 ComputeNamedNodes();
2839
Chris Lattner6cefb772008-01-05 22:25:12 +00002840 bool MadeChange = true;
2841 while (MadeChange) {
2842 MadeChange = false;
Florian Hahn0b596f02018-05-30 21:00:18 +00002843 for (TreePatternNodePtr &Tree : Trees) {
Craig Topper16642322015-11-22 20:46:24 +00002844 MadeChange |= Tree->ApplyTypeConstraints(*this, false);
2845 MadeChange |= SimplifyTree(Tree);
Chris Lattner7a0eb912010-03-28 08:38:32 +00002846 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002847
2848 // If there are constraints on our named nodes, apply them.
Craig Topper16642322015-11-22 20:46:24 +00002849 for (auto &Entry : NamedNodes) {
2850 SmallVectorImpl<TreePatternNode*> &Nodes = Entry.second;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002851
Chris Lattner2cacec52010-03-15 06:00:16 +00002852 // If we have input named node types, propagate their types to the named
2853 // values here.
2854 if (InNamedTypes) {
Craig Topper16642322015-11-22 20:46:24 +00002855 if (!InNamedTypes->count(Entry.getKey())) {
2856 error("Node '" + std::string(Entry.getKey()) +
Jim Grosbachf6342472014-07-09 18:55:49 +00002857 "' in output pattern but not input pattern");
2858 return true;
2859 }
Chris Lattner2cacec52010-03-15 06:00:16 +00002860
2861 const SmallVectorImpl<TreePatternNode*> &InNodes =
Craig Topper16642322015-11-22 20:46:24 +00002862 InNamedTypes->find(Entry.getKey())->second;
Chris Lattner2cacec52010-03-15 06:00:16 +00002863
2864 // The input types should be fully resolved by now.
Craig Topper16642322015-11-22 20:46:24 +00002865 for (TreePatternNode *Node : Nodes) {
Chris Lattner2cacec52010-03-15 06:00:16 +00002866 // If this node is a register class, and it is the root of the pattern
2867 // then we're mapping something onto an input register. We allow
2868 // changing the type of the input register in this case. This allows
2869 // us to match things like:
2870 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
Florian Hahn0b596f02018-05-30 21:00:18 +00002871 if (Node == Trees[0].get() && Node->isLeaf()) {
Craig Topper16642322015-11-22 20:46:24 +00002872 DefInit *DI = dyn_cast<DefInit>(Node->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00002873 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
2874 DI->getDef()->isSubClassOf("RegisterOperand")))
Chris Lattner2cacec52010-03-15 06:00:16 +00002875 continue;
2876 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002877
Craig Topper16642322015-11-22 20:46:24 +00002878 assert(Node->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00002879 InNodes[0]->getNumTypes() == 1 &&
2880 "FIXME: cannot name multiple result nodes yet");
Craig Topper16642322015-11-22 20:46:24 +00002881 MadeChange |= Node->UpdateNodeType(0, InNodes[0]->getExtType(0),
2882 *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002883 }
2884 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002885
Chris Lattner2cacec52010-03-15 06:00:16 +00002886 // If there are multiple nodes with the same name, they must all have the
2887 // same type.
Craig Topper16642322015-11-22 20:46:24 +00002888 if (Entry.second.size() > 1) {
Chris Lattner2cacec52010-03-15 06:00:16 +00002889 for (unsigned i = 0, e = Nodes.size()-1; i != e; ++i) {
Chris Lattnerd7349192010-03-19 21:37:09 +00002890 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i+1];
Daniel Dunbar32f6a8b2010-03-21 01:38:21 +00002891 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
Chris Lattnerd7349192010-03-19 21:37:09 +00002892 "FIXME: cannot name multiple result nodes yet");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002893
Chris Lattnerd7349192010-03-19 21:37:09 +00002894 MadeChange |= N1->UpdateNodeType(0, N2->getExtType(0), *this);
2895 MadeChange |= N2->UpdateNodeType(0, N1->getExtType(0), *this);
Chris Lattner2cacec52010-03-15 06:00:16 +00002896 }
2897 }
2898 }
Chris Lattner6cefb772008-01-05 22:25:12 +00002899 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002900
Chris Lattner6cefb772008-01-05 22:25:12 +00002901 bool HasUnresolvedTypes = false;
Florian Hahn0b596f02018-05-30 21:00:18 +00002902 for (const TreePatternNodePtr &Tree : Trees)
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002903 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(*this);
Chris Lattner6cefb772008-01-05 22:25:12 +00002904 return !HasUnresolvedTypes;
2905}
2906
Daniel Dunbar1a551802009-07-03 00:10:29 +00002907void TreePattern::print(raw_ostream &OS) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002908 OS << getRecord()->getName();
2909 if (!Args.empty()) {
2910 OS << "(" << Args[0];
2911 for (unsigned i = 1, e = Args.size(); i != e; ++i)
2912 OS << ", " << Args[i];
2913 OS << ")";
2914 }
2915 OS << ": ";
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002916
Chris Lattner6cefb772008-01-05 22:25:12 +00002917 if (Trees.size() > 1)
2918 OS << "[\n";
Florian Hahn0b596f02018-05-30 21:00:18 +00002919 for (const TreePatternNodePtr &Tree : Trees) {
Chris Lattner6cefb772008-01-05 22:25:12 +00002920 OS << "\t";
Craig Topper16642322015-11-22 20:46:24 +00002921 Tree->print(OS);
Chris Lattner6cefb772008-01-05 22:25:12 +00002922 OS << "\n";
2923 }
2924
2925 if (Trees.size() > 1)
2926 OS << "]\n";
2927}
2928
Daniel Dunbar1a551802009-07-03 00:10:29 +00002929void TreePattern::dump() const { print(errs()); }
Chris Lattner6cefb772008-01-05 22:25:12 +00002930
2931//===----------------------------------------------------------------------===//
Chris Lattnerfe718932008-01-06 01:10:31 +00002932// CodeGenDAGPatterns implementation
Chris Lattner6cefb772008-01-05 22:25:12 +00002933//
2934
Daniel Sanders8f5a5912017-11-11 03:23:44 +00002935CodeGenDAGPatterns::CodeGenDAGPatterns(RecordKeeper &R,
2936 PatternRewriterFn PatternRewriter)
2937 : Records(R), Target(R), LegalVTS(Target.getLegalValueTypes()),
2938 PatternRewriter(PatternRewriter) {
Chris Lattner67db8832010-12-13 00:23:57 +00002939
Justin Bognera3d02c72016-07-15 16:31:37 +00002940 Intrinsics = CodeGenIntrinsicTable(Records, false);
2941 TgtIntrinsics = CodeGenIntrinsicTable(Records, true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002942 ParseNodeInfo();
Chris Lattner443e3f92008-01-05 22:54:53 +00002943 ParseNodeTransforms();
Chris Lattner6cefb772008-01-05 22:25:12 +00002944 ParseComplexPatterns();
Chris Lattnerdc32f982008-01-05 22:43:57 +00002945 ParsePatternFragments();
Chris Lattner6cefb772008-01-05 22:25:12 +00002946 ParseDefaultOperands();
2947 ParseInstructions();
Hal Finkelc72cf872014-02-28 00:26:56 +00002948 ParsePatternFragments(/*OutFrags*/true);
Chris Lattner6cefb772008-01-05 22:25:12 +00002949 ParsePatterns();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00002950
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002951 // Break patterns with parameterized types into a series of patterns,
2952 // where each one has a fixed type and is predicated on the conditions
2953 // of the associated HW mode.
2954 ExpandHwModeBasedTypes();
2955
Chris Lattner6cefb772008-01-05 22:25:12 +00002956 // Generate variants. For example, commutative patterns can match
2957 // multiple ways. Add them to PatternsToMatch as well.
2958 GenerateVariants();
Dan Gohmanee4fa192008-04-03 00:02:49 +00002959
2960 // Infer instruction flags. For example, we can detect loads,
2961 // stores, and side effects in many cases by examining an
2962 // instruction's pattern.
2963 InferInstructionFlags();
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00002964
2965 // Verify that instruction flags match the patterns.
2966 VerifyInstructionFlags();
Chris Lattner6cefb772008-01-05 22:25:12 +00002967}
2968
Daniel Sanders04312952017-10-13 19:00:01 +00002969Record *CodeGenDAGPatterns::getSDNodeNamed(const std::string &Name) const {
Chris Lattner6cefb772008-01-05 22:25:12 +00002970 Record *N = Records.getDef(Name);
James Y Knightaeda4902015-05-11 22:17:13 +00002971 if (!N || !N->isSubClassOf("SDNode"))
2972 PrintFatalError("Error getting SDNode '" + Name + "'!");
2973
Chris Lattner6cefb772008-01-05 22:25:12 +00002974 return N;
2975}
2976
2977// Parse all of the SDNode definitions for the target, populating SDNodes.
Chris Lattnerfe718932008-01-06 01:10:31 +00002978void CodeGenDAGPatterns::ParseNodeInfo() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002979 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("SDNode");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002980 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
2981
Chris Lattner6cefb772008-01-05 22:25:12 +00002982 while (!Nodes.empty()) {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00002983 Record *R = Nodes.back();
2984 SDNodes.insert(std::make_pair(R, SDNodeInfo(R, CGH)));
Chris Lattner6cefb772008-01-05 22:25:12 +00002985 Nodes.pop_back();
2986 }
2987
Jim Grosbachda4231f2009-03-26 16:17:51 +00002988 // Get the builtin intrinsic nodes.
Chris Lattner6cefb772008-01-05 22:25:12 +00002989 intrinsic_void_sdnode = getSDNodeNamed("intrinsic_void");
2990 intrinsic_w_chain_sdnode = getSDNodeNamed("intrinsic_w_chain");
2991 intrinsic_wo_chain_sdnode = getSDNodeNamed("intrinsic_wo_chain");
2992}
2993
2994/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
2995/// map, and emit them to the file as functions.
Chris Lattnerfe718932008-01-06 01:10:31 +00002996void CodeGenDAGPatterns::ParseNodeTransforms() {
Chris Lattner6cefb772008-01-05 22:25:12 +00002997 std::vector<Record*> Xforms = Records.getAllDerivedDefinitions("SDNodeXForm");
2998 while (!Xforms.empty()) {
2999 Record *XFormNode = Xforms.back();
3000 Record *SDNode = XFormNode->getValueAsDef("Opcode");
Craig Topper2a129872017-05-31 21:12:46 +00003001 StringRef Code = XFormNode->getValueAsString("XFormFunction");
Chris Lattner443e3f92008-01-05 22:54:53 +00003002 SDNodeXForms.insert(std::make_pair(XFormNode, NodeXForm(SDNode, Code)));
Chris Lattner6cefb772008-01-05 22:25:12 +00003003
3004 Xforms.pop_back();
3005 }
3006}
3007
Chris Lattnerfe718932008-01-06 01:10:31 +00003008void CodeGenDAGPatterns::ParseComplexPatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00003009 std::vector<Record*> AMs = Records.getAllDerivedDefinitions("ComplexPattern");
3010 while (!AMs.empty()) {
3011 ComplexPatterns.insert(std::make_pair(AMs.back(), AMs.back()));
3012 AMs.pop_back();
3013 }
3014}
3015
3016
3017/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3018/// file, building up the PatternFragments map. After we've collected them all,
3019/// inline fragments together as necessary, so that there are no references left
3020/// inside a pattern fragment to a pattern fragment.
3021///
Hal Finkelc72cf872014-02-28 00:26:56 +00003022void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
Ulrich Weigand3a904262018-07-13 13:18:00 +00003023 std::vector<Record*> Fragments = Records.getAllDerivedDefinitions("PatFrags");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003024
Chris Lattnerdc32f982008-01-05 22:43:57 +00003025 // First step, parse all of the fragments.
Craig Topper16642322015-11-22 20:46:24 +00003026 for (Record *Frag : Fragments) {
3027 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkelc72cf872014-02-28 00:26:56 +00003028 continue;
3029
Ulrich Weigand3a904262018-07-13 13:18:00 +00003030 ListInit *LI = Frag->getValueAsListInit("Fragments");
Hal Finkelc72cf872014-02-28 00:26:56 +00003031 TreePattern *P =
Craig Topper16642322015-11-22 20:46:24 +00003032 (PatternFragments[Frag] = llvm::make_unique<TreePattern>(
Ulrich Weigand3a904262018-07-13 13:18:00 +00003033 Frag, LI, !Frag->isSubClassOf("OutPatFrag"),
David Blaikiebea87da2014-11-13 21:40:02 +00003034 *this)).get();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003035
Chris Lattnerdc32f982008-01-05 22:43:57 +00003036 // Validate the argument list, converting it to set, to discard duplicates.
Chris Lattner6cefb772008-01-05 22:25:12 +00003037 std::vector<std::string> &Args = P->getArgList();
Zachary Turnere4442992017-09-20 18:01:40 +00003038 // Copy the args so we can take StringRefs to them.
3039 auto ArgsCopy = Args;
3040 SmallDenseSet<StringRef, 4> OperandsSet;
3041 OperandsSet.insert(ArgsCopy.begin(), ArgsCopy.end());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003042
Chris Lattnerdc32f982008-01-05 22:43:57 +00003043 if (OperandsSet.count(""))
Chris Lattner6cefb772008-01-05 22:25:12 +00003044 P->error("Cannot have unnamed 'node' values in pattern fragment!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003045
Chris Lattner6cefb772008-01-05 22:25:12 +00003046 // Parse the operands list.
Craig Topper16642322015-11-22 20:46:24 +00003047 DagInit *OpsList = Frag->getValueAsDag("Operands");
Sean Silva6cfc8062012-10-10 20:24:43 +00003048 DefInit *OpsOp = dyn_cast<DefInit>(OpsList->getOperator());
Chris Lattner6cefb772008-01-05 22:25:12 +00003049 // Special cases: ops == outs == ins. Different names are used to
Jim Grosbachda4231f2009-03-26 16:17:51 +00003050 // improve readability.
Chris Lattner6cefb772008-01-05 22:25:12 +00003051 if (!OpsOp ||
3052 (OpsOp->getDef()->getName() != "ops" &&
3053 OpsOp->getDef()->getName() != "outs" &&
3054 OpsOp->getDef()->getName() != "ins"))
3055 P->error("Operands list should start with '(ops ... '!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003056
3057 // Copy over the arguments.
Chris Lattner6cefb772008-01-05 22:25:12 +00003058 Args.clear();
3059 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
Sean Silva3f7b7f82012-10-10 20:24:47 +00003060 if (!isa<DefInit>(OpsList->getArg(j)) ||
3061 cast<DefInit>(OpsList->getArg(j))->getDef()->getName() != "node")
Chris Lattner6cefb772008-01-05 22:25:12 +00003062 P->error("Operands list should all be 'node' values.");
Matthias Braunddbd6db2016-12-05 06:00:46 +00003063 if (!OpsList->getArgName(j))
Chris Lattner6cefb772008-01-05 22:25:12 +00003064 P->error("Operands list should have names for each operand!");
Matthias Braunddbd6db2016-12-05 06:00:46 +00003065 StringRef ArgNameStr = OpsList->getArgNameStr(j);
3066 if (!OperandsSet.count(ArgNameStr))
3067 P->error("'" + ArgNameStr +
Chris Lattner6cefb772008-01-05 22:25:12 +00003068 "' does not occur in pattern or was multiply specified!");
Matthias Braunddbd6db2016-12-05 06:00:46 +00003069 OperandsSet.erase(ArgNameStr);
3070 Args.push_back(ArgNameStr);
Chris Lattner6cefb772008-01-05 22:25:12 +00003071 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003072
Chris Lattnerdc32f982008-01-05 22:43:57 +00003073 if (!OperandsSet.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00003074 P->error("Operands list does not contain an entry for operand '" +
Chris Lattnerdc32f982008-01-05 22:43:57 +00003075 *OperandsSet.begin() + "'!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003076
Chris Lattner6cefb772008-01-05 22:25:12 +00003077 // If there is a node transformation corresponding to this, keep track of
3078 // it.
Craig Topper16642322015-11-22 20:46:24 +00003079 Record *Transform = Frag->getValueAsDef("OperandTransform");
Chris Lattner6cefb772008-01-05 22:25:12 +00003080 if (!getSDNodeTransform(Transform).second.empty()) // not noop xform?
Ulrich Weigand3a904262018-07-13 13:18:00 +00003081 for (auto T : P->getTrees())
3082 T->setTransformFn(Transform);
Chris Lattner6cefb772008-01-05 22:25:12 +00003083 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003084
Chris Lattner6cefb772008-01-05 22:25:12 +00003085 // Now that we've parsed all of the tree fragments, do a closure on them so
3086 // that there are not references to PatFrags left inside of them.
Craig Topper16642322015-11-22 20:46:24 +00003087 for (Record *Frag : Fragments) {
3088 if (OutFrags != Frag->isSubClassOf("OutPatFrag"))
Hal Finkelc72cf872014-02-28 00:26:56 +00003089 continue;
3090
Craig Topper16642322015-11-22 20:46:24 +00003091 TreePattern &ThePat = *PatternFragments[Frag];
David Blaikiebea87da2014-11-13 21:40:02 +00003092 ThePat.InlinePatternFragments();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003093
Chris Lattner6cefb772008-01-05 22:25:12 +00003094 // Infer as many types as possible. Don't worry about it if we don't infer
Ulrich Weigandc62320c2018-07-13 16:42:15 +00003095 // all of them, some may depend on the inputs of the pattern. Also, don't
3096 // validate type sets; validation may cause spurious failures e.g. if a
3097 // fragment needs floating-point types but the current target does not have
3098 // any (this is only an error if that fragment is ever used!).
3099 {
3100 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3101 ThePat.InferAllTypes();
3102 ThePat.resetError();
3103 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003104
Chris Lattner6cefb772008-01-05 22:25:12 +00003105 // If debugging, print out the pattern fragment result.
Nicola Zaghen0818e782018-05-14 12:53:11 +00003106 LLVM_DEBUG(ThePat.dump());
Chris Lattner6cefb772008-01-05 22:25:12 +00003107 }
3108}
3109
Chris Lattnerfe718932008-01-06 01:10:31 +00003110void CodeGenDAGPatterns::ParseDefaultOperands() {
Tom Stellard6d3d7652012-09-06 14:15:52 +00003111 std::vector<Record*> DefaultOps;
3112 DefaultOps = Records.getAllDerivedDefinitions("OperandWithDefaultOps");
Chris Lattner6cefb772008-01-05 22:25:12 +00003113
3114 // Find some SDNode.
3115 assert(!SDNodes.empty() && "No SDNodes parsed?");
David Greene05bce0b2011-07-29 22:43:06 +00003116 Init *SomeSDNode = DefInit::get(SDNodes.begin()->first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003117
Tom Stellard6d3d7652012-09-06 14:15:52 +00003118 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3119 DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag("DefaultOps");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003120
Tom Stellard6d3d7652012-09-06 14:15:52 +00003121 // Clone the DefaultInfo dag node, changing the operator from 'ops' to
3122 // SomeSDnode so that we can parse this.
Matthias Braunddbd6db2016-12-05 06:00:46 +00003123 std::vector<std::pair<Init*, StringInit*> > Ops;
Tom Stellard6d3d7652012-09-06 14:15:52 +00003124 for (unsigned op = 0, e = DefaultInfo->getNumArgs(); op != e; ++op)
3125 Ops.push_back(std::make_pair(DefaultInfo->getArg(op),
3126 DefaultInfo->getArgName(op)));
Matthias Braun205e95012016-12-05 06:00:41 +00003127 DagInit *DI = DagInit::get(SomeSDNode, nullptr, Ops);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003128
Tom Stellard6d3d7652012-09-06 14:15:52 +00003129 // Create a TreePattern to parse this.
3130 TreePattern P(DefaultOps[i], DI, false, *this);
3131 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003132
Tom Stellard6d3d7652012-09-06 14:15:52 +00003133 // Copy the operands over into a DAGDefaultOperand.
3134 DAGDefaultOperand DefaultOpInfo;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003135
Florian Hahn0b596f02018-05-30 21:00:18 +00003136 const TreePatternNodePtr &T = P.getTree(0);
Tom Stellard6d3d7652012-09-06 14:15:52 +00003137 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
Florian Hahn0b596f02018-05-30 21:00:18 +00003138 TreePatternNodePtr TPN = T->getChildShared(op);
Tom Stellard6d3d7652012-09-06 14:15:52 +00003139 while (TPN->ApplyTypeConstraints(P, false))
3140 /* Resolve all types */;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003141
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00003142 if (TPN->ContainsUnresolvedType(P)) {
Benjamin Kramerabe43b52014-03-29 17:17:15 +00003143 PrintFatalError("Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3144 DefaultOps[i]->getName() +
3145 "' doesn't have a concrete type!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003146 }
Florian Hahn5cd96b72018-06-14 11:56:19 +00003147 DefaultOpInfo.DefaultOps.push_back(std::move(TPN));
Chris Lattner6cefb772008-01-05 22:25:12 +00003148 }
Tom Stellard6d3d7652012-09-06 14:15:52 +00003149
3150 // Insert it into the DefaultOperands map so we can find it later.
3151 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
Chris Lattner6cefb772008-01-05 22:25:12 +00003152 }
3153}
3154
3155/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3156/// instruction input. Return true if this is a real use.
David Blaikie7f3c26c2018-06-11 22:14:43 +00003157static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn0b596f02018-05-30 21:00:18 +00003158 std::map<std::string, TreePatternNodePtr> &InstInputs) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003159 // No name -> not interesting.
3160 if (Pat->getName().empty()) {
3161 if (Pat->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00003162 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
Owen Andersonbea6f612011-06-27 21:06:21 +00003163 if (DI && (DI->getDef()->isSubClassOf("RegisterClass") ||
3164 DI->getDef()->isSubClassOf("RegisterOperand")))
David Blaikie7f3c26c2018-06-11 22:14:43 +00003165 I.error("Input " + DI->getDef()->getName() + " must be named!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003166 }
3167 return false;
3168 }
3169
3170 Record *Rec;
3171 if (Pat->isLeaf()) {
Sean Silva6cfc8062012-10-10 20:24:43 +00003172 DefInit *DI = dyn_cast<DefInit>(Pat->getLeafValue());
David Blaikie7f3c26c2018-06-11 22:14:43 +00003173 if (!DI)
3174 I.error("Input $" + Pat->getName() + " must be an identifier!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003175 Rec = DI->getDef();
3176 } else {
Chris Lattner6cefb772008-01-05 22:25:12 +00003177 Rec = Pat->getOperator();
3178 }
3179
3180 // SRCVALUE nodes are ignored.
3181 if (Rec->getName() == "srcvalue")
3182 return false;
3183
Florian Hahn0b596f02018-05-30 21:00:18 +00003184 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
Chris Lattner6cefb772008-01-05 22:25:12 +00003185 if (!Slot) {
3186 Slot = Pat;
Chris Lattner53d09bd2010-02-23 05:59:10 +00003187 return true;
Chris Lattner6cefb772008-01-05 22:25:12 +00003188 }
Chris Lattner53d09bd2010-02-23 05:59:10 +00003189 Record *SlotRec;
3190 if (Slot->isLeaf()) {
Sean Silva3f7b7f82012-10-10 20:24:47 +00003191 SlotRec = cast<DefInit>(Slot->getLeafValue())->getDef();
Chris Lattner53d09bd2010-02-23 05:59:10 +00003192 } else {
3193 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3194 SlotRec = Slot->getOperator();
3195 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003196
Chris Lattner53d09bd2010-02-23 05:59:10 +00003197 // Ensure that the inputs agree if we've already seen this input.
3198 if (Rec != SlotRec)
David Blaikie7f3c26c2018-06-11 22:14:43 +00003199 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Ulrich Weigand3a904262018-07-13 13:18:00 +00003200 // Ensure that the types can agree as well.
3201 Slot->UpdateNodeType(0, Pat->getExtType(0), I);
3202 Pat->UpdateNodeType(0, Slot->getExtType(0), I);
Chris Lattnerd7349192010-03-19 21:37:09 +00003203 if (Slot->getExtTypes() != Pat->getExtTypes())
David Blaikie7f3c26c2018-06-11 22:14:43 +00003204 I.error("All $" + Pat->getName() + " inputs must agree with each other");
Chris Lattner6cefb772008-01-05 22:25:12 +00003205 return true;
3206}
3207
3208/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3209/// part of "I", the instruction), computing the set of inputs and outputs of
3210/// the pattern. Report errors if we see anything naughty.
Florian Hahn0b596f02018-05-30 21:00:18 +00003211void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
Florian Hahn74dff3b2018-06-14 20:32:58 +00003212 TreePattern &I, TreePatternNodePtr Pat,
Florian Hahn0b596f02018-05-30 21:00:18 +00003213 std::map<std::string, TreePatternNodePtr> &InstInputs,
Craig Topper0f562fe2018-12-05 00:47:59 +00003214 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3215 &InstResults,
Florian Hahn0b596f02018-05-30 21:00:18 +00003216 std::vector<Record *> &InstImpResults) {
Ulrich Weigand3a904262018-07-13 13:18:00 +00003217
3218 // The instruction pattern still has unresolved fragments. For *named*
3219 // nodes we must resolve those here. This may not result in multiple
3220 // alternatives.
3221 if (!Pat->getName().empty()) {
3222 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3223 SrcPattern.InlinePatternFragments();
3224 SrcPattern.InferAllTypes();
3225 Pat = SrcPattern.getOnlyTree();
3226 }
3227
Chris Lattner6cefb772008-01-05 22:25:12 +00003228 if (Pat->isLeaf()) {
Chris Lattneracfb70f2010-04-20 06:30:25 +00003229 bool isUse = HandleUse(I, Pat, InstInputs);
Chris Lattner6cefb772008-01-05 22:25:12 +00003230 if (!isUse && Pat->getTransformFn())
David Blaikie7f3c26c2018-06-11 22:14:43 +00003231 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003232 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00003233 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003234
Chris Lattner84aa60b2010-02-17 06:53:36 +00003235 if (Pat->getOperator()->getName() == "implicit") {
Chris Lattner6cefb772008-01-05 22:25:12 +00003236 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00003237 TreePatternNode *Dest = Pat->getChild(i);
3238 if (!Dest->isLeaf())
David Blaikie7f3c26c2018-06-11 22:14:43 +00003239 I.error("implicitly defined value should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003240
Florian Hahn74dff3b2018-06-14 20:32:58 +00003241 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Chris Lattner6cefb772008-01-05 22:25:12 +00003242 if (!Val || !Val->getDef()->isSubClassOf("Register"))
David Blaikie7f3c26c2018-06-11 22:14:43 +00003243 I.error("implicitly defined value should be a register!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003244 InstImpResults.push_back(Val->getDef());
3245 }
3246 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00003247 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003248
Chris Lattner84aa60b2010-02-17 06:53:36 +00003249 if (Pat->getOperator()->getName() != "set") {
Chris Lattner6cefb772008-01-05 22:25:12 +00003250 // If this is not a set, verify that the children nodes are not void typed,
3251 // and recurse.
3252 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00003253 if (Pat->getChild(i)->getNumTypes() == 0)
David Blaikie7f3c26c2018-06-11 22:14:43 +00003254 I.error("Cannot have void nodes inside of patterns!");
Florian Hahn0b596f02018-05-30 21:00:18 +00003255 FindPatternInputsAndOutputs(I, Pat->getChildShared(i), InstInputs,
3256 InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00003257 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003258
Chris Lattner6cefb772008-01-05 22:25:12 +00003259 // If this is a non-leaf node with no children, treat it basically as if
3260 // it were a leaf. This handles nodes like (imm).
Chris Lattneracfb70f2010-04-20 06:30:25 +00003261 bool isUse = HandleUse(I, Pat, InstInputs);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003262
Chris Lattner6cefb772008-01-05 22:25:12 +00003263 if (!isUse && Pat->getTransformFn())
David Blaikie7f3c26c2018-06-11 22:14:43 +00003264 I.error("Cannot specify a transform function for a non-input value!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003265 return;
Chris Lattner84aa60b2010-02-17 06:53:36 +00003266 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003267
Chris Lattner6cefb772008-01-05 22:25:12 +00003268 // Otherwise, this is a set, validate and collect instruction results.
3269 if (Pat->getNumChildren() == 0)
David Blaikie7f3c26c2018-06-11 22:14:43 +00003270 I.error("set requires operands!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003271
Chris Lattner6cefb772008-01-05 22:25:12 +00003272 if (Pat->getTransformFn())
David Blaikie7f3c26c2018-06-11 22:14:43 +00003273 I.error("Cannot specify a transform function on a set node!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003274
Chris Lattner6cefb772008-01-05 22:25:12 +00003275 // Check the set destinations.
3276 unsigned NumDests = Pat->getNumChildren()-1;
3277 for (unsigned i = 0; i != NumDests; ++i) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00003278 TreePatternNodePtr Dest = Pat->getChildShared(i);
Ulrich Weigand3a904262018-07-13 13:18:00 +00003279 // For set destinations we also must resolve fragments here.
3280 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3281 DestPattern.InlinePatternFragments();
3282 DestPattern.InferAllTypes();
3283 Dest = DestPattern.getOnlyTree();
3284
Chris Lattner6cefb772008-01-05 22:25:12 +00003285 if (!Dest->isLeaf())
David Blaikie7f3c26c2018-06-11 22:14:43 +00003286 I.error("set destination should be a register!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003287
Sean Silva6cfc8062012-10-10 20:24:43 +00003288 DefInit *Val = dyn_cast<DefInit>(Dest->getLeafValue());
Michael Ilseman3f0e8832014-12-12 21:48:03 +00003289 if (!Val) {
David Blaikie7f3c26c2018-06-11 22:14:43 +00003290 I.error("set destination should be a register!");
Michael Ilseman3f0e8832014-12-12 21:48:03 +00003291 continue;
3292 }
Chris Lattner6cefb772008-01-05 22:25:12 +00003293
3294 if (Val->getDef()->isSubClassOf("RegisterClass") ||
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00003295 Val->getDef()->isSubClassOf("ValueType") ||
Owen Andersonbea6f612011-06-27 21:06:21 +00003296 Val->getDef()->isSubClassOf("RegisterOperand") ||
Chris Lattnera938ac62009-07-29 20:43:05 +00003297 Val->getDef()->isSubClassOf("PointerLikeRegClass")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00003298 if (Dest->getName().empty())
David Blaikie7f3c26c2018-06-11 22:14:43 +00003299 I.error("set destination must have a name!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003300 if (InstResults.count(Dest->getName()))
David Blaikie7f3c26c2018-06-11 22:14:43 +00003301 I.error("cannot set '" + Dest->getName() + "' multiple times");
Chris Lattner6cefb772008-01-05 22:25:12 +00003302 InstResults[Dest->getName()] = Dest;
3303 } else if (Val->getDef()->isSubClassOf("Register")) {
3304 InstImpResults.push_back(Val->getDef());
3305 } else {
David Blaikie7f3c26c2018-06-11 22:14:43 +00003306 I.error("set destination should be a register!");
Chris Lattner6cefb772008-01-05 22:25:12 +00003307 }
3308 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003309
Chris Lattner6cefb772008-01-05 22:25:12 +00003310 // Verify and collect info from the computation.
Florian Hahn0b596f02018-05-30 21:00:18 +00003311 FindPatternInputsAndOutputs(I, Pat->getChildShared(NumDests), InstInputs,
3312 InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00003313}
3314
Dan Gohmanee4fa192008-04-03 00:02:49 +00003315//===----------------------------------------------------------------------===//
3316// Instruction Analysis
3317//===----------------------------------------------------------------------===//
3318
3319class InstAnalyzer {
3320 const CodeGenDAGPatterns &CDP;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003321public:
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003322 bool hasSideEffects;
3323 bool mayStore;
3324 bool mayLoad;
3325 bool isBitcast;
3326 bool isVariadic;
Ulrich Weigand3a904262018-07-13 13:18:00 +00003327 bool hasChain;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003328
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003329 InstAnalyzer(const CodeGenDAGPatterns &cdp)
3330 : CDP(cdp), hasSideEffects(false), mayStore(false), mayLoad(false),
Ulrich Weigand3a904262018-07-13 13:18:00 +00003331 isBitcast(false), isVariadic(false), hasChain(false) {}
Dan Gohmanee4fa192008-04-03 00:02:49 +00003332
Craig Topperb1618d22017-06-20 16:34:37 +00003333 void Analyze(const PatternToMatch &Pat) {
Ulrich Weigand3a904262018-07-13 13:18:00 +00003334 const TreePatternNode *N = Pat.getSrcPattern();
3335 AnalyzeNode(N);
3336 // These properties are detected only on the root node.
3337 isBitcast = IsNodeBitcast(N);
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003338 }
3339
Dan Gohmanee4fa192008-04-03 00:02:49 +00003340private:
Florian Hahn74dff3b2018-06-14 20:32:58 +00003341 bool IsNodeBitcast(const TreePatternNode *N) const {
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003342 if (hasSideEffects || mayLoad || mayStore || isVariadic)
Evan Cheng0f040a22011-03-15 05:09:26 +00003343 return false;
3344
Ulrich Weigand3a904262018-07-13 13:18:00 +00003345 if (N->isLeaf())
3346 return false;
3347 if (N->getNumChildren() != 1 || !N->getChild(0)->isLeaf())
Evan Cheng0f040a22011-03-15 05:09:26 +00003348 return false;
3349
Ulrich Weigand3a904262018-07-13 13:18:00 +00003350 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(N->getOperator());
Evan Cheng0f040a22011-03-15 05:09:26 +00003351 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3352 return false;
3353 return OpInfo.getEnumName() == "ISD::BITCAST";
3354 }
3355
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003356public:
Florian Hahn74dff3b2018-06-14 20:32:58 +00003357 void AnalyzeNode(const TreePatternNode *N) {
3358 if (N->isLeaf()) {
3359 if (DefInit *DI = dyn_cast<DefInit>(N->getLeafValue())) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00003360 Record *LeafRec = DI->getDef();
3361 // Handle ComplexPattern leaves.
3362 if (LeafRec->isSubClassOf("ComplexPattern")) {
3363 const ComplexPattern &CP = CDP.getComplexPattern(LeafRec);
3364 if (CP.hasProperty(SDNPMayStore)) mayStore = true;
3365 if (CP.hasProperty(SDNPMayLoad)) mayLoad = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003366 if (CP.hasProperty(SDNPSideEffect)) hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003367 }
3368 }
3369 return;
3370 }
3371
3372 // Analyze children.
Florian Hahn74dff3b2018-06-14 20:32:58 +00003373 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3374 AnalyzeNode(N->getChild(i));
Dan Gohmanee4fa192008-04-03 00:02:49 +00003375
Dan Gohmanee4fa192008-04-03 00:02:49 +00003376 // Notice properties of the node.
Florian Hahn74dff3b2018-06-14 20:32:58 +00003377 if (N->NodeHasProperty(SDNPMayStore, CDP)) mayStore = true;
3378 if (N->NodeHasProperty(SDNPMayLoad, CDP)) mayLoad = true;
3379 if (N->NodeHasProperty(SDNPSideEffect, CDP)) hasSideEffects = true;
3380 if (N->NodeHasProperty(SDNPVariadic, CDP)) isVariadic = true;
Ulrich Weigand3a904262018-07-13 13:18:00 +00003381 if (N->NodeHasProperty(SDNPHasChain, CDP)) hasChain = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003382
Florian Hahn74dff3b2018-06-14 20:32:58 +00003383 if (const CodeGenIntrinsic *IntInfo = N->getIntrinsicInfo(CDP)) {
Dan Gohmanee4fa192008-04-03 00:02:49 +00003384 // If this is an intrinsic, analyze it.
Nicolai Haehnle318d6a22016-04-19 21:58:33 +00003385 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Ref)
Dan Gohmanee4fa192008-04-03 00:02:49 +00003386 mayLoad = true;// These may load memory.
3387
Nicolai Haehnle318d6a22016-04-19 21:58:33 +00003388 if (IntInfo->ModRef & CodeGenIntrinsic::MR_Mod)
Dan Gohmanee4fa192008-04-03 00:02:49 +00003389 mayStore = true;// Intrinsics that can write to memory are 'mayStore'.
3390
Matt Arsenault8c9ed242017-04-28 21:01:46 +00003391 if (IntInfo->ModRef >= CodeGenIntrinsic::ReadWriteMem ||
3392 IntInfo->hasSideEffects)
Nicolai Haehnle318d6a22016-04-19 21:58:33 +00003393 // ReadWriteMem intrinsics can have other strange effects.
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003394 hasSideEffects = true;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003395 }
3396 }
3397
3398};
3399
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003400static bool InferFromPattern(CodeGenInstruction &InstInfo,
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003401 const InstAnalyzer &PatInfo,
3402 Record *PatDef) {
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003403 bool Error = false;
3404
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003405 // Remember where InstInfo got its flags.
3406 if (InstInfo.hasUndefFlags())
3407 InstInfo.InferredFrom = PatDef;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003408
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003409 // Check explicitly set flags for consistency.
3410 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3411 !InstInfo.hasSideEffects_Unset) {
3412 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3413 // the pattern has no side effects. That could be useful for div/rem
3414 // instructions that may trap.
3415 if (!InstInfo.hasSideEffects) {
3416 Error = true;
3417 PrintError(PatDef->getLoc(), "Pattern doesn't match hasSideEffects = " +
3418 Twine(InstInfo.hasSideEffects));
3419 }
3420 }
3421
3422 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3423 Error = true;
3424 PrintError(PatDef->getLoc(), "Pattern doesn't match mayStore = " +
3425 Twine(InstInfo.mayStore));
3426 }
3427
3428 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3429 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
Bruce Mitchener767c34a2015-09-12 01:17:08 +00003430 // Some targets translate immediates to loads.
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003431 if (!InstInfo.mayLoad) {
3432 Error = true;
3433 PrintError(PatDef->getLoc(), "Pattern doesn't match mayLoad = " +
3434 Twine(InstInfo.mayLoad));
3435 }
3436 }
3437
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003438 // Transfer inferred flags.
3439 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3440 InstInfo.mayStore |= PatInfo.mayStore;
3441 InstInfo.mayLoad |= PatInfo.mayLoad;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003442
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003443 // These flags are silently added without any verification.
Ulrich Weigand3a904262018-07-13 13:18:00 +00003444 // FIXME: To match historical behavior of TableGen, for now add those flags
3445 // only when we're inferring from the primary instruction pattern.
3446 if (PatDef->isSubClassOf("Instruction")) {
3447 InstInfo.isBitcast |= PatInfo.isBitcast;
3448 InstInfo.hasChain |= PatInfo.hasChain;
3449 InstInfo.hasChain_Inferred = true;
3450 }
Jakob Stoklund Olesenaaaecfc2012-08-24 21:08:09 +00003451
3452 // Don't infer isVariadic. This flag means something different on SDNodes and
3453 // instructions. For example, a CALL SDNode is variadic because it has the
3454 // call arguments as operands, but a CALL instruction is not variadic - it
3455 // has argument registers as implicit, not explicit uses.
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003456
3457 return Error;
Dan Gohmanee4fa192008-04-03 00:02:49 +00003458}
3459
Jim Grosbachac915b42012-07-17 00:47:06 +00003460/// hasNullFragReference - Return true if the DAG has any reference to the
3461/// null_frag operator.
3462static bool hasNullFragReference(DagInit *DI) {
Sean Silva6cfc8062012-10-10 20:24:43 +00003463 DefInit *OpDef = dyn_cast<DefInit>(DI->getOperator());
Jim Grosbachac915b42012-07-17 00:47:06 +00003464 if (!OpDef) return false;
3465 Record *Operator = OpDef->getDef();
3466
3467 // If this is the null fragment, return true.
3468 if (Operator->getName() == "null_frag") return true;
3469 // If any of the arguments reference the null fragment, return true.
3470 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
Sean Silva6cfc8062012-10-10 20:24:43 +00003471 DagInit *Arg = dyn_cast<DagInit>(DI->getArg(i));
Jim Grosbachac915b42012-07-17 00:47:06 +00003472 if (Arg && hasNullFragReference(Arg))
3473 return true;
3474 }
3475
3476 return false;
3477}
3478
3479/// hasNullFragReference - Return true if any DAG in the list references
3480/// the null_frag operator.
3481static bool hasNullFragReference(ListInit *LI) {
Craig Toppera1bedd72015-06-02 04:15:51 +00003482 for (Init *I : LI->getValues()) {
3483 DagInit *DI = dyn_cast<DagInit>(I);
Jim Grosbachac915b42012-07-17 00:47:06 +00003484 assert(DI && "non-dag in an instruction Pattern list?!");
3485 if (hasNullFragReference(DI))
3486 return true;
3487 }
3488 return false;
3489}
3490
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003491/// Get all the instructions in a tree.
3492static void
Florian Hahn74dff3b2018-06-14 20:32:58 +00003493getInstructionsInTree(TreePatternNode *Tree, SmallVectorImpl<Record*> &Instrs) {
3494 if (Tree->isLeaf())
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003495 return;
Florian Hahn74dff3b2018-06-14 20:32:58 +00003496 if (Tree->getOperator()->isSubClassOf("Instruction"))
3497 Instrs.push_back(Tree->getOperator());
3498 for (unsigned i = 0, e = Tree->getNumChildren(); i != e; ++i)
3499 getInstructionsInTree(Tree->getChild(i), Instrs);
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003500}
3501
Jakob Stoklund Olesen19209962013-03-24 00:56:16 +00003502/// Check the class of a pattern leaf node against the instruction operand it
3503/// represents.
3504static bool checkOperandClass(CGIOperandList::OperandInfo &OI,
3505 Record *Leaf) {
3506 if (OI.Rec == Leaf)
3507 return true;
3508
3509 // Allow direct value types to be used in instruction set patterns.
3510 // The type will be checked later.
3511 if (Leaf->isSubClassOf("ValueType"))
3512 return true;
3513
3514 // Patterns can also be ComplexPattern instances.
3515 if (Leaf->isSubClassOf("ComplexPattern"))
3516 return true;
3517
3518 return false;
3519}
3520
Ulrich Weigand3a904262018-07-13 13:18:00 +00003521void CodeGenDAGPatterns::parseInstructionPattern(
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003522 CodeGenInstruction &CGI, ListInit *Pat, DAGInstMap &DAGInsts) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003523
Craig Topper541e68e2015-03-10 03:25:04 +00003524 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003525
Craig Topper541e68e2015-03-10 03:25:04 +00003526 // Parse the instruction.
Ulrich Weigand3a904262018-07-13 13:18:00 +00003527 TreePattern I(CGI.TheDef, Pat, true, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003528
Craig Topper541e68e2015-03-10 03:25:04 +00003529 // InstInputs - Keep track of all of the inputs of the instruction, along
3530 // with the record they are declared as.
Florian Hahn0b596f02018-05-30 21:00:18 +00003531 std::map<std::string, TreePatternNodePtr> InstInputs;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003532
Craig Topper541e68e2015-03-10 03:25:04 +00003533 // InstResults - Keep track of all the virtual registers that are 'set'
3534 // in the instruction, including what reg class they are.
Craig Topper0f562fe2018-12-05 00:47:59 +00003535 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
3536 InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00003537
Craig Topper541e68e2015-03-10 03:25:04 +00003538 std::vector<Record*> InstImpResults;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003539
Craig Topper541e68e2015-03-10 03:25:04 +00003540 // Verify that the top-level forms in the instruction are of void type, and
3541 // fill in the InstResults map.
Zachary Turnere4442992017-09-20 18:01:40 +00003542 SmallString<32> TypesString;
Ulrich Weigand3a904262018-07-13 13:18:00 +00003543 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
Zachary Turnere4442992017-09-20 18:01:40 +00003544 TypesString.clear();
Ulrich Weigand3a904262018-07-13 13:18:00 +00003545 TreePatternNodePtr Pat = I.getTree(j);
Nicolai Haehnle39980d62016-04-19 21:58:10 +00003546 if (Pat->getNumTypes() != 0) {
Zachary Turnere4442992017-09-20 18:01:40 +00003547 raw_svector_ostream OS(TypesString);
Nicolai Haehnle39980d62016-04-19 21:58:10 +00003548 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3549 if (k > 0)
Zachary Turnere4442992017-09-20 18:01:40 +00003550 OS << ", ";
3551 Pat->getExtType(k).writeToStream(OS);
Nicolai Haehnle39980d62016-04-19 21:58:10 +00003552 }
Ulrich Weigand3a904262018-07-13 13:18:00 +00003553 I.error("Top-level forms in instruction pattern should have"
Zachary Turnere4442992017-09-20 18:01:40 +00003554 " void types, has types " +
3555 OS.str());
Nicolai Haehnle39980d62016-04-19 21:58:10 +00003556 }
Chris Lattner6cefb772008-01-05 22:25:12 +00003557
Craig Topper541e68e2015-03-10 03:25:04 +00003558 // Find inputs and outputs, and verify the structure of the uses/defs.
Ulrich Weigand3a904262018-07-13 13:18:00 +00003559 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
Craig Topper541e68e2015-03-10 03:25:04 +00003560 InstImpResults);
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003561 }
3562
Craig Topper541e68e2015-03-10 03:25:04 +00003563 // Now that we have inputs and outputs of the pattern, inspect the operands
3564 // list for the instruction. This determines the order that operands are
3565 // added to the machine instruction the node corresponds to.
3566 unsigned NumResults = InstResults.size();
3567
3568 // Parse the operands list from the (ops) list, validating it.
Ulrich Weigand3a904262018-07-13 13:18:00 +00003569 assert(I.getArgList().empty() && "Args list should still be empty here!");
Craig Topper541e68e2015-03-10 03:25:04 +00003570
3571 // Check that all of the results occur first in the list.
3572 std::vector<Record*> Results;
Craig Topper0f562fe2018-12-05 00:47:59 +00003573 std::vector<unsigned> ResultIndices;
Florian Hahn0b596f02018-05-30 21:00:18 +00003574 SmallVector<TreePatternNodePtr, 2> ResNodes;
Craig Topper541e68e2015-03-10 03:25:04 +00003575 for (unsigned i = 0; i != NumResults; ++i) {
Craig Topper0f562fe2018-12-05 00:47:59 +00003576 if (i == CGI.Operands.size()) {
3577 const std::string &OpName =
3578 std::find_if(InstResults.begin(), InstResults.end(),
3579 [](const std::pair<std::string, TreePatternNodePtr> &P) {
3580 return P.second;
3581 })
3582 ->first;
3583
3584 I.error("'" + OpName + "' set but does not appear in operand list!");
3585 }
3586
Craig Topper541e68e2015-03-10 03:25:04 +00003587 const std::string &OpName = CGI.Operands[i].Name;
3588
3589 // Check that it exists in InstResults.
Craig Topper0f562fe2018-12-05 00:47:59 +00003590 auto InstResultIter = InstResults.find(OpName);
3591 if (InstResultIter == InstResults.end() || !InstResultIter->second)
Ulrich Weigand3a904262018-07-13 13:18:00 +00003592 I.error("Operand $" + OpName + " does not exist in operand list!");
Craig Topper541e68e2015-03-10 03:25:04 +00003593
Craig Topper0f562fe2018-12-05 00:47:59 +00003594 TreePatternNodePtr RNode = InstResultIter->second;
Craig Topper541e68e2015-03-10 03:25:04 +00003595 Record *R = cast<DefInit>(RNode->getLeafValue())->getDef();
Florian Hahn5cd96b72018-06-14 11:56:19 +00003596 ResNodes.push_back(std::move(RNode));
Craig Topper541e68e2015-03-10 03:25:04 +00003597 if (!R)
Ulrich Weigand3a904262018-07-13 13:18:00 +00003598 I.error("Operand $" + OpName + " should be a set destination: all "
Craig Topper541e68e2015-03-10 03:25:04 +00003599 "outputs must occur before inputs in operand list!");
3600
3601 if (!checkOperandClass(CGI.Operands[i], R))
Ulrich Weigand3a904262018-07-13 13:18:00 +00003602 I.error("Operand $" + OpName + " class mismatch!");
Craig Topper541e68e2015-03-10 03:25:04 +00003603
3604 // Remember the return type.
3605 Results.push_back(CGI.Operands[i].Rec);
3606
Craig Topper0f562fe2018-12-05 00:47:59 +00003607 // Remember the result index.
3608 ResultIndices.push_back(std::distance(InstResults.begin(), InstResultIter));
3609
Craig Topper541e68e2015-03-10 03:25:04 +00003610 // Okay, this one checks out.
Craig Topper0f562fe2018-12-05 00:47:59 +00003611 InstResultIter->second = nullptr;
Craig Topper541e68e2015-03-10 03:25:04 +00003612 }
3613
Craig Topperecb89052018-07-15 06:52:48 +00003614 // Loop over the inputs next.
Florian Hahn0b596f02018-05-30 21:00:18 +00003615 std::vector<TreePatternNodePtr> ResultNodeOperands;
Craig Topper541e68e2015-03-10 03:25:04 +00003616 std::vector<Record*> Operands;
3617 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
3618 CGIOperandList::OperandInfo &Op = CGI.Operands[i];
3619 const std::string &OpName = Op.Name;
3620 if (OpName.empty())
Ulrich Weigand3a904262018-07-13 13:18:00 +00003621 I.error("Operand #" + Twine(i) + " in operands list has no name!");
Craig Topper541e68e2015-03-10 03:25:04 +00003622
Craig Topperecb89052018-07-15 06:52:48 +00003623 if (!InstInputs.count(OpName)) {
Craig Topper541e68e2015-03-10 03:25:04 +00003624 // If this is an operand with a DefaultOps set filled in, we can ignore
3625 // this. When we codegen it, we will do so as always executed.
3626 if (Op.Rec->isSubClassOf("OperandWithDefaultOps")) {
3627 // Does it have a non-empty DefaultOps field? If so, ignore this
3628 // operand.
3629 if (!getDefaultOperand(Op.Rec).DefaultOps.empty())
3630 continue;
3631 }
Ulrich Weigand3a904262018-07-13 13:18:00 +00003632 I.error("Operand $" + OpName +
Craig Topper541e68e2015-03-10 03:25:04 +00003633 " does not appear in the instruction pattern");
3634 }
Craig Topperecb89052018-07-15 06:52:48 +00003635 TreePatternNodePtr InVal = InstInputs[OpName];
3636 InstInputs.erase(OpName); // It occurred, remove from map.
Craig Topper541e68e2015-03-10 03:25:04 +00003637
3638 if (InVal->isLeaf() && isa<DefInit>(InVal->getLeafValue())) {
3639 Record *InRec = static_cast<DefInit*>(InVal->getLeafValue())->getDef();
3640 if (!checkOperandClass(Op, InRec))
Ulrich Weigand3a904262018-07-13 13:18:00 +00003641 I.error("Operand $" + OpName + "'s register class disagrees"
Craig Topper541e68e2015-03-10 03:25:04 +00003642 " between the operand and pattern");
3643 }
3644 Operands.push_back(Op.Rec);
3645
3646 // Construct the result for the dest-pattern operand list.
Florian Hahn0b596f02018-05-30 21:00:18 +00003647 TreePatternNodePtr OpNode = InVal->clone();
Craig Topper541e68e2015-03-10 03:25:04 +00003648
3649 // No predicate is useful on the result.
Nicolai Haehnle98272e42018-11-30 14:15:13 +00003650 OpNode->clearPredicateCalls();
Craig Topper541e68e2015-03-10 03:25:04 +00003651
3652 // Promote the xform function to be an explicit node if set.
3653 if (Record *Xform = OpNode->getTransformFn()) {
3654 OpNode->setTransformFn(nullptr);
Florian Hahn0b596f02018-05-30 21:00:18 +00003655 std::vector<TreePatternNodePtr> Children;
Craig Topper541e68e2015-03-10 03:25:04 +00003656 Children.push_back(OpNode);
Craig Toppercfe3c912018-07-15 06:52:49 +00003657 OpNode = std::make_shared<TreePatternNode>(Xform, std::move(Children),
Florian Hahn74dff3b2018-06-14 20:32:58 +00003658 OpNode->getNumTypes());
Craig Topper541e68e2015-03-10 03:25:04 +00003659 }
3660
Florian Hahn5cd96b72018-06-14 11:56:19 +00003661 ResultNodeOperands.push_back(std::move(OpNode));
Craig Topper541e68e2015-03-10 03:25:04 +00003662 }
3663
Craig Topperecb89052018-07-15 06:52:48 +00003664 if (!InstInputs.empty())
3665 I.error("Input operand $" + InstInputs.begin()->first +
Ulrich Weigand3a904262018-07-13 13:18:00 +00003666 " occurs in pattern but not in operands list!");
Craig Topper541e68e2015-03-10 03:25:04 +00003667
Florian Hahn74dff3b2018-06-14 20:32:58 +00003668 TreePatternNodePtr ResultPattern = std::make_shared<TreePatternNode>(
Craig Toppercfe3c912018-07-15 06:52:49 +00003669 I.getRecord(), std::move(ResultNodeOperands),
Ulrich Weigand3a904262018-07-13 13:18:00 +00003670 GetNumNodeResults(I.getRecord(), *this));
Craig Topper3220d112015-03-20 05:09:06 +00003671 // Copy fully inferred output node types to instruction result pattern.
3672 for (unsigned i = 0; i != NumResults; ++i) {
3673 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
3674 ResultPattern->setType(i, ResNodes[i]->getExtType(0));
Craig Topper0f562fe2018-12-05 00:47:59 +00003675 ResultPattern->setResultIndex(i, ResultIndices[i]);
Craig Topper3220d112015-03-20 05:09:06 +00003676 }
Craig Topper541e68e2015-03-10 03:25:04 +00003677
Ulrich Weigand3a904262018-07-13 13:18:00 +00003678 // FIXME: Assume only the first tree is the pattern. The others are clobber
3679 // nodes.
3680 TreePatternNodePtr Pattern = I.getTree(0);
3681 TreePatternNodePtr SrcPattern;
3682 if (Pattern->getOperator()->getName() == "set") {
3683 SrcPattern = Pattern->getChild(Pattern->getNumChildren()-1)->clone();
3684 } else{
3685 // Not a set (store or something?)
3686 SrcPattern = Pattern;
3687 }
3688
Craig Topper541e68e2015-03-10 03:25:04 +00003689 // Create and insert the instruction.
3690 // FIXME: InstImpResults should not be part of DAGInstruction.
Ulrich Weigand3a904262018-07-13 13:18:00 +00003691 Record *R = I.getRecord();
3692 DAGInsts.emplace(std::piecewise_construct, std::forward_as_tuple(R),
3693 std::forward_as_tuple(Results, Operands, InstImpResults,
3694 SrcPattern, ResultPattern));
Craig Topper541e68e2015-03-10 03:25:04 +00003695
Ulrich Weigand3a904262018-07-13 13:18:00 +00003696 LLVM_DEBUG(I.dump());
Craig Topper541e68e2015-03-10 03:25:04 +00003697}
3698
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003699/// ParseInstructions - Parse all of the instructions, inlining and resolving
3700/// any fragments involved. This populates the Instructions list with fully
3701/// resolved instructions.
3702void CodeGenDAGPatterns::ParseInstructions() {
3703 std::vector<Record*> Instrs = Records.getAllDerivedDefinitions("Instruction");
3704
Craig Topper16642322015-11-22 20:46:24 +00003705 for (Record *Instr : Instrs) {
Craig Topper095734c2014-04-15 07:20:03 +00003706 ListInit *LI = nullptr;
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003707
Craig Topper16642322015-11-22 20:46:24 +00003708 if (isa<ListInit>(Instr->getValueInit("Pattern")))
3709 LI = Instr->getValueAsListInit("Pattern");
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003710
3711 // If there is no pattern, only collect minimal information about the
3712 // instruction for its operand list. We have to assume that there is one
3713 // result, as we have no detailed info. A pattern which references the
3714 // null_frag operator is as-if no pattern were specified. Normally this
3715 // is from a multiclass expansion w/ a SDPatternOperator passed in as
3716 // null_frag.
Craig Topperbbf57b32015-05-14 05:53:53 +00003717 if (!LI || LI->empty() || hasNullFragReference(LI)) {
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003718 std::vector<Record*> Results;
3719 std::vector<Record*> Operands;
3720
Craig Topper16642322015-11-22 20:46:24 +00003721 CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003722
3723 if (InstInfo.Operands.size() != 0) {
Craig Topper3220d112015-03-20 05:09:06 +00003724 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
3725 Results.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003726
Craig Topper3220d112015-03-20 05:09:06 +00003727 // The rest are inputs.
3728 for (unsigned j = InstInfo.Operands.NumDefs,
3729 e = InstInfo.Operands.size(); j < e; ++j)
3730 Operands.push_back(InstInfo.Operands[j].Rec);
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003731 }
3732
3733 // Create and insert the instruction.
3734 std::vector<Record*> ImpResults;
Craig Topper16642322015-11-22 20:46:24 +00003735 Instructions.insert(std::make_pair(Instr,
Ulrich Weigand3a904262018-07-13 13:18:00 +00003736 DAGInstruction(Results, Operands, ImpResults)));
Ahmed Bougacha2b43fff2013-10-28 18:07:21 +00003737 continue; // no pattern.
3738 }
3739
Craig Topper16642322015-11-22 20:46:24 +00003740 CodeGenInstruction &CGI = Target.getInstruction(Instr);
Ulrich Weigand3a904262018-07-13 13:18:00 +00003741 parseInstructionPattern(CGI, LI, Instructions);
Chris Lattner6cefb772008-01-05 22:25:12 +00003742 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003743
Chris Lattner6cefb772008-01-05 22:25:12 +00003744 // If we can, convert the instructions to be patterns that are matched!
Craig Topper16642322015-11-22 20:46:24 +00003745 for (auto &Entry : Instructions) {
Craig Topper16642322015-11-22 20:46:24 +00003746 Record *Instr = Entry.first;
Ulrich Weigand3a904262018-07-13 13:18:00 +00003747 DAGInstruction &TheInst = Entry.second;
3748 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
3749 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
3750
3751 if (SrcPattern && ResultPattern) {
3752 TreePattern Pattern(Instr, SrcPattern, true, *this);
3753 TreePattern Result(Instr, ResultPattern, false, *this);
3754 ParseOnePattern(Instr, Pattern, Result, TheInst.getImpResults());
3755 }
Chris Lattner6cefb772008-01-05 22:25:12 +00003756 }
3757}
3758
Florian Hahn74dff3b2018-06-14 20:32:58 +00003759typedef std::pair<TreePatternNode *, unsigned> NameRecord;
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00003760
Florian Hahn74dff3b2018-06-14 20:32:58 +00003761static void FindNames(TreePatternNode *P,
Chris Lattnera27234e2010-02-23 07:22:28 +00003762 std::map<std::string, NameRecord> &Names,
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00003763 TreePattern *PatternTop) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00003764 if (!P->getName().empty()) {
3765 NameRecord &Rec = Names[P->getName()];
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00003766 // If this is the first instance of the name, remember the node.
3767 if (Rec.second++ == 0)
Florian Hahn74dff3b2018-06-14 20:32:58 +00003768 Rec.first = P;
3769 else if (Rec.first->getExtTypes() != P->getExtTypes())
3770 PatternTop->error("repetition of value: $" + P->getName() +
Chris Lattnera27234e2010-02-23 07:22:28 +00003771 " where different uses have different types!");
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00003772 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003773
Florian Hahn74dff3b2018-06-14 20:32:58 +00003774 if (!P->isLeaf()) {
3775 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
3776 FindNames(P->getChild(i), Names, PatternTop);
Chris Lattner967d54a2010-02-23 06:35:45 +00003777 }
3778}
3779
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00003780std::vector<Predicate> CodeGenDAGPatterns::makePredList(ListInit *L) {
3781 std::vector<Predicate> Preds;
3782 for (Init *I : L->getValues()) {
3783 if (DefInit *Pred = dyn_cast<DefInit>(I))
3784 Preds.push_back(Pred->getDef());
3785 else
3786 llvm_unreachable("Non-def on the list");
3787 }
3788
3789 // Sort so that different orders get canonicalized to the same string.
Fangrui Song3b35e172018-09-27 02:13:45 +00003790 llvm::sort(Preds);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00003791 return Preds;
3792}
3793
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00003794void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
Craig Topper3ace6d82017-06-25 17:33:49 +00003795 PatternToMatch &&PTM) {
Chris Lattner967d54a2010-02-23 06:35:45 +00003796 // Do some sanity checking on the pattern we're about to match.
Chris Lattner25b6f912010-02-23 06:16:51 +00003797 std::string Reason;
Owen Andersoneb79b542012-09-19 22:15:06 +00003798 if (!PTM.getSrcPattern()->canPatternMatch(Reason, *this)) {
3799 PrintWarning(Pattern->getRecord()->getLoc(),
3800 Twine("Pattern can never match: ") + Reason);
3801 return;
3802 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003803
Chris Lattner405f1252010-03-01 22:29:19 +00003804 // If the source pattern's root is a complex pattern, that complex pattern
3805 // must specify the nodes it can potentially match.
3806 if (const ComplexPattern *CP =
3807 PTM.getSrcPattern()->getComplexPatternInfo(*this))
3808 if (CP->getRootNodes().empty())
3809 Pattern->error("ComplexPattern at root must specify list of opcodes it"
3810 " could match");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003811
3812
Chris Lattner967d54a2010-02-23 06:35:45 +00003813 // Find all of the named values in the input and output, ensure they have the
3814 // same type.
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00003815 std::map<std::string, NameRecord> SrcNames, DstNames;
Florian Hahn74dff3b2018-06-14 20:32:58 +00003816 FindNames(PTM.getSrcPattern(), SrcNames, Pattern);
3817 FindNames(PTM.getDstPattern(), DstNames, Pattern);
Chris Lattner967d54a2010-02-23 06:35:45 +00003818
3819 // Scan all of the named values in the destination pattern, rejecting them if
3820 // they don't exist in the input pattern.
Craig Topper16642322015-11-22 20:46:24 +00003821 for (const auto &Entry : DstNames) {
3822 if (SrcNames[Entry.first].first == nullptr)
Chris Lattner967d54a2010-02-23 06:35:45 +00003823 Pattern->error("Pattern has input without matching name in output: $" +
Craig Topper16642322015-11-22 20:46:24 +00003824 Entry.first);
Chris Lattnerba1cff42010-02-23 07:50:58 +00003825 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003826
Chris Lattner4ac7a0c2010-02-23 06:55:24 +00003827 // Scan all of the named values in the source pattern, rejecting them if the
3828 // name isn't used in the dest, and isn't used to tie two values together.
Craig Topper16642322015-11-22 20:46:24 +00003829 for (const auto &Entry : SrcNames)
3830 if (DstNames[Entry.first].first == nullptr &&
3831 SrcNames[Entry.first].second == 1)
3832 Pattern->error("Pattern has dead named input: $" + Entry.first);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003833
Florian Hahn5cd96b72018-06-14 11:56:19 +00003834 PatternsToMatch.push_back(PTM);
Chris Lattner25b6f912010-02-23 06:16:51 +00003835}
3836
Dan Gohmanee4fa192008-04-03 00:02:49 +00003837void CodeGenDAGPatterns::InferInstructionFlags() {
Craig Topper3f0462d2016-02-01 01:33:42 +00003838 ArrayRef<const CodeGenInstruction*> Instructions =
Chris Lattnerf6502782010-03-19 00:34:35 +00003839 Target.getInstructionsByEnumValue();
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003840
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003841 unsigned Errors = 0;
Jakob Stoklund Olesenccbe6032011-10-14 01:00:49 +00003842
Ulrich Weigand3a904262018-07-13 13:18:00 +00003843 // Try to infer flags from all patterns in PatternToMatch. These include
3844 // both the primary instruction patterns (which always come first) and
3845 // patterns defined outside the instruction.
Craig Topperc4a82c82017-06-20 16:34:35 +00003846 for (const PatternToMatch &PTM : ptms()) {
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003847 // We can only infer from single-instruction patterns, otherwise we won't
3848 // know which instruction should get the flags.
3849 SmallVector<Record*, 8> PatInstrs;
Florian Hahn74dff3b2018-06-14 20:32:58 +00003850 getInstructionsInTree(PTM.getDstPattern(), PatInstrs);
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003851 if (PatInstrs.size() != 1)
3852 continue;
3853
3854 // Get the single instruction.
3855 CodeGenInstruction &InstInfo = Target.getInstruction(PatInstrs.front());
3856
3857 // Only infer properties from the first pattern. We'll verify the others.
3858 if (InstInfo.InferredFrom)
3859 continue;
3860
3861 InstAnalyzer PatInfo(*this);
Craig Topperb1618d22017-06-20 16:34:37 +00003862 PatInfo.Analyze(PTM);
Jakob Stoklund Olesen4ad27ed2012-08-24 22:46:53 +00003863 Errors += InferFromPattern(InstInfo, PatInfo, PTM.getSrcRecord());
3864 }
3865
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003866 if (Errors)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00003867 PrintFatalError("pattern conflicts");
Jakob Stoklund Olesen91f8dc92012-08-24 17:08:41 +00003868
Ulrich Weigand3a904262018-07-13 13:18:00 +00003869 // If requested by the target, guess any undefined properties.
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003870 if (Target.guessInstructionProperties()) {
Ulrich Weigand3a904262018-07-13 13:18:00 +00003871 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3872 CodeGenInstruction *InstInfo =
3873 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper16642322015-11-22 20:46:24 +00003874 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003875 continue;
3876 // The mayLoad and mayStore flags default to false.
3877 // Conservatively assume hasSideEffects if it wasn't explicit.
Craig Topper16642322015-11-22 20:46:24 +00003878 if (InstInfo->hasSideEffects_Unset)
3879 InstInfo->hasSideEffects = true;
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003880 }
3881 return;
3882 }
3883
3884 // Complain about any flags that are still undefined.
Ulrich Weigand3a904262018-07-13 13:18:00 +00003885 for (unsigned i = 0, e = Instructions.size(); i != e; ++i) {
3886 CodeGenInstruction *InstInfo =
3887 const_cast<CodeGenInstruction *>(Instructions[i]);
Craig Topper16642322015-11-22 20:46:24 +00003888 if (InstInfo->InferredFrom)
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003889 continue;
Craig Topper16642322015-11-22 20:46:24 +00003890 if (InstInfo->hasSideEffects_Unset)
3891 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003892 "Can't infer hasSideEffects from patterns");
Craig Topper16642322015-11-22 20:46:24 +00003893 if (InstInfo->mayStore_Unset)
3894 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003895 "Can't infer mayStore from patterns");
Craig Topper16642322015-11-22 20:46:24 +00003896 if (InstInfo->mayLoad_Unset)
3897 PrintError(InstInfo->TheDef->getLoc(),
Jakob Stoklund Olesen912519a2012-08-24 00:31:16 +00003898 "Can't infer mayLoad from patterns");
Dan Gohmanee4fa192008-04-03 00:02:49 +00003899 }
3900}
3901
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003902
3903/// Verify instruction flags against pattern node properties.
3904void CodeGenDAGPatterns::VerifyInstructionFlags() {
3905 unsigned Errors = 0;
3906 for (ptm_iterator I = ptm_begin(), E = ptm_end(); I != E; ++I) {
3907 const PatternToMatch &PTM = *I;
3908 SmallVector<Record*, 8> Instrs;
Florian Hahn74dff3b2018-06-14 20:32:58 +00003909 getInstructionsInTree(PTM.getDstPattern(), Instrs);
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003910 if (Instrs.empty())
3911 continue;
3912
3913 // Count the number of instructions with each flag set.
3914 unsigned NumSideEffects = 0;
3915 unsigned NumStores = 0;
3916 unsigned NumLoads = 0;
Craig Topper16642322015-11-22 20:46:24 +00003917 for (const Record *Instr : Instrs) {
3918 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003919 NumSideEffects += InstInfo.hasSideEffects;
3920 NumStores += InstInfo.mayStore;
3921 NumLoads += InstInfo.mayLoad;
3922 }
3923
3924 // Analyze the source pattern.
3925 InstAnalyzer PatInfo(*this);
Craig Topperb1618d22017-06-20 16:34:37 +00003926 PatInfo.Analyze(PTM);
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003927
3928 // Collect error messages.
3929 SmallVector<std::string, 4> Msgs;
3930
3931 // Check for missing flags in the output.
3932 // Permit extra flags for now at least.
3933 if (PatInfo.hasSideEffects && !NumSideEffects)
3934 Msgs.push_back("pattern has side effects, but hasSideEffects isn't set");
3935
3936 // Don't verify store flags on instructions with side effects. At least for
3937 // intrinsics, side effects implies mayStore.
3938 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
3939 Msgs.push_back("pattern may store, but mayStore isn't set");
3940
3941 // Similarly, mayStore implies mayLoad on intrinsics.
3942 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
3943 Msgs.push_back("pattern may load, but mayLoad isn't set");
3944
3945 // Print error messages.
3946 if (Msgs.empty())
3947 continue;
3948 ++Errors;
3949
Craig Topper16642322015-11-22 20:46:24 +00003950 for (const std::string &Msg : Msgs)
3951 PrintError(PTM.getSrcRecord()->getLoc(), Twine(Msg) + " on the " +
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003952 (Instrs.size() == 1 ?
3953 "instruction" : "output instructions"));
3954 // Provide the location of the relevant instruction definitions.
Craig Topper16642322015-11-22 20:46:24 +00003955 for (const Record *Instr : Instrs) {
3956 if (Instr != PTM.getSrcRecord())
3957 PrintError(Instr->getLoc(), "defined here");
3958 const CodeGenInstruction &InstInfo = Target.getInstruction(Instr);
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003959 if (InstInfo.InferredFrom &&
3960 InstInfo.InferredFrom != InstInfo.TheDef &&
3961 InstInfo.InferredFrom != PTM.getSrcRecord())
Bruce Mitchener767c34a2015-09-12 01:17:08 +00003962 PrintError(InstInfo.InferredFrom->getLoc(), "inferred from pattern");
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003963 }
3964 }
3965 if (Errors)
Joerg Sonnenberger61131ab2012-10-25 20:33:17 +00003966 PrintFatalError("Errors in DAG patterns");
Jakob Stoklund Olesen325907d2012-08-28 03:26:49 +00003967}
3968
Chris Lattner2cacec52010-03-15 06:00:16 +00003969/// Given a pattern result with an unresolved type, see if we can find one
3970/// instruction with an unresolved result type. Force this result type to an
3971/// arbitrary element if it's possible types to converge results.
Florian Hahn74dff3b2018-06-14 20:32:58 +00003972static bool ForceArbitraryInstResultType(TreePatternNode *N, TreePattern &TP) {
3973 if (N->isLeaf())
Chris Lattner2cacec52010-03-15 06:00:16 +00003974 return false;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003975
Chris Lattner2cacec52010-03-15 06:00:16 +00003976 // Analyze children.
Florian Hahn74dff3b2018-06-14 20:32:58 +00003977 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3978 if (ForceArbitraryInstResultType(N->getChild(i), TP))
Chris Lattner2cacec52010-03-15 06:00:16 +00003979 return true;
3980
Florian Hahn74dff3b2018-06-14 20:32:58 +00003981 if (!N->getOperator()->isSubClassOf("Instruction"))
Chris Lattner2cacec52010-03-15 06:00:16 +00003982 return false;
3983
3984 // If this type is already concrete or completely unknown we can't do
3985 // anything.
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00003986 TypeInfer &TI = TP.getInfer();
Florian Hahn74dff3b2018-06-14 20:32:58 +00003987 for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i) {
3988 if (N->getExtType(i).empty() || TI.isConcrete(N->getExtType(i), false))
Chris Lattnerd7349192010-03-19 21:37:09 +00003989 continue;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003990
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00003991 // Otherwise, force its type to an arbitrary choice.
Florian Hahn74dff3b2018-06-14 20:32:58 +00003992 if (TI.forceArbitrary(N->getExtType(i)))
Chris Lattnerd7349192010-03-19 21:37:09 +00003993 return true;
3994 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00003995
Chris Lattnerd7349192010-03-19 21:37:09 +00003996 return false;
Chris Lattner2cacec52010-03-15 06:00:16 +00003997}
3998
Ulrich Weigandafca5c22018-08-01 11:57:58 +00003999// Promote xform function to be an explicit node wherever set.
4000static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4001 if (Record *Xform = N->getTransformFn()) {
4002 N->setTransformFn(nullptr);
4003 std::vector<TreePatternNodePtr> Children;
4004 Children.push_back(PromoteXForms(N));
4005 return std::make_shared<TreePatternNode>(Xform, std::move(Children),
4006 N->getNumTypes());
4007 }
4008
4009 if (!N->isLeaf())
4010 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4011 TreePatternNodePtr Child = N->getChildShared(i);
Ulrich Weigand18595742018-08-01 12:07:32 +00004012 N->setChild(i, PromoteXForms(Child));
Ulrich Weigandafca5c22018-08-01 11:57:58 +00004013 }
4014 return N;
4015}
4016
Ulrich Weigand3a904262018-07-13 13:18:00 +00004017void CodeGenDAGPatterns::ParseOnePattern(Record *TheDef,
4018 TreePattern &Pattern, TreePattern &Result,
4019 const std::vector<Record *> &InstImpResults) {
4020
4021 // Inline pattern fragments and expand multiple alternatives.
4022 Pattern.InlinePatternFragments();
4023 Result.InlinePatternFragments();
4024
4025 if (Result.getNumTrees() != 1)
4026 Result.error("Cannot use multi-alternative fragments in result pattern!");
4027
4028 // Infer types.
4029 bool IterateInference;
4030 bool InferredAllPatternTypes, InferredAllResultTypes;
4031 do {
4032 // Infer as many types as possible. If we cannot infer all of them, we
4033 // can never do anything with this pattern: report it to the user.
4034 InferredAllPatternTypes =
4035 Pattern.InferAllTypes(&Pattern.getNamedNodesMap());
4036
4037 // Infer as many types as possible. If we cannot infer all of them, we
4038 // can never do anything with this pattern: report it to the user.
4039 InferredAllResultTypes =
4040 Result.InferAllTypes(&Pattern.getNamedNodesMap());
4041
4042 IterateInference = false;
4043
4044 // Apply the type of the result to the source pattern. This helps us
4045 // resolve cases where the input type is known to be a pointer type (which
4046 // is considered resolved), but the result knows it needs to be 32- or
4047 // 64-bits. Infer the other way for good measure.
4048 for (auto T : Pattern.getTrees())
4049 for (unsigned i = 0, e = std::min(Result.getOnlyTree()->getNumTypes(),
4050 T->getNumTypes());
4051 i != e; ++i) {
4052 IterateInference |= T->UpdateNodeType(
4053 i, Result.getOnlyTree()->getExtType(i), Result);
4054 IterateInference |= Result.getOnlyTree()->UpdateNodeType(
4055 i, T->getExtType(i), Result);
4056 }
4057
4058 // If our iteration has converged and the input pattern's types are fully
4059 // resolved but the result pattern is not fully resolved, we may have a
4060 // situation where we have two instructions in the result pattern and
4061 // the instructions require a common register class, but don't care about
4062 // what actual MVT is used. This is actually a bug in our modelling:
4063 // output patterns should have register classes, not MVTs.
4064 //
4065 // In any case, to handle this, we just go through and disambiguate some
4066 // arbitrary types to the result pattern's nodes.
4067 if (!IterateInference && InferredAllPatternTypes &&
4068 !InferredAllResultTypes)
4069 IterateInference =
4070 ForceArbitraryInstResultType(Result.getTree(0).get(), Result);
4071 } while (IterateInference);
4072
4073 // Verify that we inferred enough types that we can do something with the
4074 // pattern and result. If these fire the user has to add type casts.
4075 if (!InferredAllPatternTypes)
4076 Pattern.error("Could not infer all types in pattern!");
4077 if (!InferredAllResultTypes) {
4078 Pattern.dump();
4079 Result.error("Could not infer all types in pattern result!");
4080 }
4081
Ulrich Weigandafca5c22018-08-01 11:57:58 +00004082 // Promote xform function to be an explicit node wherever set.
4083 TreePatternNodePtr DstShared = PromoteXForms(Result.getOnlyTree());
Ulrich Weigand3a904262018-07-13 13:18:00 +00004084
4085 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4086 Temp.InferAllTypes();
4087
4088 ListInit *Preds = TheDef->getValueAsListInit("Predicates");
4089 int Complexity = TheDef->getValueAsInt("AddedComplexity");
4090
4091 if (PatternRewriter)
4092 PatternRewriter(&Pattern);
4093
4094 // A pattern may end up with an "impossible" type, i.e. a situation
4095 // where all types have been eliminated for some node in this pattern.
4096 // This could occur for intrinsics that only make sense for a specific
4097 // value type, and use a specific register class. If, for some mode,
4098 // that register class does not accept that type, the type inference
4099 // will lead to a contradiction, which is not an error however, but
4100 // a sign that this pattern will simply never match.
4101 if (Temp.getOnlyTree()->hasPossibleType())
4102 for (auto T : Pattern.getTrees())
4103 if (T->hasPossibleType())
4104 AddPatternToMatch(&Pattern,
4105 PatternToMatch(TheDef, makePredList(Preds),
4106 T, Temp.getOnlyTree(),
4107 InstImpResults, Complexity,
4108 TheDef->getID()));
4109}
4110
Chris Lattnerfe718932008-01-06 01:10:31 +00004111void CodeGenDAGPatterns::ParsePatterns() {
Chris Lattner6cefb772008-01-05 22:25:12 +00004112 std::vector<Record*> Patterns = Records.getAllDerivedDefinitions("Pattern");
4113
Craig Topper16642322015-11-22 20:46:24 +00004114 for (Record *CurPattern : Patterns) {
David Greene05bce0b2011-07-29 22:43:06 +00004115 DagInit *Tree = CurPattern->getValueAsDag("PatternToMatch");
Jim Grosbachd3e31212012-07-17 18:39:36 +00004116
4117 // If the pattern references the null_frag, there's nothing to do.
4118 if (hasNullFragReference(Tree))
4119 continue;
4120
Florian Hahn0b596f02018-05-30 21:00:18 +00004121 TreePattern Pattern(CurPattern, Tree, true, *this);
Chris Lattner6cefb772008-01-05 22:25:12 +00004122
David Greene05bce0b2011-07-29 22:43:06 +00004123 ListInit *LI = CurPattern->getValueAsListInit("ResultInstrs");
Craig Topperbbf57b32015-05-14 05:53:53 +00004124 if (LI->empty()) continue; // no pattern.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004125
Chris Lattner6cefb772008-01-05 22:25:12 +00004126 // Parse the instruction.
David Blaikie6141b4a2014-11-14 21:53:50 +00004127 TreePattern Result(CurPattern, LI, false, *this);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004128
David Blaikie6141b4a2014-11-14 21:53:50 +00004129 if (Result.getNumTrees() != 1)
4130 Result.error("Cannot handle instructions producing instructions "
4131 "with temporaries yet!");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004132
Chris Lattner6cefb772008-01-05 22:25:12 +00004133 // Validate that the input pattern is correct.
Florian Hahn0b596f02018-05-30 21:00:18 +00004134 std::map<std::string, TreePatternNodePtr> InstInputs;
Craig Topper0f562fe2018-12-05 00:47:59 +00004135 MapVector<std::string, TreePatternNodePtr, std::map<std::string, unsigned>>
4136 InstResults;
Chris Lattner6cefb772008-01-05 22:25:12 +00004137 std::vector<Record*> InstImpResults;
Florian Hahn0b596f02018-05-30 21:00:18 +00004138 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
David Blaikie7f3c26c2018-06-11 22:14:43 +00004139 FindPatternInputsAndOutputs(Pattern, Pattern.getTree(j), InstInputs,
Florian Hahn0b596f02018-05-30 21:00:18 +00004140 InstResults, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00004141
Ulrich Weigand3a904262018-07-13 13:18:00 +00004142 ParseOnePattern(CurPattern, Pattern, Result, InstImpResults);
Chris Lattner6cefb772008-01-05 22:25:12 +00004143 }
4144}
4145
Florian Hahn74dff3b2018-06-14 20:32:58 +00004146static void collectModes(std::set<unsigned> &Modes, const TreePatternNode *N) {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004147 for (const TypeSetByHwMode &VTS : N->getExtTypes())
4148 for (const auto &I : VTS)
4149 Modes.insert(I.first);
4150
4151 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn74dff3b2018-06-14 20:32:58 +00004152 collectModes(Modes, N->getChild(i));
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004153}
4154
4155void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4156 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4157 std::map<unsigned,std::vector<Predicate>> ModeChecks;
4158 std::vector<PatternToMatch> Copy = PatternsToMatch;
4159 PatternsToMatch.clear();
4160
Florian Hahn0b596f02018-05-30 21:00:18 +00004161 auto AppendPattern = [this, &ModeChecks](PatternToMatch &P, unsigned Mode) {
4162 TreePatternNodePtr NewSrc = P.SrcPattern->clone();
4163 TreePatternNodePtr NewDst = P.DstPattern->clone();
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004164 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004165 return;
4166 }
4167
4168 std::vector<Predicate> Preds = P.Predicates;
4169 const std::vector<Predicate> &MC = ModeChecks[Mode];
4170 Preds.insert(Preds.end(), MC.begin(), MC.end());
Florian Hahn5cd96b72018-06-14 11:56:19 +00004171 PatternsToMatch.emplace_back(P.getSrcRecord(), Preds, std::move(NewSrc),
4172 std::move(NewDst), P.getDstRegs(),
4173 P.getAddedComplexity(), Record::getNewUID(),
4174 Mode);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004175 };
4176
4177 for (PatternToMatch &P : Copy) {
Florian Hahn0b596f02018-05-30 21:00:18 +00004178 TreePatternNodePtr SrcP = nullptr, DstP = nullptr;
Florian Hahn74dff3b2018-06-14 20:32:58 +00004179 if (P.SrcPattern->hasProperTypeByHwMode())
4180 SrcP = P.SrcPattern;
4181 if (P.DstPattern->hasProperTypeByHwMode())
4182 DstP = P.DstPattern;
4183 if (!SrcP && !DstP) {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004184 PatternsToMatch.push_back(P);
4185 continue;
4186 }
4187
4188 std::set<unsigned> Modes;
Florian Hahn74dff3b2018-06-14 20:32:58 +00004189 if (SrcP)
4190 collectModes(Modes, SrcP.get());
4191 if (DstP)
4192 collectModes(Modes, DstP.get());
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004193
4194 // The predicate for the default mode needs to be constructed for each
4195 // pattern separately.
4196 // Since not all modes must be present in each pattern, if a mode m is
4197 // absent, then there is no point in constructing a check for m. If such
4198 // a check was created, it would be equivalent to checking the default
4199 // mode, except not all modes' predicates would be a part of the checking
4200 // code. The subsequently generated check for the default mode would then
4201 // have the exact same patterns, but a different predicate code. To avoid
4202 // duplicated patterns with different predicate checks, construct the
4203 // default check as a negation of all predicates that are actually present
4204 // in the source/destination patterns.
4205 std::vector<Predicate> DefaultPred;
4206
4207 for (unsigned M : Modes) {
4208 if (M == DefaultMode)
4209 continue;
4210 if (ModeChecks.find(M) != ModeChecks.end())
4211 continue;
4212
4213 // Fill the map entry for this mode.
4214 const HwMode &HM = CGH.getMode(M);
4215 ModeChecks[M].emplace_back(Predicate(HM.Features, true));
4216
4217 // Add negations of the HM's predicates to the default predicate.
4218 DefaultPred.emplace_back(Predicate(HM.Features, false));
4219 }
4220
4221 for (unsigned M : Modes) {
4222 if (M == DefaultMode)
4223 continue;
4224 AppendPattern(P, M);
4225 }
4226
4227 bool HasDefault = Modes.count(DefaultMode);
4228 if (HasDefault)
4229 AppendPattern(P, DefaultMode);
4230 }
4231}
4232
4233/// Dependent variable map for CodeGenDAGPattern variant generation
Zachary Turnere4442992017-09-20 18:01:40 +00004234typedef StringMap<int> DepVarMap;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004235
Florian Hahn74dff3b2018-06-14 20:32:58 +00004236static void FindDepVarsOf(TreePatternNode *N, DepVarMap &DepMap) {
4237 if (N->isLeaf()) {
4238 if (N->hasName() && isa<DefInit>(N->getLeafValue()))
4239 DepMap[N->getName()]++;
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004240 } else {
Florian Hahn74dff3b2018-06-14 20:32:58 +00004241 for (size_t i = 0, e = N->getNumChildren(); i != e; ++i)
4242 FindDepVarsOf(N->getChild(i), DepMap);
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004243 }
4244}
4245
4246/// Find dependent variables within child patterns
Florian Hahn74dff3b2018-06-14 20:32:58 +00004247static void FindDepVars(TreePatternNode *N, MultipleUseVarSet &DepVars) {
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004248 DepVarMap depcounts;
4249 FindDepVarsOf(N, depcounts);
Zachary Turnere4442992017-09-20 18:01:40 +00004250 for (const auto &Pair : depcounts) {
4251 if (Pair.getValue() > 1)
4252 DepVars.insert(Pair.getKey());
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004253 }
4254}
4255
4256#ifndef NDEBUG
4257/// Dump the dependent variable set:
4258static void DumpDepVars(MultipleUseVarSet &DepVars) {
4259 if (DepVars.empty()) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00004260 LLVM_DEBUG(errs() << "<empty set>");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004261 } else {
Nicola Zaghen0818e782018-05-14 12:53:11 +00004262 LLVM_DEBUG(errs() << "[ ");
Zachary Turnere4442992017-09-20 18:01:40 +00004263 for (const auto &DepVar : DepVars) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00004264 LLVM_DEBUG(errs() << DepVar.getKey() << " ");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004265 }
Nicola Zaghen0818e782018-05-14 12:53:11 +00004266 LLVM_DEBUG(errs() << "]");
Krzysztof Parzyszekdb815642017-09-14 16:56:21 +00004267 }
4268}
4269#endif
4270
4271
Chris Lattner6cefb772008-01-05 22:25:12 +00004272/// CombineChildVariants - Given a bunch of permutations of each child of the
4273/// 'operator' node, put them together in all possible ways.
Florian Hahn0b596f02018-05-30 21:00:18 +00004274static void CombineChildVariants(
Florian Hahn74dff3b2018-06-14 20:32:58 +00004275 TreePatternNodePtr Orig,
Florian Hahn0b596f02018-05-30 21:00:18 +00004276 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4277 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4278 const MultipleUseVarSet &DepVars) {
Chris Lattner6cefb772008-01-05 22:25:12 +00004279 // Make sure that each operand has at least one variant to choose from.
Craig Topper16642322015-11-22 20:46:24 +00004280 for (const auto &Variants : ChildVariants)
4281 if (Variants.empty())
Chris Lattner6cefb772008-01-05 22:25:12 +00004282 return;
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004283
Chris Lattner6cefb772008-01-05 22:25:12 +00004284 // The end result is an all-pairs construction of the resultant pattern.
4285 std::vector<unsigned> Idxs;
4286 Idxs.resize(ChildVariants.size());
Scott Michel327d0652008-03-05 17:49:05 +00004287 bool NotDone;
4288 do {
4289#ifndef NDEBUG
Nicola Zaghen0818e782018-05-14 12:53:11 +00004290 LLVM_DEBUG(if (!Idxs.empty()) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00004291 errs() << Orig->getOperator()->getName() << ": Idxs = [ ";
Nicola Zaghen0818e782018-05-14 12:53:11 +00004292 for (unsigned Idx : Idxs) {
4293 errs() << Idx << " ";
4294 }
4295 errs() << "]\n";
4296 });
Scott Michel327d0652008-03-05 17:49:05 +00004297#endif
Chris Lattner6cefb772008-01-05 22:25:12 +00004298 // Create the variant and add it to the output list.
Florian Hahn0b596f02018-05-30 21:00:18 +00004299 std::vector<TreePatternNodePtr> NewChildren;
Chris Lattner6cefb772008-01-05 22:25:12 +00004300 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4301 NewChildren.push_back(ChildVariants[i][Idxs[i]]);
Florian Hahn0b596f02018-05-30 21:00:18 +00004302 TreePatternNodePtr R = std::make_shared<TreePatternNode>(
Craig Toppercfe3c912018-07-15 06:52:49 +00004303 Orig->getOperator(), std::move(NewChildren), Orig->getNumTypes());
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004304
Chris Lattner6cefb772008-01-05 22:25:12 +00004305 // Copy over properties.
Florian Hahn74dff3b2018-06-14 20:32:58 +00004306 R->setName(Orig->getName());
Nicolai Haehnle98272e42018-11-30 14:15:13 +00004307 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4308 R->setPredicateCalls(Orig->getPredicateCalls());
Florian Hahn74dff3b2018-06-14 20:32:58 +00004309 R->setTransformFn(Orig->getTransformFn());
4310 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4311 R->setType(i, Orig->getExtType(i));
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004312
Scott Michel327d0652008-03-05 17:49:05 +00004313 // If this pattern cannot match, do not include it as a variant.
Chris Lattner6cefb772008-01-05 22:25:12 +00004314 std::string ErrString;
David Blaikie7ceb9c72015-11-22 20:11:21 +00004315 // Scan to see if this pattern has already been emitted. We can get
4316 // duplication due to things like commuting:
4317 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4318 // which are the same pattern. Ignore the dups.
4319 if (R->canPatternMatch(ErrString, CDP) &&
Florian Hahn0b596f02018-05-30 21:00:18 +00004320 none_of(OutVariants, [&](TreePatternNodePtr Variant) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00004321 return R->isIsomorphicTo(Variant.get(), DepVars);
David Majnemerdc9c7372016-08-11 21:15:00 +00004322 }))
Florian Hahn0b596f02018-05-30 21:00:18 +00004323 OutVariants.push_back(R);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004324
Scott Michel327d0652008-03-05 17:49:05 +00004325 // Increment indices to the next permutation by incrementing the
Bruce Mitchener767c34a2015-09-12 01:17:08 +00004326 // indices from last index backward, e.g., generate the sequence
Scott Michel327d0652008-03-05 17:49:05 +00004327 // [0, 0], [0, 1], [1, 0], [1, 1].
4328 int IdxsIdx;
4329 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4330 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4331 Idxs[IdxsIdx] = 0;
4332 else
Chris Lattner6cefb772008-01-05 22:25:12 +00004333 break;
Chris Lattner6cefb772008-01-05 22:25:12 +00004334 }
Scott Michel327d0652008-03-05 17:49:05 +00004335 NotDone = (IdxsIdx >= 0);
4336 } while (NotDone);
Chris Lattner6cefb772008-01-05 22:25:12 +00004337}
4338
4339/// CombineChildVariants - A helper function for binary operators.
4340///
Florian Hahn74dff3b2018-06-14 20:32:58 +00004341static void CombineChildVariants(TreePatternNodePtr Orig,
Florian Hahn0b596f02018-05-30 21:00:18 +00004342 const std::vector<TreePatternNodePtr> &LHS,
4343 const std::vector<TreePatternNodePtr> &RHS,
4344 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00004345 CodeGenDAGPatterns &CDP,
4346 const MultipleUseVarSet &DepVars) {
Florian Hahn0b596f02018-05-30 21:00:18 +00004347 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner6cefb772008-01-05 22:25:12 +00004348 ChildVariants.push_back(LHS);
4349 ChildVariants.push_back(RHS);
Scott Michel327d0652008-03-05 17:49:05 +00004350 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004351}
Chris Lattner6cefb772008-01-05 22:25:12 +00004352
Florian Hahn0b596f02018-05-30 21:00:18 +00004353static void
Florian Hahn74dff3b2018-06-14 20:32:58 +00004354GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
Florian Hahn0b596f02018-05-30 21:00:18 +00004355 std::vector<TreePatternNodePtr> &Children) {
Chris Lattner6cefb772008-01-05 22:25:12 +00004356 assert(N->getNumChildren()==2 &&"Associative but doesn't have 2 children!");
4357 Record *Operator = N->getOperator();
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004358
Chris Lattner6cefb772008-01-05 22:25:12 +00004359 // Only permit raw nodes.
Nicolai Haehnle98272e42018-11-30 14:15:13 +00004360 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
Chris Lattner6cefb772008-01-05 22:25:12 +00004361 N->getTransformFn()) {
4362 Children.push_back(N);
4363 return;
4364 }
4365
Florian Hahn74dff3b2018-06-14 20:32:58 +00004366 if (N->getChild(0)->isLeaf() || N->getChild(0)->getOperator() != Operator)
Florian Hahn0b596f02018-05-30 21:00:18 +00004367 Children.push_back(N->getChildShared(0));
Chris Lattner6cefb772008-01-05 22:25:12 +00004368 else
Florian Hahn0b596f02018-05-30 21:00:18 +00004369 GatherChildrenOfAssociativeOpcode(N->getChildShared(0), Children);
Chris Lattner6cefb772008-01-05 22:25:12 +00004370
Florian Hahn74dff3b2018-06-14 20:32:58 +00004371 if (N->getChild(1)->isLeaf() || N->getChild(1)->getOperator() != Operator)
Florian Hahn0b596f02018-05-30 21:00:18 +00004372 Children.push_back(N->getChildShared(1));
Chris Lattner6cefb772008-01-05 22:25:12 +00004373 else
Florian Hahn0b596f02018-05-30 21:00:18 +00004374 GatherChildrenOfAssociativeOpcode(N->getChildShared(1), Children);
Chris Lattner6cefb772008-01-05 22:25:12 +00004375}
4376
4377/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4378/// the (potentially recursive) pattern by using algebraic laws.
4379///
Florian Hahn74dff3b2018-06-14 20:32:58 +00004380static void GenerateVariantsOf(TreePatternNodePtr N,
Florian Hahn0b596f02018-05-30 21:00:18 +00004381 std::vector<TreePatternNodePtr> &OutVariants,
Scott Michel327d0652008-03-05 17:49:05 +00004382 CodeGenDAGPatterns &CDP,
4383 const MultipleUseVarSet &DepVars) {
Tim Northoveree8d5c32014-05-20 11:52:46 +00004384 // We cannot permute leaves or ComplexPattern uses.
4385 if (N->isLeaf() || N->getOperator()->isSubClassOf("ComplexPattern")) {
Chris Lattner6cefb772008-01-05 22:25:12 +00004386 OutVariants.push_back(N);
4387 return;
4388 }
4389
4390 // Look up interesting info about the node.
4391 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(N->getOperator());
4392
Jim Grosbachda4231f2009-03-26 16:17:51 +00004393 // If this node is associative, re-associate.
Chris Lattner6cefb772008-01-05 22:25:12 +00004394 if (NodeInfo.hasProperty(SDNPAssociative)) {
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004395 // Re-associate by pulling together all of the linked operators
Florian Hahn0b596f02018-05-30 21:00:18 +00004396 std::vector<TreePatternNodePtr> MaximalChildren;
Chris Lattner6cefb772008-01-05 22:25:12 +00004397 GatherChildrenOfAssociativeOpcode(N, MaximalChildren);
4398
4399 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4400 // permutations.
4401 if (MaximalChildren.size() == 3) {
4402 // Find the variants of all of our maximal children.
Florian Hahn0b596f02018-05-30 21:00:18 +00004403 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
Scott Michel327d0652008-03-05 17:49:05 +00004404 GenerateVariantsOf(MaximalChildren[0], AVariants, CDP, DepVars);
4405 GenerateVariantsOf(MaximalChildren[1], BVariants, CDP, DepVars);
4406 GenerateVariantsOf(MaximalChildren[2], CVariants, CDP, DepVars);
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004407
Chris Lattner6cefb772008-01-05 22:25:12 +00004408 // There are only two ways we can permute the tree:
4409 // (A op B) op C and A op (B op C)
4410 // Within these forms, we can also permute A/B/C.
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004411
Chris Lattner6cefb772008-01-05 22:25:12 +00004412 // Generate legal pair permutations of A/B/C.
Florian Hahn0b596f02018-05-30 21:00:18 +00004413 std::vector<TreePatternNodePtr> ABVariants;
4414 std::vector<TreePatternNodePtr> BAVariants;
4415 std::vector<TreePatternNodePtr> ACVariants;
4416 std::vector<TreePatternNodePtr> CAVariants;
4417 std::vector<TreePatternNodePtr> BCVariants;
4418 std::vector<TreePatternNodePtr> CBVariants;
Florian Hahn74dff3b2018-06-14 20:32:58 +00004419 CombineChildVariants(N, AVariants, BVariants, ABVariants, CDP, DepVars);
4420 CombineChildVariants(N, BVariants, AVariants, BAVariants, CDP, DepVars);
4421 CombineChildVariants(N, AVariants, CVariants, ACVariants, CDP, DepVars);
4422 CombineChildVariants(N, CVariants, AVariants, CAVariants, CDP, DepVars);
4423 CombineChildVariants(N, BVariants, CVariants, BCVariants, CDP, DepVars);
4424 CombineChildVariants(N, CVariants, BVariants, CBVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00004425
4426 // Combine those into the result: (x op x) op x
Florian Hahn74dff3b2018-06-14 20:32:58 +00004427 CombineChildVariants(N, ABVariants, CVariants, OutVariants, CDP, DepVars);
4428 CombineChildVariants(N, BAVariants, CVariants, OutVariants, CDP, DepVars);
4429 CombineChildVariants(N, ACVariants, BVariants, OutVariants, CDP, DepVars);
4430 CombineChildVariants(N, CAVariants, BVariants, OutVariants, CDP, DepVars);
4431 CombineChildVariants(N, BCVariants, AVariants, OutVariants, CDP, DepVars);
4432 CombineChildVariants(N, CBVariants, AVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00004433
4434 // Combine those into the result: x op (x op x)
Florian Hahn74dff3b2018-06-14 20:32:58 +00004435 CombineChildVariants(N, CVariants, ABVariants, OutVariants, CDP, DepVars);
4436 CombineChildVariants(N, CVariants, BAVariants, OutVariants, CDP, DepVars);
4437 CombineChildVariants(N, BVariants, ACVariants, OutVariants, CDP, DepVars);
4438 CombineChildVariants(N, BVariants, CAVariants, OutVariants, CDP, DepVars);
4439 CombineChildVariants(N, AVariants, BCVariants, OutVariants, CDP, DepVars);
4440 CombineChildVariants(N, AVariants, CBVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00004441 return;
4442 }
4443 }
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004444
Chris Lattner6cefb772008-01-05 22:25:12 +00004445 // Compute permutations of all children.
Florian Hahn0b596f02018-05-30 21:00:18 +00004446 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
Chris Lattner6cefb772008-01-05 22:25:12 +00004447 ChildVariants.resize(N->getNumChildren());
4448 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
Florian Hahn0b596f02018-05-30 21:00:18 +00004449 GenerateVariantsOf(N->getChildShared(i), ChildVariants[i], CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00004450
4451 // Build all permutations based on how the children were formed.
Florian Hahn74dff3b2018-06-14 20:32:58 +00004452 CombineChildVariants(N, ChildVariants, OutVariants, CDP, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00004453
4454 // If this node is commutative, consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00004455 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4456 if (NodeInfo.hasProperty(SDNPCommutative) || isCommIntrinsic) {
Craig Topper911f6bb2017-09-04 03:44:33 +00004457 assert((N->getNumChildren()>=2 || isCommIntrinsic) &&
Evan Cheng6bd95672008-06-16 20:29:38 +00004458 "Commutative but doesn't have 2 children!");
Chris Lattner6cefb772008-01-05 22:25:12 +00004459 // Don't count children which are actually register references.
4460 unsigned NC = 0;
4461 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00004462 TreePatternNode *Child = N->getChild(i);
4463 if (Child->isLeaf())
4464 if (DefInit *DI = dyn_cast<DefInit>(Child->getLeafValue())) {
Chris Lattner6cefb772008-01-05 22:25:12 +00004465 Record *RR = DI->getDef();
4466 if (RR->isSubClassOf("Register"))
4467 continue;
4468 }
4469 NC++;
4470 }
4471 // Consider the commuted order.
Evan Cheng6bd95672008-06-16 20:29:38 +00004472 if (isCommIntrinsic) {
4473 // Commutative intrinsic. First operand is the intrinsic id, 2nd and 3rd
4474 // operands are the commutative operands, and there might be more operands
4475 // after those.
4476 assert(NC >= 3 &&
Bruce Mitchener767c34a2015-09-12 01:17:08 +00004477 "Commutative intrinsic should have at least 3 children!");
Florian Hahn0b596f02018-05-30 21:00:18 +00004478 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn5cd96b72018-06-14 11:56:19 +00004479 Variants.push_back(std::move(ChildVariants[0])); // Intrinsic id.
4480 Variants.push_back(std::move(ChildVariants[2]));
4481 Variants.push_back(std::move(ChildVariants[1]));
Evan Cheng6bd95672008-06-16 20:29:38 +00004482 for (unsigned i = 3; i != NC; ++i)
Florian Hahn5cd96b72018-06-14 11:56:19 +00004483 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn74dff3b2018-06-14 20:32:58 +00004484 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper911f6bb2017-09-04 03:44:33 +00004485 } else if (NC == N->getNumChildren()) {
Florian Hahn0b596f02018-05-30 21:00:18 +00004486 std::vector<std::vector<TreePatternNodePtr>> Variants;
Florian Hahn5cd96b72018-06-14 11:56:19 +00004487 Variants.push_back(std::move(ChildVariants[1]));
4488 Variants.push_back(std::move(ChildVariants[0]));
Craig Topper911f6bb2017-09-04 03:44:33 +00004489 for (unsigned i = 2; i != NC; ++i)
Florian Hahn5cd96b72018-06-14 11:56:19 +00004490 Variants.push_back(std::move(ChildVariants[i]));
Florian Hahn74dff3b2018-06-14 20:32:58 +00004491 CombineChildVariants(N, Variants, OutVariants, CDP, DepVars);
Craig Topper911f6bb2017-09-04 03:44:33 +00004492 }
Chris Lattner6cefb772008-01-05 22:25:12 +00004493 }
4494}
4495
4496
4497// GenerateVariants - Generate variants. For example, commutative patterns can
4498// match multiple ways. Add them to PatternsToMatch as well.
Chris Lattnerfe718932008-01-06 01:10:31 +00004499void CodeGenDAGPatterns::GenerateVariants() {
Nicola Zaghen0818e782018-05-14 12:53:11 +00004500 LLVM_DEBUG(errs() << "Generating instruction variants.\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004501
Chris Lattner6cefb772008-01-05 22:25:12 +00004502 // Loop over all of the patterns we've collected, checking to see if we can
4503 // generate variants of the instruction, through the exploitation of
Jim Grosbachda4231f2009-03-26 16:17:51 +00004504 // identities. This permits the target to provide aggressive matching without
Chris Lattner6cefb772008-01-05 22:25:12 +00004505 // the .td file having to contain tons of variants of instructions.
4506 //
4507 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4508 // intentionally do not reconsider these. Any variants of added patterns have
4509 // already been added.
4510 //
Simon Pilgrim686bd242018-09-18 11:30:30 +00004511 const unsigned NumOriginalPatterns = PatternsToMatch.size();
4512 BitVector MatchedPatterns(NumOriginalPatterns);
4513 std::vector<BitVector> MatchedPredicates(NumOriginalPatterns,
4514 BitVector(NumOriginalPatterns));
4515
4516 typedef std::pair<MultipleUseVarSet, std::vector<TreePatternNodePtr>>
4517 DepsAndVariants;
4518 std::map<unsigned, DepsAndVariants> PatternsWithVariants;
4519
4520 // Collect patterns with more than one variant.
4521 for (unsigned i = 0; i != NumOriginalPatterns; ++i) {
4522 MultipleUseVarSet DepVars;
Florian Hahn0b596f02018-05-30 21:00:18 +00004523 std::vector<TreePatternNodePtr> Variants;
Florian Hahn74dff3b2018-06-14 20:32:58 +00004524 FindDepVars(PatternsToMatch[i].getSrcPattern(), DepVars);
Nicola Zaghen0818e782018-05-14 12:53:11 +00004525 LLVM_DEBUG(errs() << "Dependent/multiply used variables: ");
4526 LLVM_DEBUG(DumpDepVars(DepVars));
4527 LLVM_DEBUG(errs() << "\n");
Florian Hahn0b596f02018-05-30 21:00:18 +00004528 GenerateVariantsOf(PatternsToMatch[i].getSrcPatternShared(), Variants,
4529 *this, DepVars);
Chris Lattner6cefb772008-01-05 22:25:12 +00004530
4531 assert(!Variants.empty() && "Must create at least original variant!");
Simon Pilgrim686bd242018-09-18 11:30:30 +00004532 if (Variants.size() == 1) // No additional variants for this pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +00004533 continue;
4534
Nicola Zaghen0818e782018-05-14 12:53:11 +00004535 LLVM_DEBUG(errs() << "FOUND VARIANTS OF: ";
4536 PatternsToMatch[i].getSrcPattern()->dump(); errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00004537
Simon Pilgrim686bd242018-09-18 11:30:30 +00004538 PatternsWithVariants[i] = std::make_pair(DepVars, Variants);
4539
Simon Pilgrimac6174e2018-08-28 15:42:08 +00004540 // Cache matching predicates.
Simon Pilgrim686bd242018-09-18 11:30:30 +00004541 if (MatchedPatterns[i])
4542 continue;
4543
4544 const std::vector<Predicate> &Predicates =
4545 PatternsToMatch[i].getPredicates();
4546
4547 BitVector &Matches = MatchedPredicates[i];
Simon Pilgrimf02ce8d2018-09-19 12:23:50 +00004548 MatchedPatterns.set(i);
4549 Matches.set(i);
Simon Pilgrim686bd242018-09-18 11:30:30 +00004550
4551 // Don't test patterns that have already been cached - it won't match.
4552 for (unsigned p = 0; p != NumOriginalPatterns; ++p)
4553 if (!MatchedPatterns[p])
4554 Matches[p] = (Predicates == PatternsToMatch[p].getPredicates());
4555
4556 // Copy this to all the matching patterns.
4557 for (int p = Matches.find_first(); p != -1; p = Matches.find_next(p))
Simon Pilgrim275d69b2018-09-18 12:01:25 +00004558 if (p != (int)i) {
Simon Pilgrimf02ce8d2018-09-19 12:23:50 +00004559 MatchedPatterns.set(p);
Simon Pilgrim686bd242018-09-18 11:30:30 +00004560 MatchedPredicates[p] = Matches;
4561 }
4562 }
4563
4564 for (auto it : PatternsWithVariants) {
4565 unsigned i = it.first;
4566 const MultipleUseVarSet &DepVars = it.second.first;
4567 const std::vector<TreePatternNodePtr> &Variants = it.second.second;
Simon Pilgrimac6174e2018-08-28 15:42:08 +00004568
Chris Lattner6cefb772008-01-05 22:25:12 +00004569 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
Florian Hahn74dff3b2018-06-14 20:32:58 +00004570 TreePatternNodePtr Variant = Variants[v];
Simon Pilgrim686bd242018-09-18 11:30:30 +00004571 BitVector &Matches = MatchedPredicates[i];
Chris Lattner6cefb772008-01-05 22:25:12 +00004572
Nicola Zaghen0818e782018-05-14 12:53:11 +00004573 LLVM_DEBUG(errs() << " VAR#" << v << ": "; Variant->dump();
4574 errs() << "\n");
Jim Grosbachfbadcd02010-12-21 16:16:00 +00004575
Chris Lattner6cefb772008-01-05 22:25:12 +00004576 // Scan to see if an instruction or explicit pattern already matches this.
4577 bool AlreadyExists = false;
Craig Topper020e2402015-11-22 22:43:40 +00004578 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
Evan Chengc0ad80f2009-06-26 05:59:16 +00004579 // Skip if the top level predicates do not match.
Simon Pilgrim686bd242018-09-18 11:30:30 +00004580 if (!Matches[p])
Evan Chengc0ad80f2009-06-26 05:59:16 +00004581 continue;
Chris Lattner6cefb772008-01-05 22:25:12 +00004582 // Check to see if this variant already exists.
Florian Hahn74dff3b2018-06-14 20:32:58 +00004583 if (Variant->isIsomorphicTo(PatternsToMatch[p].getSrcPattern(),
Craig Topper020e2402015-11-22 22:43:40 +00004584 DepVars)) {
Nicola Zaghen0818e782018-05-14 12:53:11 +00004585 LLVM_DEBUG(errs() << " *** ALREADY EXISTS, ignoring variant.\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00004586 AlreadyExists = true;
4587 break;
4588 }
4589 }
4590 // If we already have it, ignore the variant.
4591 if (AlreadyExists) continue;
4592
4593 // Otherwise, add it to the list of patterns we have.
Ayman Musa1921b1c2017-06-27 07:10:20 +00004594 PatternsToMatch.push_back(PatternToMatch(
Craig Topper020e2402015-11-22 22:43:40 +00004595 PatternsToMatch[i].getSrcRecord(), PatternsToMatch[i].getPredicates(),
Florian Hahn0b596f02018-05-30 21:00:18 +00004596 Variant, PatternsToMatch[i].getDstPatternShared(),
Craig Topper020e2402015-11-22 22:43:40 +00004597 PatternsToMatch[i].getDstRegs(),
Ayman Musa1921b1c2017-06-27 07:10:20 +00004598 PatternsToMatch[i].getAddedComplexity(), Record::getNewUID()));
Simon Pilgrim686bd242018-09-18 11:30:30 +00004599 MatchedPredicates.push_back(Matches);
4600
Simon Pilgrimff6f0e22018-09-18 14:05:07 +00004601 // Add a new match the same as this pattern.
Simon Pilgrimff6f0e22018-09-18 14:05:07 +00004602 for (auto &P : MatchedPredicates)
Simon Pilgrim60bebed2018-09-19 11:18:49 +00004603 P.push_back(P[i]);
Chris Lattner6cefb772008-01-05 22:25:12 +00004604 }
4605
Nicola Zaghen0818e782018-05-14 12:53:11 +00004606 LLVM_DEBUG(errs() << "\n");
Chris Lattner6cefb772008-01-05 22:25:12 +00004607 }
4608}