1//===- CodeGenDAGPatterns.cpp - Read DAG patterns from .td file -----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the CodeGenDAGPatterns class, which is used to read and
10// represent the patterns present in a .td file for instructions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenDAGPatterns.h"
15#include "CodeGenInstruction.h"
16#include "CodeGenRegisters.h"
17#include "SubtargetFeatureInfo.h"
18#include "llvm/ADT/DenseSet.h"
19#include "llvm/ADT/MapVector.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/ADT/SmallString.h"
23#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/StringMap.h"
25#include "llvm/ADT/Twine.h"
26#include "llvm/Support/Debug.h"
27#include "llvm/Support/ErrorHandling.h"
28#include "llvm/Support/InterleavedRange.h"
29#include "llvm/Support/TypeSize.h"
30#include "llvm/TableGen/Error.h"
31#include "llvm/TableGen/Record.h"
32#include <algorithm>
33#include <cstdio>
34#include <iterator>
35#include <set>
36using namespace llvm;
37
38#define DEBUG_TYPE "dag-patterns"
39
40static inline bool isIntegerOrPtr(MVT VT) {
41 return VT.isInteger() || VT == MVT::iPTR;
42}
43static inline bool isFloatingPoint(MVT VT) { return VT.isFloatingPoint(); }
44static inline bool isVector(MVT VT) { return VT.isVector(); }
45static inline bool isScalar(MVT VT) { return !VT.isVector(); }
46
47template <typename Predicate>
48static bool berase_if(MachineValueTypeSet &S, Predicate P) {
49 bool Erased = false;
50 // It is ok to iterate over MachineValueTypeSet and remove elements from it
51 // at the same time.
52 for (MVT T : S) {
53 if (!P(T))
54 continue;
55 Erased = true;
56 S.erase(T);
57 }
58 return Erased;
59}
60
61void MachineValueTypeSet::writeToStream(raw_ostream &OS) const {
62 SmallVector<MVT, 4> Types(begin(), end());
63 array_pod_sort(Start: Types.begin(), End: Types.end());
64
65 OS << '[';
66 ListSeparator LS(" ");
67 for (const MVT &T : Types)
68 OS << LS << ValueTypeByHwMode::getMVTName(T);
69 OS << ']';
70}
71
72// --- TypeSetByHwMode
73
74// This is a parameterized type-set class. For each mode there is a list
75// of types that are currently possible for a given tree node. Type
76// inference will apply to each mode separately.
77
78TypeSetByHwMode::TypeSetByHwMode(ArrayRef<ValueTypeByHwMode> VTList) {
79 // Take the address space from the first type in the list.
80 if (!VTList.empty())
81 PtrAddrSpace = VTList[0].PtrAddrSpace;
82
83 for (const ValueTypeByHwMode &VVT : VTList)
84 insert(VVT);
85}
86
87bool TypeSetByHwMode::isValueTypeByHwMode(bool AllowEmpty) const {
88 for (const auto &I : *this) {
89 if (I.second.size() > 1)
90 return false;
91 if (!AllowEmpty && I.second.empty())
92 return false;
93 }
94 return true;
95}
96
97ValueTypeByHwMode TypeSetByHwMode::getValueTypeByHwMode(bool SkipEmpty) const {
98 assert(isValueTypeByHwMode(true) &&
99 "The type set has multiple types for at least one HW mode");
100 ValueTypeByHwMode VVT;
101 VVT.PtrAddrSpace = PtrAddrSpace;
102
103 for (const auto &I : *this) {
104 if (SkipEmpty && I.second.empty())
105 continue;
106 MVT T = I.second.empty() ? MVT::Other : *I.second.begin();
107 VVT.insertTypeForMode(Mode: I.first, Type: T);
108 }
109 return VVT;
110}
111
112bool TypeSetByHwMode::isPossible() const {
113 for (const auto &I : *this)
114 if (!I.second.empty())
115 return true;
116 return false;
117}
118
119bool TypeSetByHwMode::insert(const ValueTypeByHwMode &VVT) {
120 bool Changed = false;
121 bool ContainsDefault = false;
122 MVT DT = MVT::Other;
123
124 for (const auto &P : VVT) {
125 unsigned M = P.first;
126 // Make sure there exists a set for each specific mode from VVT.
127 Changed |= getOrCreate(Mode: M).insert(T: P.second).second;
128 // Cache VVT's default mode.
129 if (DefaultMode == M) {
130 ContainsDefault = true;
131 DT = P.second;
132 }
133 }
134
135 // If VVT has a default mode, add the corresponding type to all
136 // modes in "this" that do not exist in VVT.
137 if (ContainsDefault)
138 for (auto &I : *this)
139 if (!VVT.hasMode(M: I.first))
140 Changed |= I.second.insert(T: DT).second;
141
142 return Changed;
143}
144
145// Constrain the type set to be the intersection with VTS.
146bool TypeSetByHwMode::constrain(const TypeSetByHwMode &VTS) {
147 bool Changed = false;
148 if (hasDefault()) {
149 for (const auto &I : VTS) {
150 unsigned M = I.first;
151 if (M == DefaultMode || hasMode(M))
152 continue;
153 Map.try_emplace(k: M, args&: Map.at(k: DefaultMode));
154 Changed = true;
155 }
156 }
157
158 for (auto &I : *this) {
159 unsigned M = I.first;
160 SetType &S = I.second;
161 if (VTS.hasMode(M) || VTS.hasDefault()) {
162 Changed |= intersect(Out&: I.second, In: VTS.get(Mode: M));
163 } else if (!S.empty()) {
164 S.clear();
165 Changed = true;
166 }
167 }
168 return Changed;
169}
170
171template <typename Predicate> bool TypeSetByHwMode::constrain(Predicate P) {
172 bool Changed = false;
173 for (auto &I : *this)
174 Changed |= berase_if(I.second, [&P](MVT VT) { return !P(VT); });
175 return Changed;
176}
177
178template <typename Predicate>
179bool TypeSetByHwMode::assign_if(const TypeSetByHwMode &VTS, Predicate P) {
180 assert(empty());
181 for (const auto &I : VTS) {
182 SetType &S = getOrCreate(Mode: I.first);
183 for (auto J : I.second)
184 if (P(J))
185 S.insert(T: J);
186 }
187 return !empty();
188}
189
190void TypeSetByHwMode::writeToStream(raw_ostream &OS) const {
191 if (Map.empty()) {
192 OS << "{}";
193 return;
194 }
195 OS << '{';
196 for (const auto &[Mode, Types] : Map) {
197 OS << ' ' << getModeName(Mode) << ':';
198 Types.writeToStream(OS);
199 }
200 OS << " }";
201}
202
203bool TypeSetByHwMode::operator==(const TypeSetByHwMode &VTS) const {
204 // The isSimple call is much quicker than hasDefault - check this first.
205 bool IsSimple = isSimple();
206 bool VTSIsSimple = VTS.isSimple();
207 if (IsSimple && VTSIsSimple)
208 return getSimple() == VTS.getSimple();
209
210 // Speedup: We have a default if the set is simple.
211 bool HaveDefault = IsSimple || hasDefault();
212 bool VTSHaveDefault = VTSIsSimple || VTS.hasDefault();
213 if (HaveDefault != VTSHaveDefault)
214 return false;
215
216 SmallSet<unsigned, 4> Modes;
217 Modes.insert_range(R: llvm::make_first_range(c: *this));
218 Modes.insert_range(R: llvm::make_first_range(c: VTS));
219
220 if (HaveDefault) {
221 // Both sets have default mode.
222 for (unsigned M : Modes) {
223 if (get(Mode: M) != VTS.get(Mode: M))
224 return false;
225 }
226 } else {
227 // Neither set has default mode.
228 for (unsigned M : Modes) {
229 // If there is no default mode, an empty set is equivalent to not having
230 // the corresponding mode.
231 bool NoModeThis = !hasMode(M) || get(Mode: M).empty();
232 bool NoModeVTS = !VTS.hasMode(M) || VTS.get(Mode: M).empty();
233 if (NoModeThis != NoModeVTS)
234 return false;
235 if (!NoModeThis)
236 if (get(Mode: M) != VTS.get(Mode: M))
237 return false;
238 }
239 }
240
241 return true;
242}
243
244raw_ostream &llvm::operator<<(raw_ostream &OS, const MachineValueTypeSet &T) {
245 T.writeToStream(OS);
246 return OS;
247}
248raw_ostream &llvm::operator<<(raw_ostream &OS, const TypeSetByHwMode &T) {
249 T.writeToStream(OS);
250 return OS;
251}
252
253LLVM_DUMP_METHOD
254void TypeSetByHwMode::dump() const { dbgs() << *this << '\n'; }
255
256bool TypeSetByHwMode::intersect(SetType &Out, const SetType &In) {
257 auto IntersectP = [&](std::optional<MVT> WildVT, function_ref<bool(MVT)> P) {
258 // Complement of In within this partition.
259 auto CompIn = [&](MVT T) -> bool { return !In.count(T) && P(T); };
260
261 if (!WildVT)
262 return berase_if(S&: Out, P: CompIn);
263
264 bool OutW = Out.count(T: *WildVT), InW = In.count(T: *WildVT);
265 if (OutW == InW)
266 return berase_if(S&: Out, P: CompIn);
267
268 // Compute the intersection of scalars separately to account for only one
269 // set containing WildVT.
270 // The intersection of WildVT with a set of corresponding types that does
271 // not include WildVT will result in the most specific type:
272 // - WildVT is more specific than any set with two elements or more
273 // - WildVT is less specific than any single type.
274 // For example, for iPTR and scalar integer types
275 // { iPTR } * { i32 } -> { i32 }
276 // { iPTR } * { i32 i64 } -> { iPTR }
277 // and
278 // { iPTR i32 } * { i32 } -> { i32 }
279 // { iPTR i32 } * { i32 i64 } -> { i32 i64 }
280 // { iPTR i32 } * { i32 i64 i128 } -> { iPTR i32 }
281
282 // Looking at just this partition, let In' = elements only in In,
283 // Out' = elements only in Out, and IO = elements common to both. Normally
284 // IO would be returned as the result of the intersection, but we need to
285 // account for WildVT being a "wildcard" of sorts. Since elements in IO are
286 // those that match both sets exactly, they will all belong to the output.
287 // If any of the "leftovers" (i.e. In' or Out') contain WildVT, it means
288 // that the other set doesn't have it, but it could have (1) a more
289 // specific type, or (2) a set of types that is less specific. The
290 // "leftovers" from the other set is what we want to examine more closely.
291
292 auto Leftovers = [&](const SetType &A, const SetType &B) {
293 SetType Diff = A;
294 berase_if(S&: Diff, P: [&](MVT T) { return B.count(T) || !P(T); });
295 return Diff;
296 };
297
298 if (InW) {
299 SetType OutLeftovers = Leftovers(Out, In);
300 if (OutLeftovers.size() < 2) {
301 // WildVT not added to Out. Keep the possible single leftover.
302 return false;
303 }
304 // WildVT replaces the leftovers.
305 berase_if(S&: Out, P: CompIn);
306 Out.insert(T: *WildVT);
307 return true;
308 }
309
310 // OutW == true
311 SetType InLeftovers = Leftovers(In, Out);
312 unsigned SizeOut = Out.size();
313 berase_if(S&: Out, P: CompIn); // This will remove at least the WildVT.
314 if (InLeftovers.size() < 2) {
315 // WildVT deleted from Out. Add back the possible single leftover.
316 Out.insert(S: InLeftovers);
317 return true;
318 }
319
320 // Keep the WildVT in Out.
321 Out.insert(T: *WildVT);
322 // If WildVT was the only element initially removed from Out, then Out
323 // has not changed.
324 return SizeOut != Out.size();
325 };
326
327 // Note: must be non-overlapping
328 using WildPartT = std::pair<MVT, std::function<bool(MVT)>>;
329 static const WildPartT WildParts[] = {
330 {MVT::iPTR, [](MVT T) { return T.isScalarInteger() || T == MVT::iPTR; }},
331 {MVT::cPTR,
332 [](MVT T) { return T.isCheriCapability() || T == MVT::cPTR; }},
333 };
334
335 bool Changed = false;
336 for (const auto &I : WildParts)
337 Changed |= IntersectP(I.first, I.second);
338
339 Changed |= IntersectP(std::nullopt, [&](MVT T) {
340 return !any_of(Range: WildParts, P: [=](const WildPartT &I) { return I.second(T); });
341 });
342
343 return Changed;
344}
345
346bool TypeSetByHwMode::validate() const {
347 if (empty())
348 return true;
349 bool AllEmpty = true;
350 for (const auto &I : *this)
351 AllEmpty &= I.second.empty();
352 return !AllEmpty;
353}
354
355// --- TypeInfer
356
357bool TypeInfer::MergeInTypeInfo(TypeSetByHwMode &Out,
358 const TypeSetByHwMode &In) const {
359 ValidateOnExit _1(Out, *this);
360 In.validate();
361 if (In.empty() || Out == In || TP.hasError())
362 return false;
363 if (Out.empty()) {
364 Out = In;
365 return true;
366 }
367
368 bool Changed = Out.constrain(VTS: In);
369 if (Changed && Out.empty())
370 TP.error(Msg: "Type contradiction");
371
372 return Changed;
373}
374
375bool TypeInfer::forceArbitrary(TypeSetByHwMode &Out) {
376 ValidateOnExit _1(Out, *this);
377 if (TP.hasError())
378 return false;
379 assert(!Out.empty() && "cannot pick from an empty set");
380
381 bool Changed = false;
382 for (auto &I : Out) {
383 TypeSetByHwMode::SetType &S = I.second;
384 if (S.size() <= 1)
385 continue;
386 MVT T = *S.begin(); // Pick the first element.
387 S.clear();
388 S.insert(T);
389 Changed = true;
390 }
391 return Changed;
392}
393
394bool TypeInfer::EnforceInteger(TypeSetByHwMode &Out) {
395 ValidateOnExit _1(Out, *this);
396 if (TP.hasError())
397 return false;
398 if (!Out.empty())
399 return Out.constrain(P: isIntegerOrPtr);
400
401 return Out.assign_if(VTS: getLegalTypes(), P: isIntegerOrPtr);
402}
403
404bool TypeInfer::EnforceFloatingPoint(TypeSetByHwMode &Out) {
405 ValidateOnExit _1(Out, *this);
406 if (TP.hasError())
407 return false;
408 if (!Out.empty())
409 return Out.constrain(P: isFloatingPoint);
410
411 return Out.assign_if(VTS: getLegalTypes(), P: isFloatingPoint);
412}
413
414bool TypeInfer::EnforceScalar(TypeSetByHwMode &Out) {
415 ValidateOnExit _1(Out, *this);
416 if (TP.hasError())
417 return false;
418 if (!Out.empty())
419 return Out.constrain(P: isScalar);
420
421 return Out.assign_if(VTS: getLegalTypes(), P: isScalar);
422}
423
424bool TypeInfer::EnforceVector(TypeSetByHwMode &Out) {
425 ValidateOnExit _1(Out, *this);
426 if (TP.hasError())
427 return false;
428 if (!Out.empty())
429 return Out.constrain(P: isVector);
430
431 return Out.assign_if(VTS: getLegalTypes(), P: isVector);
432}
433
434bool TypeInfer::EnforceAny(TypeSetByHwMode &Out) {
435 ValidateOnExit _1(Out, *this);
436 if (TP.hasError() || !Out.empty())
437 return false;
438
439 Out = getLegalTypes();
440 return true;
441}
442
443template <typename Iter, typename Pred, typename Less>
444static Iter min_if(Iter B, Iter E, Pred P, Less L) {
445 if (B == E)
446 return E;
447 Iter Min = E;
448 for (Iter I = B; I != E; ++I) {
449 if (!P(*I))
450 continue;
451 if (Min == E || L(*I, *Min))
452 Min = I;
453 }
454 return Min;
455}
456
457template <typename Iter, typename Pred, typename Less>
458static Iter max_if(Iter B, Iter E, Pred P, Less L) {
459 if (B == E)
460 return E;
461 Iter Max = E;
462 for (Iter I = B; I != E; ++I) {
463 if (!P(*I))
464 continue;
465 if (Max == E || L(*Max, *I))
466 Max = I;
467 }
468 return Max;
469}
470
471/// Make sure that for each type in Small, there exists a larger type in Big.
472bool TypeInfer::EnforceSmallerThan(TypeSetByHwMode &Small, TypeSetByHwMode &Big,
473 bool SmallIsVT) {
474 ValidateOnExit _1(Small, *this), _2(Big, *this);
475 if (TP.hasError())
476 return false;
477 bool Changed = false;
478
479 assert((!SmallIsVT || !Small.empty()) &&
480 "Small should not be empty for SDTCisVTSmallerThanOp");
481
482 if (Small.empty())
483 Changed |= EnforceAny(Out&: Small);
484 if (Big.empty())
485 Changed |= EnforceAny(Out&: Big);
486
487 assert(Small.hasDefault() && Big.hasDefault());
488
489 SmallVector<unsigned, 4> Modes;
490 union_modes(A: Small, B: Big, Modes);
491
492 // 1. Only allow integer or floating point types and make sure that
493 // both sides are both integer or both floating point.
494 // 2. Make sure that either both sides have vector types, or neither
495 // of them does.
496 for (unsigned M : Modes) {
497 TypeSetByHwMode::SetType &S = Small.get(Mode: M);
498 TypeSetByHwMode::SetType &B = Big.get(Mode: M);
499
500 assert((!SmallIsVT || !S.empty()) && "Expected non-empty type");
501
502 if (any_of(Range&: S, P: isIntegerOrPtr) && any_of(Range&: B, P: isIntegerOrPtr)) {
503 auto NotInt = [](MVT VT) { return !isIntegerOrPtr(VT); };
504 Changed |= berase_if(S, P: NotInt);
505 Changed |= berase_if(S&: B, P: NotInt);
506 } else if (any_of(Range&: S, P: isFloatingPoint) && any_of(Range&: B, P: isFloatingPoint)) {
507 auto NotFP = [](MVT VT) { return !isFloatingPoint(VT); };
508 Changed |= berase_if(S, P: NotFP);
509 Changed |= berase_if(S&: B, P: NotFP);
510 } else if (SmallIsVT && B.empty()) {
511 // B is empty and since S is a specific VT, it will never be empty. Don't
512 // report this as a change, just clear S and continue. This prevents an
513 // infinite loop.
514 S.clear();
515 } else if (S.empty() || B.empty()) {
516 Changed = !S.empty() || !B.empty();
517 S.clear();
518 B.clear();
519 } else {
520 TP.error(Msg: "Incompatible types");
521 return Changed;
522 }
523
524 if (none_of(Range&: S, P: isVector) || none_of(Range&: B, P: isVector)) {
525 Changed |= berase_if(S, P: isVector);
526 Changed |= berase_if(S&: B, P: isVector);
527 }
528 }
529
530 auto LT = [](MVT A, MVT B) -> bool {
531 // Always treat non-scalable MVTs as smaller than scalable MVTs for the
532 // purposes of ordering.
533 auto ASize = std::tuple(A.isScalableVector(), A.getScalarSizeInBits(),
534 A.getSizeInBits().getKnownMinValue());
535 auto BSize = std::tuple(B.isScalableVector(), B.getScalarSizeInBits(),
536 B.getSizeInBits().getKnownMinValue());
537 return ASize < BSize;
538 };
539 auto SameKindLE = [](MVT A, MVT B) -> bool {
540 // This function is used when removing elements: when a vector is compared
541 // to a non-vector or a scalable vector to any non-scalable MVT, it should
542 // return false (to avoid removal).
543 if (std::tuple(A.isVector(), A.isScalableVector()) !=
544 std::tuple(B.isVector(), B.isScalableVector()))
545 return false;
546
547 return std::tuple(A.getScalarSizeInBits(),
548 A.getSizeInBits().getKnownMinValue()) <=
549 std::tuple(B.getScalarSizeInBits(),
550 B.getSizeInBits().getKnownMinValue());
551 };
552
553 for (unsigned M : Modes) {
554 TypeSetByHwMode::SetType &S = Small.get(Mode: M);
555 TypeSetByHwMode::SetType &B = Big.get(Mode: M);
556 // MinS = min scalar in Small, remove all scalars from Big that are
557 // smaller-or-equal than MinS.
558 auto MinS = min_if(B: S.begin(), E: S.end(), P: isScalar, L: LT);
559 if (MinS != S.end())
560 Changed |=
561 berase_if(S&: B, P: std::bind(f&: SameKindLE, args: std::placeholders::_1, args: *MinS));
562
563 // MaxS = max scalar in Big, remove all scalars from Small that are
564 // larger than MaxS.
565 auto MaxS = max_if(B: B.begin(), E: B.end(), P: isScalar, L: LT);
566 if (MaxS != B.end())
567 Changed |=
568 berase_if(S, P: std::bind(f&: SameKindLE, args: *MaxS, args: std::placeholders::_1));
569
570 // MinV = min vector in Small, remove all vectors from Big that are
571 // smaller-or-equal than MinV.
572 auto MinV = min_if(B: S.begin(), E: S.end(), P: isVector, L: LT);
573 if (MinV != S.end())
574 Changed |=
575 berase_if(S&: B, P: std::bind(f&: SameKindLE, args: std::placeholders::_1, args: *MinV));
576
577 // MaxV = max vector in Big, remove all vectors from Small that are
578 // larger than MaxV.
579 auto MaxV = max_if(B: B.begin(), E: B.end(), P: isVector, L: LT);
580 if (MaxV != B.end())
581 Changed |=
582 berase_if(S, P: std::bind(f&: SameKindLE, args: *MaxV, args: std::placeholders::_1));
583 }
584
585 return Changed;
586}
587
588/// 1. Ensure that for each type T in Vec, T is a vector type, and that
589/// for each type U in Elem, U is a scalar type.
590/// 2. Ensure that for each (scalar) type U in Elem, there exists a (vector)
591/// type T in Vec, such that U is the element type of T.
592bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
593 TypeSetByHwMode &Elem) {
594 ValidateOnExit _1(Vec, *this), _2(Elem, *this);
595 if (TP.hasError())
596 return false;
597 bool Changed = false;
598
599 if (Vec.empty())
600 Changed |= EnforceVector(Out&: Vec);
601 if (Elem.empty())
602 Changed |= EnforceScalar(Out&: Elem);
603
604 SmallVector<unsigned, 4> Modes;
605 union_modes(A: Vec, B: Elem, Modes);
606 for (unsigned M : Modes) {
607 TypeSetByHwMode::SetType &V = Vec.get(Mode: M);
608 TypeSetByHwMode::SetType &E = Elem.get(Mode: M);
609
610 Changed |= berase_if(S&: V, P: isScalar); // Scalar = !vector
611 Changed |= berase_if(S&: E, P: isVector); // Vector = !scalar
612 assert(!V.empty() && !E.empty());
613
614 MachineValueTypeSet VT, ST;
615 // Collect element types from the "vector" set.
616 for (MVT T : V)
617 VT.insert(T: T.getVectorElementType());
618 // Collect scalar types from the "element" set.
619 for (MVT T : E)
620 ST.insert(T);
621
622 // Remove from V all (vector) types whose element type is not in S.
623 Changed |= berase_if(S&: V, P: [&ST](MVT T) -> bool {
624 return !ST.count(T: T.getVectorElementType());
625 });
626 // Remove from E all (scalar) types, for which there is no corresponding
627 // type in V.
628 Changed |= berase_if(S&: E, P: [&VT](MVT T) -> bool { return !VT.count(T); });
629 }
630
631 return Changed;
632}
633
634bool TypeInfer::EnforceVectorEltTypeIs(TypeSetByHwMode &Vec,
635 const ValueTypeByHwMode &VVT) {
636 TypeSetByHwMode Tmp(VVT);
637 ValidateOnExit _1(Vec, *this), _2(Tmp, *this);
638 return EnforceVectorEltTypeIs(Vec, Elem&: Tmp);
639}
640
641/// Ensure that for each type T in Sub, T is a vector type, and there
642/// exists a type U in Vec such that U is a vector type with the same
643/// element type as T and at least as many elements as T.
644bool TypeInfer::EnforceVectorSubVectorTypeIs(TypeSetByHwMode &Vec,
645 TypeSetByHwMode &Sub) {
646 ValidateOnExit _1(Vec, *this), _2(Sub, *this);
647 if (TP.hasError())
648 return false;
649
650 /// Return true if B is a suB-vector of P, i.e. P is a suPer-vector of B.
651 auto IsSubVec = [](MVT B, MVT P) -> bool {
652 if (!B.isVector() || !P.isVector())
653 return false;
654 // You cannot extract a scalable vector from a fixed length vector.
655 // You cannot insert a scalable vector into a fixed length vector.
656 if (B.isScalableVector() && !P.isScalableVector())
657 return false;
658 if (B.getVectorElementType() != P.getVectorElementType())
659 return false;
660 return B.getVectorMinNumElements() < P.getVectorMinNumElements();
661 };
662
663 /// Return true if S has no element (vector type) that T is a sub-vector of,
664 /// i.e. has the same element type as T and more elements.
665 auto NoSubV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
666 for (auto I : S)
667 if (IsSubVec(T, I))
668 return false;
669 return true;
670 };
671
672 /// Return true if S has no element (vector type) that T is a super-vector
673 /// of, i.e. has the same element type as T and fewer elements.
674 auto NoSupV = [&IsSubVec](const TypeSetByHwMode::SetType &S, MVT T) -> bool {
675 for (auto I : S)
676 if (IsSubVec(I, T))
677 return false;
678 return true;
679 };
680
681 bool Changed = false;
682
683 if (Vec.empty())
684 Changed |= EnforceVector(Out&: Vec);
685 if (Sub.empty())
686 Changed |= EnforceVector(Out&: Sub);
687
688 SmallVector<unsigned, 4> Modes;
689 union_modes(A: Vec, B: Sub, Modes);
690 for (unsigned M : Modes) {
691 TypeSetByHwMode::SetType &S = Sub.get(Mode: M);
692 TypeSetByHwMode::SetType &V = Vec.get(Mode: M);
693
694 Changed |= berase_if(S, P: isScalar);
695
696 // Erase all types from S that are not sub-vectors of a type in V.
697 Changed |= berase_if(S, P: std::bind(f&: NoSubV, args&: V, args: std::placeholders::_1));
698
699 // Erase all types from V that are not super-vectors of a type in S.
700 Changed |= berase_if(S&: V, P: std::bind(f&: NoSupV, args&: S, args: std::placeholders::_1));
701 }
702
703 return Changed;
704}
705
706/// 1. Ensure that V has a scalar type iff W has a scalar type.
707/// 2. Ensure that for each vector type T in V, there exists a vector
708/// type U in W, such that T and U have the same number of elements.
709/// 3. Ensure that for each vector type U in W, there exists a vector
710/// type T in V, such that T and U have the same number of elements
711/// (reverse of 2).
712bool TypeInfer::EnforceSameNumElts(TypeSetByHwMode &V, TypeSetByHwMode &W) {
713 ValidateOnExit _1(V, *this), _2(W, *this);
714 if (TP.hasError())
715 return false;
716
717 bool Changed = false;
718 if (V.empty())
719 Changed |= EnforceAny(Out&: V);
720 if (W.empty())
721 Changed |= EnforceAny(Out&: W);
722
723 // An actual vector type cannot have 0 elements, so we can treat scalars
724 // as zero-length vectors. This way both vectors and scalars can be
725 // processed identically.
726 auto NoLength = [](const SmallDenseSet<ElementCount> &Lengths,
727 MVT T) -> bool {
728 return !Lengths.contains(V: T.isVector() ? T.getVectorElementCount()
729 : ElementCount());
730 };
731
732 SmallVector<unsigned, 4> Modes;
733 union_modes(A: V, B: W, Modes);
734 for (unsigned M : Modes) {
735 TypeSetByHwMode::SetType &VS = V.get(Mode: M);
736 TypeSetByHwMode::SetType &WS = W.get(Mode: M);
737
738 SmallDenseSet<ElementCount> VN, WN;
739 for (MVT T : VS)
740 VN.insert(V: T.isVector() ? T.getVectorElementCount() : ElementCount());
741 for (MVT T : WS)
742 WN.insert(V: T.isVector() ? T.getVectorElementCount() : ElementCount());
743
744 Changed |= berase_if(S&: VS, P: std::bind(f&: NoLength, args&: WN, args: std::placeholders::_1));
745 Changed |= berase_if(S&: WS, P: std::bind(f&: NoLength, args&: VN, args: std::placeholders::_1));
746 }
747 return Changed;
748}
749
750namespace {
751struct TypeSizeComparator {
752 bool operator()(const TypeSize &LHS, const TypeSize &RHS) const {
753 return std::tuple(LHS.isScalable(), LHS.getKnownMinValue()) <
754 std::tuple(RHS.isScalable(), RHS.getKnownMinValue());
755 }
756};
757} // end anonymous namespace
758
759/// 1. Ensure that for each type T in A, there exists a type U in B,
760/// such that T and U have equal size in bits.
761/// 2. Ensure that for each type U in B, there exists a type T in A
762/// such that T and U have equal size in bits (reverse of 1).
763bool TypeInfer::EnforceSameSize(TypeSetByHwMode &A, TypeSetByHwMode &B) {
764 ValidateOnExit _1(A, *this), _2(B, *this);
765 if (TP.hasError())
766 return false;
767 bool Changed = false;
768 if (A.empty())
769 Changed |= EnforceAny(Out&: A);
770 if (B.empty())
771 Changed |= EnforceAny(Out&: B);
772
773 using TypeSizeSet = SmallSet<TypeSize, 2, TypeSizeComparator>;
774
775 auto NoSize = [](const TypeSizeSet &Sizes, MVT T) -> bool {
776 return !Sizes.contains(V: T.getSizeInBits());
777 };
778
779 SmallVector<unsigned, 4> Modes;
780 union_modes(A, B, Modes);
781 for (unsigned M : Modes) {
782 TypeSetByHwMode::SetType &AS = A.get(Mode: M);
783 TypeSetByHwMode::SetType &BS = B.get(Mode: M);
784 TypeSizeSet AN, BN;
785
786 for (MVT T : AS)
787 AN.insert(V: T.getSizeInBits());
788 for (MVT T : BS)
789 BN.insert(V: T.getSizeInBits());
790
791 Changed |= berase_if(S&: AS, P: std::bind(f&: NoSize, args&: BN, args: std::placeholders::_1));
792 Changed |= berase_if(S&: BS, P: std::bind(f&: NoSize, args&: AN, args: std::placeholders::_1));
793 }
794
795 return Changed;
796}
797
798void TypeInfer::expandOverloads(TypeSetByHwMode &VTS) const {
799 ValidateOnExit _1(VTS, *this);
800 const TypeSetByHwMode &Legal = getLegalTypes();
801 assert(Legal.isSimple() && "Default-mode only expected");
802 const TypeSetByHwMode::SetType &LegalTypes = Legal.getSimple();
803
804 for (auto &I : VTS)
805 expandOverloads(Out&: I.second, Legal: LegalTypes);
806}
807
808void TypeInfer::expandOverloads(TypeSetByHwMode::SetType &Out,
809 const TypeSetByHwMode::SetType &Legal) const {
810 if (Out.count(T: MVT::pAny)) {
811 Out.erase(T: MVT::pAny);
812 Out.insert(T: MVT::iPTR);
813 for (MVT T : MVT::cheri_capability_valuetypes()) {
814 if (Legal.count(T))
815 Out.insert(T: MVT::cPTR);
816 }
817 } else if (Out.count(T: MVT::iAny)) {
818 Out.erase(T: MVT::iAny);
819 for (MVT T : MVT::integer_valuetypes())
820 if (Legal.count(T))
821 Out.insert(T);
822 for (MVT T : MVT::integer_fixedlen_vector_valuetypes())
823 if (Legal.count(T))
824 Out.insert(T);
825 for (MVT T : MVT::integer_scalable_vector_valuetypes())
826 if (Legal.count(T))
827 Out.insert(T);
828 } else if (Out.count(T: MVT::fAny)) {
829 Out.erase(T: MVT::fAny);
830 for (MVT T : MVT::fp_valuetypes())
831 if (Legal.count(T))
832 Out.insert(T);
833 for (MVT T : MVT::fp_fixedlen_vector_valuetypes())
834 if (Legal.count(T))
835 Out.insert(T);
836 for (MVT T : MVT::fp_scalable_vector_valuetypes())
837 if (Legal.count(T))
838 Out.insert(T);
839 } else if (Out.count(T: MVT::vAny)) {
840 Out.erase(T: MVT::vAny);
841 for (MVT T : MVT::vector_valuetypes())
842 if (Legal.count(T))
843 Out.insert(T);
844 } else if (Out.count(T: MVT::Any)) {
845 Out.erase(T: MVT::Any);
846 for (MVT T : MVT::all_valuetypes())
847 if (Legal.count(T))
848 Out.insert(T);
849 }
850}
851
852const TypeSetByHwMode &TypeInfer::getLegalTypes() const {
853 if (!LegalTypesCached) {
854 TypeSetByHwMode::SetType &LegalTypes = LegalCache.getOrCreate(Mode: DefaultMode);
855 // Stuff all types from all modes into the default mode.
856 const TypeSetByHwMode &LTS = TP.getDAGPatterns().getLegalTypes();
857 for (const auto &I : LTS)
858 LegalTypes.insert(S: I.second);
859 LegalTypesCached = true;
860 }
861 assert(LegalCache.isSimple() && "Default-mode only expected");
862 return LegalCache;
863}
864
865TypeInfer::ValidateOnExit::~ValidateOnExit() {
866 if (Infer.Validate && !VTS.validate()) {
867#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
868 errs() << "Type set is empty for each HW mode:\n"
869 "possible type contradiction in the pattern below "
870 "(use -print-records with llvm-tblgen to see all "
871 "expanded records).\n";
872 Infer.TP.dump();
873 errs() << "Generated from record:\n";
874 Infer.TP.getRecord()->dump();
875#endif
876 PrintFatalError(ErrorLoc: Infer.TP.getRecord()->getLoc(),
877 Msg: "Type set is empty for each HW mode in '" +
878 Infer.TP.getRecord()->getName() + "'");
879 }
880}
881
882//===----------------------------------------------------------------------===//
883// ScopedName Implementation
884//===----------------------------------------------------------------------===//
885
886bool ScopedName::operator==(const ScopedName &o) const {
887 return Scope == o.Scope && Identifier == o.Identifier;
888}
889
890bool ScopedName::operator!=(const ScopedName &o) const { return !(*this == o); }
891
892//===----------------------------------------------------------------------===//
893// TreePredicateFn Implementation
894//===----------------------------------------------------------------------===//
895
896/// TreePredicateFn constructor. Here 'N' is a subclass of PatFrag.
897TreePredicateFn::TreePredicateFn(TreePattern *N) : PatFragRec(N) {
898 assert(
899 (!hasPredCode() || !hasImmCode()) &&
900 ".td file corrupt: can't have a node predicate *and* an imm predicate");
901
902 if (hasGISelPredicateCode() && hasGISelLeafPredicateCode())
903 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
904 Msg: ".td file corrupt: can't have GISelPredicateCode *and* "
905 "GISelLeafPredicateCode");
906}
907
908bool TreePredicateFn::hasPredCode() const {
909 return isLoad() || isStore() || isAtomic() || hasNoUse() || hasOneUse() ||
910 !PatFragRec->getRecord()->getValueAsString(FieldName: "PredicateCode").empty();
911}
912
913std::string TreePredicateFn::getPredCode() const {
914 std::string Code;
915
916 if (!isLoad() && !isStore() && !isAtomic() && getMemoryVT())
917 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
918 Msg: "MemoryVT requires IsLoad or IsStore or IsAtomic");
919
920 if (!isLoad() && !isStore()) {
921 if (isUnindexed())
922 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
923 Msg: "IsUnindexed requires IsLoad or IsStore");
924
925 if (getScalarMemoryVT())
926 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
927 Msg: "ScalarMemoryVT requires IsLoad or IsStore");
928 }
929
930 if (isLoad() + isStore() + isAtomic() > 1)
931 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
932 Msg: "IsLoad, IsStore, and IsAtomic are mutually exclusive");
933
934 if (isLoad()) {
935 if (!isUnindexed() && !isNonExtLoad() && !isAnyExtLoad() &&
936 !isSignExtLoad() && !isZeroExtLoad() && getMemoryVT() == nullptr &&
937 getScalarMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
938 getMinAlignment() < 1)
939 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
940 Msg: "IsLoad cannot be used by itself");
941 } else if (!isAtomic()) {
942 if (isNonExtLoad())
943 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
944 Msg: "IsNonExtLoad requires IsLoad or IsAtomic");
945 if (isAnyExtLoad())
946 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
947 Msg: "IsAnyExtLoad requires IsLoad or IsAtomic");
948 if (isSignExtLoad())
949 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
950 Msg: "IsSignExtLoad requires IsLoad or IsAtomic");
951 if (isZeroExtLoad())
952 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
953 Msg: "IsZeroExtLoad requires IsLoad or IsAtomic");
954 }
955
956 if (isStore()) {
957 if (!isUnindexed() && !isTruncStore() && !isNonTruncStore() &&
958 getMemoryVT() == nullptr && getScalarMemoryVT() == nullptr &&
959 getAddressSpaces() == nullptr && getMinAlignment() < 1)
960 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
961 Msg: "IsStore cannot be used by itself");
962 } else {
963 if (isNonTruncStore())
964 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
965 Msg: "IsNonTruncStore requires IsStore");
966 if (isTruncStore())
967 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
968 Msg: "IsTruncStore requires IsStore");
969 }
970
971 if (isAtomic()) {
972 if (getMemoryVT() == nullptr && getAddressSpaces() == nullptr &&
973 // FIXME: Should atomic loads be IsLoad, IsAtomic, or both?
974 !isNonExtLoad() && !isAnyExtLoad() && !isZeroExtLoad() &&
975 !isSignExtLoad() && !isAtomicOrderingMonotonic() &&
976 !isAtomicOrderingAcquire() && !isAtomicOrderingRelease() &&
977 !isAtomicOrderingAcquireRelease() &&
978 !isAtomicOrderingSequentiallyConsistent() &&
979 !isAtomicOrderingAcquireOrStronger() &&
980 !isAtomicOrderingReleaseOrStronger() &&
981 !isAtomicOrderingWeakerThanAcquire() &&
982 !isAtomicOrderingWeakerThanRelease())
983 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
984 Msg: "IsAtomic cannot be used by itself");
985 } else {
986 if (isAtomicOrderingMonotonic())
987 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
988 Msg: "IsAtomicOrderingMonotonic requires IsAtomic");
989 if (isAtomicOrderingAcquire())
990 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
991 Msg: "IsAtomicOrderingAcquire requires IsAtomic");
992 if (isAtomicOrderingRelease())
993 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
994 Msg: "IsAtomicOrderingRelease requires IsAtomic");
995 if (isAtomicOrderingAcquireRelease())
996 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
997 Msg: "IsAtomicOrderingAcquireRelease requires IsAtomic");
998 if (isAtomicOrderingSequentiallyConsistent())
999 PrintFatalError(
1000 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1001 Msg: "IsAtomicOrderingSequentiallyConsistent requires IsAtomic");
1002 if (isAtomicOrderingAcquireOrStronger())
1003 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1004 Msg: "IsAtomicOrderingAcquireOrStronger requires IsAtomic");
1005 if (isAtomicOrderingReleaseOrStronger())
1006 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1007 Msg: "IsAtomicOrderingReleaseOrStronger requires IsAtomic");
1008 if (isAtomicOrderingWeakerThanAcquire())
1009 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1010 Msg: "IsAtomicOrderingWeakerThanAcquire requires IsAtomic");
1011 }
1012
1013 if (isLoad() || isStore() || isAtomic()) {
1014 if (const ListInit *AddressSpaces = getAddressSpaces()) {
1015 Code += "unsigned AddrSpace = cast<MemSDNode>(N)->getAddressSpace();\n"
1016 " if (";
1017
1018 ListSeparator LS(" && ");
1019 for (const Init *Val : AddressSpaces->getElements()) {
1020 Code += LS;
1021
1022 const IntInit *IntVal = dyn_cast<IntInit>(Val);
1023 if (!IntVal) {
1024 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1025 Msg: "AddressSpaces element must be integer");
1026 }
1027
1028 Code += "AddrSpace != " + utostr(X: IntVal->getValue());
1029 }
1030
1031 Code += ")\nreturn false;\n";
1032 }
1033
1034 int64_t MinAlign = getMinAlignment();
1035 if (MinAlign > 0) {
1036 Code += "if (cast<MemSDNode>(N)->getAlign() < Align(";
1037 Code += utostr(X: MinAlign);
1038 Code += "))\nreturn false;\n";
1039 }
1040
1041 if (const Record *MemoryVT = getMemoryVT())
1042 Code += ("if (cast<MemSDNode>(N)->getMemoryVT() != MVT::" +
1043 MemoryVT->getName() + ") return false;\n")
1044 .str();
1045 }
1046
1047 if (isAtomic() && isAtomicOrderingMonotonic())
1048 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1049 "AtomicOrdering::Monotonic) return false;\n";
1050 if (isAtomic() && isAtomicOrderingAcquire())
1051 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1052 "AtomicOrdering::Acquire) return false;\n";
1053 if (isAtomic() && isAtomicOrderingRelease())
1054 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1055 "AtomicOrdering::Release) return false;\n";
1056 if (isAtomic() && isAtomicOrderingAcquireRelease())
1057 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1058 "AtomicOrdering::AcquireRelease) return false;\n";
1059 if (isAtomic() && isAtomicOrderingSequentiallyConsistent())
1060 Code += "if (cast<AtomicSDNode>(N)->getMergedOrdering() != "
1061 "AtomicOrdering::SequentiallyConsistent) return false;\n";
1062
1063 if (isAtomic() && isAtomicOrderingAcquireOrStronger())
1064 Code +=
1065 "if (!isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1066 "return false;\n";
1067 if (isAtomic() && isAtomicOrderingWeakerThanAcquire())
1068 Code +=
1069 "if (isAcquireOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1070 "return false;\n";
1071
1072 if (isAtomic() && isAtomicOrderingReleaseOrStronger())
1073 Code +=
1074 "if (!isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1075 "return false;\n";
1076 if (isAtomic() && isAtomicOrderingWeakerThanRelease())
1077 Code +=
1078 "if (isReleaseOrStronger(cast<AtomicSDNode>(N)->getMergedOrdering())) "
1079 "return false;\n";
1080
1081 if (isAtomic()) {
1082 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() + isZeroExtLoad()) >
1083 1)
1084 PrintFatalError(
1085 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1086 Msg: "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and IsZeroExtLoad are "
1087 "mutually exclusive");
1088
1089 if (isNonExtLoad())
1090 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != "
1091 "ISD::NON_EXTLOAD) return false;\n";
1092 if (isAnyExtLoad())
1093 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1094 "return false;\n";
1095 if (isSignExtLoad())
1096 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1097 "return false;\n";
1098 if (isZeroExtLoad())
1099 Code += "if (cast<AtomicSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1100 "return false;\n";
1101 }
1102
1103 if (isLoad() || isStore()) {
1104 StringRef SDNodeName = isLoad() ? "LoadSDNode" : "StoreSDNode";
1105
1106 if (isUnindexed())
1107 Code += ("if (cast<" + SDNodeName +
1108 ">(N)->getAddressingMode() != ISD::UNINDEXED) "
1109 "return false;\n")
1110 .str();
1111
1112 if (isLoad()) {
1113 if ((isNonExtLoad() + isAnyExtLoad() + isSignExtLoad() +
1114 isZeroExtLoad()) > 1)
1115 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1116 Msg: "IsNonExtLoad, IsAnyExtLoad, IsSignExtLoad, and "
1117 "IsZeroExtLoad are mutually exclusive");
1118 if (isNonExtLoad())
1119 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != "
1120 "ISD::NON_EXTLOAD) return false;\n";
1121 if (isAnyExtLoad())
1122 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::EXTLOAD) "
1123 "return false;\n";
1124 if (isSignExtLoad())
1125 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::SEXTLOAD) "
1126 "return false;\n";
1127 if (isZeroExtLoad())
1128 Code += "if (cast<LoadSDNode>(N)->getExtensionType() != ISD::ZEXTLOAD) "
1129 "return false;\n";
1130 } else {
1131 if ((isNonTruncStore() + isTruncStore()) > 1)
1132 PrintFatalError(
1133 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1134 Msg: "IsNonTruncStore, and IsTruncStore are mutually exclusive");
1135 if (isNonTruncStore())
1136 Code +=
1137 " if (cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1138 if (isTruncStore())
1139 Code +=
1140 " if (!cast<StoreSDNode>(N)->isTruncatingStore()) return false;\n";
1141 }
1142
1143 if (const Record *ScalarMemoryVT = getScalarMemoryVT())
1144 Code += ("if (cast<" + SDNodeName +
1145 ">(N)->getMemoryVT().getScalarType() != MVT::" +
1146 ScalarMemoryVT->getName() + ") return false;\n")
1147 .str();
1148 }
1149
1150 if (hasNoUse())
1151 Code += "if (N->hasAnyUseOfValue(0)) return false;\n";
1152 if (hasOneUse())
1153 Code += "if (!N->hasNUsesOfValue(1, 0)) return false;\n";
1154
1155 std::string PredicateCode =
1156 PatFragRec->getRecord()->getValueAsString(FieldName: "PredicateCode").str();
1157
1158 Code += PredicateCode;
1159
1160 if (PredicateCode.empty() && !Code.empty())
1161 Code += "return true;\n";
1162
1163 return Code;
1164}
1165
1166bool TreePredicateFn::hasImmCode() const {
1167 return !PatFragRec->getRecord()->getValueAsString(FieldName: "ImmediateCode").empty();
1168}
1169
1170std::string TreePredicateFn::getImmCode() const {
1171 return PatFragRec->getRecord()->getValueAsString(FieldName: "ImmediateCode").str();
1172}
1173
1174bool TreePredicateFn::immCodeUsesAPInt() const {
1175 return getOrigPatFragRecord()->getRecord()->getValueAsBit(FieldName: "IsAPInt");
1176}
1177
1178bool TreePredicateFn::immCodeUsesAPFloat() const {
1179 bool Unset;
1180 // The return value will be false when IsAPFloat is unset.
1181 return getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(FieldName: "IsAPFloat",
1182 Unset);
1183}
1184
1185bool TreePredicateFn::isPredefinedPredicateEqualTo(StringRef Field,
1186 bool Value) const {
1187 bool Unset;
1188 bool Result =
1189 getOrigPatFragRecord()->getRecord()->getValueAsBitOrUnset(FieldName: Field, Unset);
1190 if (Unset)
1191 return false;
1192 return Result == Value;
1193}
1194bool TreePredicateFn::usesOperands() const {
1195 return isPredefinedPredicateEqualTo(Field: "PredicateCodeUsesOperands", Value: true);
1196}
1197bool TreePredicateFn::hasNoUse() const {
1198 return isPredefinedPredicateEqualTo(Field: "HasNoUse", Value: true);
1199}
1200bool TreePredicateFn::hasOneUse() const {
1201 return isPredefinedPredicateEqualTo(Field: "HasOneUse", Value: true);
1202}
1203bool TreePredicateFn::isLoad() const {
1204 return isPredefinedPredicateEqualTo(Field: "IsLoad", Value: true);
1205}
1206bool TreePredicateFn::isStore() const {
1207 return isPredefinedPredicateEqualTo(Field: "IsStore", Value: true);
1208}
1209bool TreePredicateFn::isAtomic() const {
1210 return isPredefinedPredicateEqualTo(Field: "IsAtomic", Value: true);
1211}
1212bool TreePredicateFn::isUnindexed() const {
1213 return isPredefinedPredicateEqualTo(Field: "IsUnindexed", Value: true);
1214}
1215bool TreePredicateFn::isNonExtLoad() const {
1216 return isPredefinedPredicateEqualTo(Field: "IsNonExtLoad", Value: true);
1217}
1218bool TreePredicateFn::isAnyExtLoad() const {
1219 return isPredefinedPredicateEqualTo(Field: "IsAnyExtLoad", Value: true);
1220}
1221bool TreePredicateFn::isSignExtLoad() const {
1222 return isPredefinedPredicateEqualTo(Field: "IsSignExtLoad", Value: true);
1223}
1224bool TreePredicateFn::isZeroExtLoad() const {
1225 return isPredefinedPredicateEqualTo(Field: "IsZeroExtLoad", Value: true);
1226}
1227bool TreePredicateFn::isNonTruncStore() const {
1228 return isPredefinedPredicateEqualTo(Field: "IsTruncStore", Value: false);
1229}
1230bool TreePredicateFn::isTruncStore() const {
1231 return isPredefinedPredicateEqualTo(Field: "IsTruncStore", Value: true);
1232}
1233bool TreePredicateFn::isAtomicOrderingMonotonic() const {
1234 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingMonotonic", Value: true);
1235}
1236bool TreePredicateFn::isAtomicOrderingAcquire() const {
1237 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquire", Value: true);
1238}
1239bool TreePredicateFn::isAtomicOrderingRelease() const {
1240 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingRelease", Value: true);
1241}
1242bool TreePredicateFn::isAtomicOrderingAcquireRelease() const {
1243 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquireRelease", Value: true);
1244}
1245bool TreePredicateFn::isAtomicOrderingSequentiallyConsistent() const {
1246 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingSequentiallyConsistent",
1247 Value: true);
1248}
1249bool TreePredicateFn::isAtomicOrderingAcquireOrStronger() const {
1250 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquireOrStronger",
1251 Value: true);
1252}
1253bool TreePredicateFn::isAtomicOrderingWeakerThanAcquire() const {
1254 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingAcquireOrStronger",
1255 Value: false);
1256}
1257bool TreePredicateFn::isAtomicOrderingReleaseOrStronger() const {
1258 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingReleaseOrStronger",
1259 Value: true);
1260}
1261bool TreePredicateFn::isAtomicOrderingWeakerThanRelease() const {
1262 return isPredefinedPredicateEqualTo(Field: "IsAtomicOrderingReleaseOrStronger",
1263 Value: false);
1264}
1265const Record *TreePredicateFn::getMemoryVT() const {
1266 const Record *R = getOrigPatFragRecord()->getRecord();
1267 if (R->isValueUnset(FieldName: "MemoryVT"))
1268 return nullptr;
1269 return R->getValueAsDef(FieldName: "MemoryVT");
1270}
1271
1272const ListInit *TreePredicateFn::getAddressSpaces() const {
1273 const Record *R = getOrigPatFragRecord()->getRecord();
1274 if (R->isValueUnset(FieldName: "AddressSpaces"))
1275 return nullptr;
1276 return R->getValueAsListInit(FieldName: "AddressSpaces");
1277}
1278
1279int64_t TreePredicateFn::getMinAlignment() const {
1280 const Record *R = getOrigPatFragRecord()->getRecord();
1281 if (R->isValueUnset(FieldName: "MinAlignment"))
1282 return 0;
1283 return R->getValueAsInt(FieldName: "MinAlignment");
1284}
1285
1286const Record *TreePredicateFn::getScalarMemoryVT() const {
1287 const Record *R = getOrigPatFragRecord()->getRecord();
1288 if (R->isValueUnset(FieldName: "ScalarMemoryVT"))
1289 return nullptr;
1290 return R->getValueAsDef(FieldName: "ScalarMemoryVT");
1291}
1292
1293bool TreePredicateFn::hasGISelPredicateCode() const {
1294 return !PatFragRec->getRecord()
1295 ->getValueAsString(FieldName: "GISelPredicateCode")
1296 .empty();
1297}
1298
1299std::string TreePredicateFn::getGISelPredicateCode() const {
1300 return PatFragRec->getRecord()->getValueAsString(FieldName: "GISelPredicateCode").str();
1301}
1302
1303bool TreePredicateFn::hasGISelLeafPredicateCode() const {
1304 return PatFragRec->getRecord()
1305 ->getValueAsOptionalString(FieldName: "GISelLeafPredicateCode")
1306 .has_value();
1307}
1308
1309std::string TreePredicateFn::getGISelLeafPredicateCode() const {
1310 return PatFragRec->getRecord()
1311 ->getValueAsOptionalString(FieldName: "GISelLeafPredicateCode")
1312 .value_or(u: StringRef())
1313 .str();
1314}
1315
1316StringRef TreePredicateFn::getImmType() const {
1317 if (immCodeUsesAPInt())
1318 return "const APInt &";
1319 if (immCodeUsesAPFloat())
1320 return "const APFloat &";
1321 return "int64_t";
1322}
1323
1324StringRef TreePredicateFn::getImmTypeIdentifier() const {
1325 if (immCodeUsesAPInt())
1326 return "APInt";
1327 if (immCodeUsesAPFloat())
1328 return "APFloat";
1329 return "I64";
1330}
1331
1332/// isAlwaysTrue - Return true if this is a noop predicate.
1333bool TreePredicateFn::isAlwaysTrue() const {
1334 return !hasPredCode() && !hasImmCode();
1335}
1336
1337/// Return the name to use in the generated code to reference this, this is
1338/// "Predicate_foo" if from a pattern fragment "foo".
1339std::string TreePredicateFn::getFnName() const {
1340 return "Predicate_" + PatFragRec->getRecord()->getName().str();
1341}
1342
1343/// getCodeToRunOnSDNode - Return the code for the function body that
1344/// evaluates this predicate. The argument is expected to be in "Node",
1345/// not N. This handles casting and conversion to a concrete node type as
1346/// appropriate.
1347std::string TreePredicateFn::getCodeToRunOnSDNode() const {
1348 // Handle immediate predicates first.
1349 std::string ImmCode = getImmCode();
1350 if (!ImmCode.empty()) {
1351 if (isLoad())
1352 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1353 Msg: "IsLoad cannot be used with ImmLeaf or its subclasses");
1354 if (isStore())
1355 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1356 Msg: "IsStore cannot be used with ImmLeaf or its subclasses");
1357 if (isUnindexed())
1358 PrintFatalError(
1359 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1360 Msg: "IsUnindexed cannot be used with ImmLeaf or its subclasses");
1361 if (isNonExtLoad())
1362 PrintFatalError(
1363 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1364 Msg: "IsNonExtLoad cannot be used with ImmLeaf or its subclasses");
1365 if (isAnyExtLoad())
1366 PrintFatalError(
1367 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1368 Msg: "IsAnyExtLoad cannot be used with ImmLeaf or its subclasses");
1369 if (isSignExtLoad())
1370 PrintFatalError(
1371 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1372 Msg: "IsSignExtLoad cannot be used with ImmLeaf or its subclasses");
1373 if (isZeroExtLoad())
1374 PrintFatalError(
1375 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1376 Msg: "IsZeroExtLoad cannot be used with ImmLeaf or its subclasses");
1377 if (isNonTruncStore())
1378 PrintFatalError(
1379 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1380 Msg: "IsNonTruncStore cannot be used with ImmLeaf or its subclasses");
1381 if (isTruncStore())
1382 PrintFatalError(
1383 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1384 Msg: "IsTruncStore cannot be used with ImmLeaf or its subclasses");
1385 if (getMemoryVT())
1386 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1387 Msg: "MemoryVT cannot be used with ImmLeaf or its subclasses");
1388 if (getScalarMemoryVT())
1389 PrintFatalError(
1390 ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1391 Msg: "ScalarMemoryVT cannot be used with ImmLeaf or its subclasses");
1392
1393 std::string Result = (" " + getImmType() + " Imm = ").str();
1394 if (immCodeUsesAPFloat())
1395 Result += "cast<ConstantFPSDNode>(Op.getNode())->getValueAPF();\n";
1396 else if (immCodeUsesAPInt())
1397 Result += "Op->getAsAPIntVal();\n";
1398 else
1399 Result += "cast<ConstantSDNode>(Op.getNode())->getSExtValue();\n";
1400 return Result + ImmCode;
1401 }
1402
1403 // Handle arbitrary node predicates.
1404 assert(hasPredCode() && "Don't have any predicate code!");
1405
1406 // If this is using PatFrags, there are multiple trees to search. They should
1407 // all have the same class. FIXME: Is there a way to find a common
1408 // superclass?
1409 StringRef ClassName;
1410 for (const auto &Tree : PatFragRec->getTrees()) {
1411 StringRef TreeClassName;
1412 if (Tree->isLeaf())
1413 TreeClassName = "SDNode";
1414 else {
1415 const Record *Op = Tree->getOperator();
1416 const SDNodeInfo &Info = PatFragRec->getDAGPatterns().getSDNodeInfo(R: Op);
1417 TreeClassName = Info.getSDClassName();
1418 }
1419
1420 if (ClassName.empty())
1421 ClassName = TreeClassName;
1422 else if (ClassName != TreeClassName) {
1423 PrintFatalError(ErrorLoc: getOrigPatFragRecord()->getRecord()->getLoc(),
1424 Msg: "PatFrags trees do not have consistent class");
1425 }
1426 }
1427
1428 std::string Result;
1429 if (ClassName == "SDNode")
1430 Result = " SDNode *N = Op.getNode();\n";
1431 else
1432 Result = " auto *N = cast<" + ClassName.str() + ">(Op.getNode());\n";
1433
1434 return (Twine(Result) + " (void)N;\n" + getPredCode()).str();
1435}
1436
1437//===----------------------------------------------------------------------===//
1438// PatternToMatch implementation
1439//
1440
1441static bool isImmAllOnesAllZerosMatch(const TreePatternNode &P) {
1442 if (!P.isLeaf())
1443 return false;
1444 const DefInit *DI = dyn_cast<DefInit>(Val: P.getLeafValue());
1445 if (!DI)
1446 return false;
1447
1448 const Record *R = DI->getDef();
1449 return R->getName() == "immAllOnesV" || R->getName() == "immAllZerosV";
1450}
1451
1452/// getPatternSize - Return the 'size' of this pattern. We want to match large
1453/// patterns before small ones. This is used to determine the size of a
1454/// pattern.
1455static unsigned getPatternSize(const TreePatternNode &P,
1456 const CodeGenDAGPatterns &CGP) {
1457 unsigned Size = 3; // The node itself.
1458 // If the root node is a ConstantSDNode, increases its size.
1459 // e.g. (set R32:$dst, 0).
1460 if (P.isLeaf() && isa<IntInit>(Val: P.getLeafValue()))
1461 Size += 2;
1462
1463 if (const ComplexPattern *AM = P.getComplexPatternInfo(CGP)) {
1464 Size += AM->getComplexity();
1465 // We don't want to count any children twice, so return early.
1466 return Size;
1467 }
1468
1469 // If this node has some predicate function that must match, it adds to the
1470 // complexity of this node.
1471 if (!P.getPredicateCalls().empty())
1472 ++Size;
1473
1474 // Count children in the count if they are also nodes.
1475 for (const TreePatternNode &Child : P.children()) {
1476 if (!Child.isLeaf() && Child.getNumTypes()) {
1477 // FIXME: Can we assume non-simple VTs should be counted?
1478 auto VVT = Child.getType(ResNo: 0);
1479 if (llvm::any_of(Range&: VVT, P: [](auto &P) { return P.second != MVT::Other; })) {
1480 Size += getPatternSize(P: Child, CGP);
1481 continue;
1482 }
1483 }
1484 if (Child.isLeaf()) {
1485 if (isa<IntInit>(Val: Child.getLeafValue()))
1486 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
1487 else if (Child.getComplexPatternInfo(CGP))
1488 Size += getPatternSize(P: Child, CGP);
1489 else if (isImmAllOnesAllZerosMatch(P: Child))
1490 Size += 4; // Matches a build_vector(+3) and a predicate (+1).
1491 else if (!Child.getPredicateCalls().empty())
1492 ++Size;
1493 }
1494 }
1495
1496 return Size;
1497}
1498
1499/// Compute the complexity metric for the input pattern. This roughly
1500/// corresponds to the number of nodes that are covered.
1501int PatternToMatch::getPatternComplexity(const CodeGenDAGPatterns &CGP) const {
1502 return getPatternSize(P: getSrcPattern(), CGP) + getAddedComplexity();
1503}
1504
1505void PatternToMatch::getPredicateRecords(
1506 SmallVectorImpl<const Record *> &PredicateRecs) const {
1507 for (const Init *I : Predicates->getElements()) {
1508 if (const DefInit *Pred = dyn_cast<DefInit>(Val: I)) {
1509 const Record *Def = Pred->getDef();
1510 if (!Def->isSubClassOf(Name: "Predicate")) {
1511#ifndef NDEBUG
1512 Def->dump();
1513#endif
1514 llvm_unreachable("Unknown predicate type!");
1515 }
1516 PredicateRecs.push_back(Elt: Def);
1517 }
1518 }
1519 // Sort so that different orders get canonicalized to the same string.
1520 llvm::sort(C&: PredicateRecs, Comp: LessRecord());
1521 // Remove duplicate predicates.
1522 PredicateRecs.erase(CS: llvm::unique(R&: PredicateRecs), CE: PredicateRecs.end());
1523}
1524
1525/// getPredicateCheck - Return a single string containing all of this
1526/// pattern's predicates concatenated with "&&" operators.
1527///
1528std::string PatternToMatch::getPredicateCheck() const {
1529 SmallVector<const Record *, 4> PredicateRecs;
1530 getPredicateRecords(PredicateRecs);
1531
1532 SmallString<128> PredicateCheck;
1533 raw_svector_ostream OS(PredicateCheck);
1534 ListSeparator LS(" && ");
1535 for (const Record *Pred : PredicateRecs) {
1536 StringRef CondString = Pred->getValueAsString(FieldName: "CondString");
1537 if (CondString.empty())
1538 continue;
1539 OS << LS << '(' << CondString << ')';
1540 }
1541
1542 if (!HwModeFeatures.empty())
1543 OS << LS << HwModeFeatures;
1544
1545 return std::string(PredicateCheck);
1546}
1547
1548//===----------------------------------------------------------------------===//
1549// SDTypeConstraint implementation
1550//
1551
1552SDTypeConstraint::SDTypeConstraint(const Record *R, const CodeGenHwModes &CGH) {
1553 OperandNo = R->getValueAsInt(FieldName: "OperandNum");
1554
1555 if (R->isSubClassOf(Name: "SDTCisVT")) {
1556 ConstraintType = SDTCisVT;
1557 VVT = getValueTypeByHwMode(Rec: R->getValueAsDef(FieldName: "VT"), CGH);
1558 for (const auto &P : VVT)
1559 if (P.second == MVT::isVoid)
1560 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "Cannot use 'Void' as type to SDTCisVT");
1561 } else if (R->isSubClassOf(Name: "SDTCisPtrTy")) {
1562 ConstraintType = SDTCisPtrTy;
1563 } else if (R->isSubClassOf(Name: "SDTCisInt")) {
1564 ConstraintType = SDTCisInt;
1565 } else if (R->isSubClassOf(Name: "SDTCisFP")) {
1566 ConstraintType = SDTCisFP;
1567 } else if (R->isSubClassOf(Name: "SDTCisVec")) {
1568 ConstraintType = SDTCisVec;
1569 } else if (R->isSubClassOf(Name: "SDTCisSameAs")) {
1570 ConstraintType = SDTCisSameAs;
1571 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1572 } else if (R->isSubClassOf(Name: "SDTCisVTSmallerThanOp")) {
1573 ConstraintType = SDTCisVTSmallerThanOp;
1574 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1575 } else if (R->isSubClassOf(Name: "SDTCisOpSmallerThanOp")) {
1576 ConstraintType = SDTCisOpSmallerThanOp;
1577 OtherOperandNo = R->getValueAsInt(FieldName: "BigOperandNum");
1578 } else if (R->isSubClassOf(Name: "SDTCisEltOfVec")) {
1579 ConstraintType = SDTCisEltOfVec;
1580 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOpNum");
1581 } else if (R->isSubClassOf(Name: "SDTCisSubVecOfVec")) {
1582 ConstraintType = SDTCisSubVecOfVec;
1583 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOpNum");
1584 } else if (R->isSubClassOf(Name: "SDTCVecEltisVT")) {
1585 ConstraintType = SDTCVecEltisVT;
1586 VVT = getValueTypeByHwMode(Rec: R->getValueAsDef(FieldName: "VT"), CGH);
1587 for (const auto &P : VVT) {
1588 MVT T = P.second;
1589 if (T.isVector())
1590 PrintFatalError(ErrorLoc: R->getLoc(),
1591 Msg: "Cannot use vector type as SDTCVecEltisVT");
1592 if (!T.isInteger() && !T.isFloatingPoint())
1593 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "Must use integer or floating point type "
1594 "as SDTCVecEltisVT");
1595 }
1596 } else if (R->isSubClassOf(Name: "SDTCisSameNumEltsAs")) {
1597 ConstraintType = SDTCisSameNumEltsAs;
1598 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1599 } else if (R->isSubClassOf(Name: "SDTCisSameSizeAs")) {
1600 ConstraintType = SDTCisSameSizeAs;
1601 OtherOperandNo = R->getValueAsInt(FieldName: "OtherOperandNum");
1602 } else {
1603 PrintFatalError(ErrorLoc: R->getLoc(),
1604 Msg: "Unrecognized SDTypeConstraint '" + R->getName() + "'!\n");
1605 }
1606}
1607
1608/// getOperandNum - Return the node corresponding to operand #OpNo in tree
1609/// N, and the result number in ResNo.
1610static TreePatternNode &getOperandNum(unsigned OpNo, TreePatternNode &N,
1611 const SDNodeInfo &NodeInfo,
1612 unsigned &ResNo) {
1613 unsigned NumResults = NodeInfo.getNumResults();
1614 if (OpNo < NumResults) {
1615 ResNo = OpNo;
1616 return N;
1617 }
1618
1619 OpNo -= NumResults;
1620
1621 if (OpNo >= N.getNumChildren()) {
1622 PrintFatalError(PrintMsg: [&N, OpNo, NumResults](raw_ostream &OS) {
1623 OS << "Invalid operand number in type constraint " << (OpNo + NumResults);
1624 N.print(OS);
1625 });
1626 }
1627 return N.getChild(N: OpNo);
1628}
1629
1630/// ApplyTypeConstraint - Given a node in a pattern, apply this type
1631/// constraint to the nodes operands. This returns true if it makes a
1632/// change, false otherwise. If a type contradiction is found, flag an error.
1633bool SDTypeConstraint::ApplyTypeConstraint(TreePatternNode &N,
1634 const SDNodeInfo &NodeInfo,
1635 TreePattern &TP) const {
1636 if (TP.hasError())
1637 return false;
1638
1639 unsigned ResNo = 0; // The result number being referenced.
1640 TreePatternNode &NodeToApply = getOperandNum(OpNo: OperandNo, N, NodeInfo, ResNo);
1641 TypeInfer &TI = TP.getInfer();
1642
1643 switch (ConstraintType) {
1644 case SDTCisVT:
1645 // Operand must be a particular type.
1646 return NodeToApply.UpdateNodeType(ResNo, InTy: VVT, TP);
1647 case SDTCisPtrTy: {
1648 // Operand must be a legal pointer (iPTR, or possibly cPTR) type.
1649 const TypeSetByHwMode &PtrTys = TP.getDAGPatterns().getLegalPtrTypes();
1650 return NodeToApply.UpdateNodeType(ResNo, InTy: PtrTys, TP);
1651 }
1652 case SDTCisInt:
1653 // Require it to be one of the legal integer VTs.
1654 return TI.EnforceInteger(Out&: NodeToApply.getExtType(ResNo));
1655 case SDTCisFP:
1656 // Require it to be one of the legal fp VTs.
1657 return TI.EnforceFloatingPoint(Out&: NodeToApply.getExtType(ResNo));
1658 case SDTCisVec:
1659 // Require it to be one of the legal vector VTs.
1660 return TI.EnforceVector(Out&: NodeToApply.getExtType(ResNo));
1661 case SDTCisSameAs: {
1662 unsigned OResNo = 0;
1663 TreePatternNode &OtherNode =
1664 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1665 return (int)NodeToApply.UpdateNodeType(ResNo, InTy: OtherNode.getExtType(ResNo: OResNo),
1666 TP) |
1667 (int)OtherNode.UpdateNodeType(ResNo: OResNo, InTy: NodeToApply.getExtType(ResNo),
1668 TP);
1669 }
1670 case SDTCisVTSmallerThanOp: {
1671 // The NodeToApply must be a leaf node that is a VT. OtherOperandNum must
1672 // have an integer type that is smaller than the VT.
1673 if (!NodeToApply.isLeaf() || !isa<DefInit>(Val: NodeToApply.getLeafValue()) ||
1674 !cast<DefInit>(Val: NodeToApply.getLeafValue())
1675 ->getDef()
1676 ->isSubClassOf(Name: "ValueType")) {
1677 TP.error(Msg: N.getOperator()->getName() + " expects a VT operand!");
1678 return false;
1679 }
1680 const DefInit *DI = cast<DefInit>(Val: NodeToApply.getLeafValue());
1681 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1682 auto VVT = getValueTypeByHwMode(Rec: DI->getDef(), CGH: T.getHwModes());
1683 TypeSetByHwMode TypeListTmp(VVT);
1684
1685 unsigned OResNo = 0;
1686 TreePatternNode &OtherNode =
1687 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1688
1689 return TI.EnforceSmallerThan(Small&: TypeListTmp, Big&: OtherNode.getExtType(ResNo: OResNo),
1690 /*SmallIsVT*/ true);
1691 }
1692 case SDTCisOpSmallerThanOp: {
1693 unsigned BResNo = 0;
1694 TreePatternNode &BigOperand =
1695 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: BResNo);
1696 return TI.EnforceSmallerThan(Small&: NodeToApply.getExtType(ResNo),
1697 Big&: BigOperand.getExtType(ResNo: BResNo));
1698 }
1699 case SDTCisEltOfVec: {
1700 unsigned VResNo = 0;
1701 TreePatternNode &VecOperand =
1702 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: VResNo);
1703 // Filter vector types out of VecOperand that don't have the right element
1704 // type.
1705 return TI.EnforceVectorEltTypeIs(Vec&: VecOperand.getExtType(ResNo: VResNo),
1706 Elem&: NodeToApply.getExtType(ResNo));
1707 }
1708 case SDTCisSubVecOfVec: {
1709 unsigned VResNo = 0;
1710 TreePatternNode &BigVecOperand =
1711 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: VResNo);
1712
1713 // Filter vector types out of BigVecOperand that don't have the
1714 // right subvector type.
1715 return TI.EnforceVectorSubVectorTypeIs(Vec&: BigVecOperand.getExtType(ResNo: VResNo),
1716 Sub&: NodeToApply.getExtType(ResNo));
1717 }
1718 case SDTCVecEltisVT: {
1719 return TI.EnforceVectorEltTypeIs(Vec&: NodeToApply.getExtType(ResNo), VVT);
1720 }
1721 case SDTCisSameNumEltsAs: {
1722 unsigned OResNo = 0;
1723 TreePatternNode &OtherNode =
1724 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1725 return TI.EnforceSameNumElts(V&: OtherNode.getExtType(ResNo: OResNo),
1726 W&: NodeToApply.getExtType(ResNo));
1727 }
1728 case SDTCisSameSizeAs: {
1729 unsigned OResNo = 0;
1730 TreePatternNode &OtherNode =
1731 getOperandNum(OpNo: OtherOperandNo, N, NodeInfo, ResNo&: OResNo);
1732 return TI.EnforceSameSize(A&: OtherNode.getExtType(ResNo: OResNo),
1733 B&: NodeToApply.getExtType(ResNo));
1734 }
1735 }
1736 llvm_unreachable("Invalid ConstraintType!");
1737}
1738
1739bool llvm::operator==(const SDTypeConstraint &LHS,
1740 const SDTypeConstraint &RHS) {
1741 if (std::tie(args: LHS.OperandNo, args: LHS.ConstraintType) !=
1742 std::tie(args: RHS.OperandNo, args: RHS.ConstraintType))
1743 return false;
1744 switch (LHS.ConstraintType) {
1745 case SDTypeConstraint::SDTCisVT:
1746 case SDTypeConstraint::SDTCVecEltisVT:
1747 return LHS.VVT == RHS.VVT;
1748 case SDTypeConstraint::SDTCisPtrTy:
1749 case SDTypeConstraint::SDTCisInt:
1750 case SDTypeConstraint::SDTCisFP:
1751 case SDTypeConstraint::SDTCisVec:
1752 break;
1753 case SDTypeConstraint::SDTCisSameAs:
1754 case SDTypeConstraint::SDTCisVTSmallerThanOp:
1755 case SDTypeConstraint::SDTCisOpSmallerThanOp:
1756 case SDTypeConstraint::SDTCisEltOfVec:
1757 case SDTypeConstraint::SDTCisSubVecOfVec:
1758 case SDTypeConstraint::SDTCisSameNumEltsAs:
1759 case SDTypeConstraint::SDTCisSameSizeAs:
1760 return LHS.OtherOperandNo == RHS.OtherOperandNo;
1761 }
1762 return true;
1763}
1764
1765bool llvm::operator<(const SDTypeConstraint &LHS, const SDTypeConstraint &RHS) {
1766 if (std::tie(args: LHS.OperandNo, args: LHS.ConstraintType) !=
1767 std::tie(args: RHS.OperandNo, args: RHS.ConstraintType))
1768 return std::tie(args: LHS.OperandNo, args: LHS.ConstraintType) <
1769 std::tie(args: RHS.OperandNo, args: RHS.ConstraintType);
1770 switch (LHS.ConstraintType) {
1771 case SDTypeConstraint::SDTCisVT:
1772 case SDTypeConstraint::SDTCVecEltisVT:
1773 return LHS.VVT < RHS.VVT;
1774 case SDTypeConstraint::SDTCisPtrTy:
1775 case SDTypeConstraint::SDTCisInt:
1776 case SDTypeConstraint::SDTCisFP:
1777 case SDTypeConstraint::SDTCisVec:
1778 break;
1779 case SDTypeConstraint::SDTCisSameAs:
1780 case SDTypeConstraint::SDTCisVTSmallerThanOp:
1781 case SDTypeConstraint::SDTCisOpSmallerThanOp:
1782 case SDTypeConstraint::SDTCisEltOfVec:
1783 case SDTypeConstraint::SDTCisSubVecOfVec:
1784 case SDTypeConstraint::SDTCisSameNumEltsAs:
1785 case SDTypeConstraint::SDTCisSameSizeAs:
1786 return LHS.OtherOperandNo < RHS.OtherOperandNo;
1787 }
1788 return false;
1789}
1790
1791/// RegClassByHwMode acts like ValueTypeByHwMode, taking the type of the
1792/// register class from the active mode.
1793static TypeSetByHwMode getTypeForRegClassByHwMode(const CodeGenTarget &T,
1794 const Record *R,
1795 ArrayRef<SMLoc> Loc) {
1796 TypeSetByHwMode TypeSet;
1797 RegClassByHwMode Helper(R, T.getRegBank());
1798
1799 for (auto [ModeID, RegClass] : Helper) {
1800 ArrayRef<ValueTypeByHwMode> RegClassVTs = RegClass->getValueTypes();
1801 MachineValueTypeSet &ModeTypeSet = TypeSet.getOrCreate(Mode: ModeID);
1802 for (const ValueTypeByHwMode &VT : RegClassVTs) {
1803 if (!VT.hasMode(M: ModeID) && !VT.hasDefault()) {
1804 PrintError(ErrorLoc: R->getLoc(), Msg: "Could not resolve VT for Mode " +
1805 T.getHwModes().getModeName(Id: ModeID, IncludeDefault: true));
1806 if (VT.getRecord())
1807 PrintNote(NoteLoc: VT.getRecord()->getLoc(), Msg: "ValueTypeByHwMode " +
1808 VT.getRecord()->getName() +
1809 " defined here");
1810 PrintFatalNote(ErrorLoc: Loc, Msg: "pattern instantiated here");
1811 continue;
1812 }
1813 ModeTypeSet.insert(T: VT.getType(Mode: ModeID));
1814 }
1815 }
1816
1817 return TypeSet;
1818}
1819
1820// Update the node type to match an instruction operand or result as specified
1821// in the ins or outs lists on the instruction definition. Return true if the
1822// type was actually changed.
1823bool TreePatternNode::UpdateNodeTypeFromInst(unsigned ResNo,
1824 const Record *Operand,
1825 TreePattern &TP) {
1826 // The 'unknown' operand indicates that types should be inferred from the
1827 // context.
1828 if (Operand->isSubClassOf(Name: "unknown_class"))
1829 return false;
1830
1831 // The Operand class specifies a type directly.
1832 if (Operand->isSubClassOf(Name: "Operand")) {
1833 const Record *R = Operand->getValueAsDef(FieldName: "Type");
1834 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
1835 return UpdateNodeType(ResNo, InTy: getValueTypeByHwMode(Rec: R, CGH: T.getHwModes()), TP);
1836 }
1837
1838 // Both RegisterClass and RegisterOperand operands derive their types from a
1839 // register class def.
1840 const Record *RC = nullptr;
1841 if (Operand->isSubClassOf(Name: "RegisterClassLike"))
1842 RC = Operand;
1843 else if (Operand->isSubClassOf(Name: "RegisterOperand"))
1844 RC = Operand->getValueAsDef(FieldName: "RegClass");
1845
1846 if (!RC) {
1847 TP.error(Msg: "cannot update node type from unknown operand!");
1848 return false;
1849 }
1850
1851 CodeGenTarget &Tgt = TP.getDAGPatterns().getTargetInfo();
1852 if (RC->isSubClassOf(Name: "RegClassByHwMode"))
1853 return UpdateNodeType(
1854 ResNo, InTy: getTypeForRegClassByHwMode(T: Tgt, R: RC, Loc: TP.getRecord()->getLoc()),
1855 TP);
1856
1857 return UpdateNodeType(ResNo, InTy: Tgt.getRegisterClass(R: RC).getValueTypes(), TP);
1858}
1859
1860bool TreePatternNode::ContainsUnresolvedType(TreePattern &TP) const {
1861 for (const TypeSetByHwMode &Type : Types)
1862 if (!Type.isValueTypeByHwMode(/*AllowEmpty=*/true))
1863 return true;
1864 for (const TreePatternNode &Child : children())
1865 if (Child.ContainsUnresolvedType(TP))
1866 return true;
1867 return false;
1868}
1869
1870bool TreePatternNode::hasProperTypeByHwMode() const {
1871 for (const TypeSetByHwMode &S : Types)
1872 if (!S.isSimple())
1873 return true;
1874 for (const TreePatternNodePtr &C : Children)
1875 if (C->hasProperTypeByHwMode())
1876 return true;
1877 return false;
1878}
1879
1880bool TreePatternNode::hasPossibleType() const {
1881 for (const TypeSetByHwMode &S : Types)
1882 if (!S.isPossible())
1883 return false;
1884 for (const TreePatternNodePtr &C : Children)
1885 if (!C->hasPossibleType())
1886 return false;
1887 return true;
1888}
1889
1890bool TreePatternNode::setDefaultMode(unsigned Mode) {
1891 for (TypeSetByHwMode &S : Types) {
1892 S.makeSimple(Mode);
1893 // Check if the selected mode had a type conflict.
1894 if (S.get(Mode: DefaultMode).empty())
1895 return false;
1896 }
1897 for (const TreePatternNodePtr &C : Children)
1898 if (!C->setDefaultMode(Mode))
1899 return false;
1900 return true;
1901}
1902
1903//===----------------------------------------------------------------------===//
1904// SDNodeInfo implementation
1905//
1906SDNodeInfo::SDNodeInfo(const Record *R, const CodeGenHwModes &CGH) : Def(R) {
1907 EnumName = R->getValueAsString(FieldName: "Opcode");
1908 SDClassName = R->getValueAsString(FieldName: "SDClass");
1909 const Record *TypeProfile = R->getValueAsDef(FieldName: "TypeProfile");
1910 NumResults = TypeProfile->getValueAsInt(FieldName: "NumResults");
1911 NumOperands = TypeProfile->getValueAsInt(FieldName: "NumOperands");
1912
1913 // Parse the properties.
1914 Properties = parseSDPatternOperatorProperties(R);
1915 IsStrictFP = R->getValueAsBit(FieldName: "IsStrictFP");
1916
1917 std::optional<int64_t> MaybeTSFlags =
1918 R->getValueAsBitsInit(FieldName: "TSFlags")->convertInitializerToInt();
1919 if (!MaybeTSFlags)
1920 PrintFatalError(ErrorLoc: R->getLoc(), Msg: "Invalid TSFlags");
1921 assert(isUInt<32>(*MaybeTSFlags) && "TSFlags bit width out of sync");
1922 TSFlags = *MaybeTSFlags;
1923
1924 // Parse the type constraints.
1925 for (const Record *R : TypeProfile->getValueAsListOfDefs(FieldName: "Constraints"))
1926 TypeConstraints.emplace_back(args&: R, args: CGH);
1927}
1928
1929/// getKnownType - If the type constraints on this node imply a fixed type
1930/// (e.g. all stores return void, etc), then return it as an
1931/// MVT. Otherwise, return EEVT::Other.
1932MVT SDNodeInfo::getKnownType(unsigned ResNo) const {
1933 unsigned NumResults = getNumResults();
1934 assert(NumResults <= 1 &&
1935 "We only work with nodes with zero or one result so far!");
1936 assert(ResNo == 0 && "Only handles single result nodes so far");
1937
1938 for (const SDTypeConstraint &Constraint : TypeConstraints) {
1939 // Make sure that this applies to the correct node result.
1940 if (Constraint.OperandNo >= NumResults) // FIXME: need value #
1941 continue;
1942
1943 switch (Constraint.ConstraintType) {
1944 default:
1945 break;
1946 case SDTypeConstraint::SDTCisVT:
1947 if (Constraint.VVT.isSimple())
1948 return Constraint.VVT.getSimple().SimpleTy;
1949 break;
1950 case SDTypeConstraint::SDTCisPtrTy:
1951 return MVT::iPTR;
1952 }
1953 }
1954 return MVT::Other;
1955}
1956
1957//===----------------------------------------------------------------------===//
1958// TreePatternNode implementation
1959//
1960
1961static unsigned GetNumNodeResults(const Record *Operator,
1962 CodeGenDAGPatterns &CDP) {
1963 if (Operator->getName() == "set")
1964 return 0; // All return nothing.
1965
1966 if (Operator->isSubClassOf(Name: "Intrinsic"))
1967 return CDP.getIntrinsic(R: Operator).IS.RetTys.size();
1968
1969 if (Operator->isSubClassOf(Name: "SDNode"))
1970 return CDP.getSDNodeInfo(R: Operator).getNumResults();
1971
1972 if (Operator->isSubClassOf(Name: "PatFrags")) {
1973 // If we've already parsed this pattern fragment, get it. Otherwise, handle
1974 // the forward reference case where one pattern fragment references another
1975 // before it is processed.
1976 if (TreePattern *PFRec = CDP.getPatternFragmentIfRead(R: Operator)) {
1977 // The number of results of a fragment with alternative records is the
1978 // maximum number of results across all alternatives.
1979 unsigned NumResults = 0;
1980 for (const auto &T : PFRec->getTrees())
1981 NumResults = std::max(a: NumResults, b: T->getNumTypes());
1982 return NumResults;
1983 }
1984
1985 const ListInit *LI = Operator->getValueAsListInit(FieldName: "Fragments");
1986 assert(LI && "Invalid Fragment");
1987 unsigned NumResults = 0;
1988 for (const Init *I : LI->getElements()) {
1989 const Record *Op = nullptr;
1990 if (const DagInit *Dag = dyn_cast<DagInit>(Val: I))
1991 if (const DefInit *DI = dyn_cast<DefInit>(Val: Dag->getOperator()))
1992 Op = DI->getDef();
1993 assert(Op && "Invalid Fragment");
1994 NumResults = std::max(a: NumResults, b: GetNumNodeResults(Operator: Op, CDP));
1995 }
1996 return NumResults;
1997 }
1998
1999 if (Operator->isSubClassOf(Name: "Instruction")) {
2000 const CodeGenInstruction &InstInfo =
2001 CDP.getTargetInfo().getInstruction(InstRec: Operator);
2002
2003 unsigned NumDefsToAdd = InstInfo.Operands.NumDefs;
2004
2005 // Subtract any defaulted outputs.
2006 for (unsigned i = 0; i != InstInfo.Operands.NumDefs; ++i) {
2007 const Record *OperandNode = InstInfo.Operands[i].Rec;
2008
2009 if (OperandNode->isSubClassOf(Name: "OperandWithDefaultOps") &&
2010 !CDP.getDefaultOperand(R: OperandNode).DefaultOps.empty())
2011 --NumDefsToAdd;
2012 }
2013
2014 // Add on one implicit def if it has a resolvable type.
2015 if (InstInfo.HasOneImplicitDefWithKnownVT(TargetInfo: CDP.getTargetInfo()) !=
2016 MVT::Other)
2017 ++NumDefsToAdd;
2018 return NumDefsToAdd;
2019 }
2020
2021 if (Operator->isSubClassOf(Name: "SDNodeXForm"))
2022 return 1; // FIXME: Generalize SDNodeXForm
2023
2024 if (Operator->isSubClassOf(Name: "ValueType"))
2025 return 1; // A type-cast of one result.
2026
2027 if (Operator->isSubClassOf(Name: "ComplexPattern"))
2028 return 1;
2029
2030 errs() << *Operator;
2031 PrintFatalError(Msg: "Unhandled node in GetNumNodeResults");
2032}
2033
2034void TreePatternNode::print(raw_ostream &OS) const {
2035 if (isLeaf())
2036 OS << *getLeafValue();
2037 else
2038 OS << '(' << getOperator()->getName();
2039
2040 for (unsigned i = 0, e = Types.size(); i != e; ++i) {
2041 OS << ':';
2042 getExtType(ResNo: i).writeToStream(OS);
2043 }
2044
2045 if (!isLeaf()) {
2046 if (getNumChildren() != 0) {
2047 OS << " ";
2048 ListSeparator LS;
2049 for (const TreePatternNode &Child : children()) {
2050 OS << LS;
2051 Child.print(OS);
2052 }
2053 }
2054 OS << ")";
2055 }
2056
2057 for (const TreePredicateCall &Pred : PredicateCalls) {
2058 OS << "<<P:";
2059 if (Pred.Scope)
2060 OS << Pred.Scope << ":";
2061 OS << Pred.Fn.getFnName() << ">>";
2062 }
2063 if (TransformFn)
2064 OS << "<<X:" << TransformFn->getName() << ">>";
2065 if (!getName().empty())
2066 OS << ":$" << getName();
2067
2068 for (const ScopedName &Name : NamesAsPredicateArg)
2069 OS << ":$pred:" << Name.getScope() << ":" << Name.getIdentifier();
2070}
2071void TreePatternNode::dump() const {
2072 print(OS&: dbgs());
2073 dbgs() << '\n';
2074}
2075
2076/// isIsomorphicTo - Return true if this node is recursively
2077/// isomorphic to the specified node. For this comparison, the node's
2078/// entire state is considered. The assigned name is ignored, since
2079/// nodes with differing names are considered isomorphic. However, if
2080/// the assigned name is present in the dependent variable set, then
2081/// the assigned name is considered significant and the node is
2082/// isomorphic if the names match.
2083bool TreePatternNode::isIsomorphicTo(const TreePatternNode &N,
2084 const MultipleUseVarSet &DepVars) const {
2085 if (&N == this)
2086 return true;
2087 if (N.isLeaf() != isLeaf())
2088 return false;
2089
2090 // Check operator of non-leaves early since it can be cheaper than checking
2091 // types.
2092 if (!isLeaf())
2093 if (N.getOperator() != getOperator() ||
2094 N.getNumChildren() != getNumChildren())
2095 return false;
2096
2097 if (getExtTypes() != N.getExtTypes() ||
2098 getPredicateCalls() != N.getPredicateCalls() ||
2099 getTransformFn() != N.getTransformFn())
2100 return false;
2101
2102 if (isLeaf()) {
2103 if (const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue())) {
2104 if (const DefInit *NDI = dyn_cast<DefInit>(Val: N.getLeafValue())) {
2105 return ((DI->getDef() == NDI->getDef()) &&
2106 (!DepVars.contains(key: getName()) || getName() == N.getName()));
2107 }
2108 }
2109 return getLeafValue() == N.getLeafValue();
2110 }
2111
2112 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
2113 if (!getChild(N: i).isIsomorphicTo(N: N.getChild(N: i), DepVars))
2114 return false;
2115 return true;
2116}
2117
2118/// clone - Make a copy of this tree and all of its children.
2119///
2120TreePatternNodePtr TreePatternNode::clone() const {
2121 TreePatternNodePtr New;
2122 if (isLeaf()) {
2123 New = makeIntrusiveRefCnt<TreePatternNode>(A: getLeafValue(), A: getNumTypes());
2124 } else {
2125 std::vector<TreePatternNodePtr> CChildren;
2126 CChildren.reserve(n: Children.size());
2127 for (const TreePatternNode &Child : children())
2128 CChildren.push_back(x: Child.clone());
2129 New = makeIntrusiveRefCnt<TreePatternNode>(
2130 A: getOperator(), A: std::move(CChildren), A: getNumTypes());
2131 }
2132 New->setName(getName());
2133 New->setNamesAsPredicateArg(getNamesAsPredicateArg());
2134 New->Types = Types;
2135 New->setPredicateCalls(getPredicateCalls());
2136 New->setGISelFlagsRecord(getGISelFlagsRecord());
2137 New->setTransformFn(getTransformFn());
2138 return New;
2139}
2140
2141/// RemoveAllTypes - Recursively strip all the types of this tree.
2142void TreePatternNode::RemoveAllTypes() {
2143 // Reset to unknown type.
2144 llvm::fill(Range&: Types, Value: TypeSetByHwMode());
2145 if (isLeaf())
2146 return;
2147 for (TreePatternNode &Child : children())
2148 Child.RemoveAllTypes();
2149}
2150
2151/// SubstituteFormalArguments - Replace the formal arguments in this tree
2152/// with actual values specified by ArgMap.
2153void TreePatternNode::SubstituteFormalArguments(
2154 std::map<StringRef, TreePatternNodePtr> &ArgMap) {
2155 if (isLeaf())
2156 return;
2157
2158 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2159 TreePatternNode &Child = getChild(N: i);
2160 if (Child.isLeaf()) {
2161 const Init *Val = Child.getLeafValue();
2162 // Note that, when substituting into an output pattern, Val might be an
2163 // UnsetInit.
2164 if (isa<UnsetInit>(Val) ||
2165 (isa<DefInit>(Val) &&
2166 cast<DefInit>(Val)->getDef()->getName() == "node")) {
2167 // We found a use of a formal argument, replace it with its value.
2168 TreePatternNodePtr NewChild = ArgMap[Child.getName()];
2169 assert(NewChild && "Couldn't find formal argument!");
2170 assert((Child.getPredicateCalls().empty() ||
2171 NewChild->getPredicateCalls() == Child.getPredicateCalls()) &&
2172 "Non-empty child predicate clobbered!");
2173 setChild(i, N: std::move(NewChild));
2174 }
2175 } else {
2176 getChild(N: i).SubstituteFormalArguments(ArgMap);
2177 }
2178 }
2179}
2180
2181/// InlinePatternFragments - If this pattern refers to any pattern
2182/// fragments, return the set of inlined versions (this can be more than
2183/// one if a PatFrags record has multiple alternatives).
2184void TreePatternNode::InlinePatternFragments(
2185 TreePattern &TP, std::vector<TreePatternNodePtr> &OutAlternatives) {
2186
2187 if (TP.hasError())
2188 return;
2189
2190 if (isLeaf()) {
2191 OutAlternatives.push_back(x: this); // nothing to do.
2192 return;
2193 }
2194
2195 const Record *Op = getOperator();
2196
2197 if (!Op->isSubClassOf(Name: "PatFrags")) {
2198 if (getNumChildren() == 0) {
2199 OutAlternatives.push_back(x: this);
2200 return;
2201 }
2202
2203 // Recursively inline children nodes.
2204 std::vector<std::vector<TreePatternNodePtr>> ChildAlternatives(
2205 getNumChildren());
2206 for (unsigned i = 0, e = getNumChildren(); i != e; ++i) {
2207 TreePatternNodePtr Child = getChildShared(N: i);
2208 Child->InlinePatternFragments(TP, OutAlternatives&: ChildAlternatives[i]);
2209 // If there are no alternatives for any child, there are no
2210 // alternatives for this expression as whole.
2211 if (ChildAlternatives[i].empty())
2212 return;
2213
2214 assert((Child->getPredicateCalls().empty() ||
2215 llvm::all_of(ChildAlternatives[i],
2216 [&](const TreePatternNodePtr &NewChild) {
2217 return NewChild->getPredicateCalls() ==
2218 Child->getPredicateCalls();
2219 })) &&
2220 "Non-empty child predicate clobbered!");
2221 }
2222
2223 // The end result is an all-pairs construction of the resultant pattern.
2224 std::vector<unsigned> Idxs(ChildAlternatives.size());
2225 bool NotDone;
2226 do {
2227 // Create the variant and add it to the output list.
2228 std::vector<TreePatternNodePtr> NewChildren;
2229 NewChildren.reserve(n: ChildAlternatives.size());
2230 for (unsigned i = 0, e = ChildAlternatives.size(); i != e; ++i)
2231 NewChildren.push_back(x: ChildAlternatives[i][Idxs[i]]);
2232 TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
2233 A: getOperator(), A: std::move(NewChildren), A: getNumTypes());
2234
2235 // Copy over properties.
2236 R->setName(getName());
2237 R->setNamesAsPredicateArg(getNamesAsPredicateArg());
2238 R->setPredicateCalls(getPredicateCalls());
2239 R->setGISelFlagsRecord(getGISelFlagsRecord());
2240 R->setTransformFn(getTransformFn());
2241 for (unsigned i = 0, e = getNumTypes(); i != e; ++i)
2242 R->setType(ResNo: i, T: getExtType(ResNo: i));
2243 for (unsigned i = 0, e = getNumResults(); i != e; ++i)
2244 R->setResultIndex(ResNo: i, RI: getResultIndex(ResNo: i));
2245
2246 // Register alternative.
2247 OutAlternatives.push_back(x: R);
2248
2249 // Increment indices to the next permutation by incrementing the
2250 // indices from last index backward, e.g., generate the sequence
2251 // [0, 0], [0, 1], [1, 0], [1, 1].
2252 int IdxsIdx;
2253 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
2254 if (++Idxs[IdxsIdx] == ChildAlternatives[IdxsIdx].size())
2255 Idxs[IdxsIdx] = 0;
2256 else
2257 break;
2258 }
2259 NotDone = (IdxsIdx >= 0);
2260 } while (NotDone);
2261
2262 return;
2263 }
2264
2265 // Otherwise, we found a reference to a fragment. First, look up its
2266 // TreePattern record.
2267 TreePattern *Frag = TP.getDAGPatterns().getPatternFragment(R: Op);
2268
2269 // Verify that we are passing the right number of operands.
2270 if (Frag->getNumArgs() != getNumChildren()) {
2271 TP.error(Msg: "'" + Op->getName() + "' fragment requires " +
2272 Twine(Frag->getNumArgs()) + " operands!");
2273 return;
2274 }
2275
2276 TreePredicateFn PredFn(Frag);
2277 unsigned Scope = 0;
2278 if (TreePredicateFn(Frag).usesOperands())
2279 Scope = TP.getDAGPatterns().allocateScope();
2280
2281 // Compute the map of formal to actual arguments.
2282 std::map<StringRef, TreePatternNodePtr> ArgMap;
2283 for (unsigned i = 0, e = Frag->getNumArgs(); i != e; ++i) {
2284 TreePatternNodePtr Child = getChildShared(N: i);
2285 if (Scope != 0) {
2286 Child = Child->clone();
2287 Child->addNameAsPredicateArg(N: ScopedName(Scope, Frag->getArgName(i)));
2288 }
2289 ArgMap[Frag->getArgName(i)] = Child;
2290 }
2291
2292 // Loop over all fragment alternatives.
2293 for (const auto &Alternative : Frag->getTrees()) {
2294 TreePatternNodePtr FragTree = Alternative->clone();
2295
2296 if (!PredFn.isAlwaysTrue())
2297 FragTree->addPredicateCall(Fn: PredFn, Scope);
2298
2299 // Resolve formal arguments to their actual value.
2300 if (Frag->getNumArgs())
2301 FragTree->SubstituteFormalArguments(ArgMap);
2302
2303 // Transfer types. Note that the resolved alternative may have fewer
2304 // (but not more) results than the PatFrags node.
2305 FragTree->setName(getName());
2306 for (unsigned i = 0, e = FragTree->getNumTypes(); i != e; ++i)
2307 FragTree->UpdateNodeType(ResNo: i, InTy: getExtType(ResNo: i), TP);
2308
2309 if (Op->isSubClassOf(Name: "GISelFlags"))
2310 FragTree->setGISelFlagsRecord(Op);
2311
2312 // Transfer in the old predicates.
2313 for (const TreePredicateCall &Pred : getPredicateCalls())
2314 FragTree->addPredicateCall(Call: Pred);
2315
2316 // The fragment we inlined could have recursive inlining that is needed. See
2317 // if there are any pattern fragments in it and inline them as needed.
2318 FragTree->InlinePatternFragments(TP, OutAlternatives);
2319 }
2320}
2321
2322/// getImplicitType - Check to see if the specified record has an implicit
2323/// type which should be applied to it. This will infer the type of register
2324/// references from the register file information, for example.
2325///
2326/// When Unnamed is set, return the type of a DAG operand with no name, such as
2327/// the F8RC register class argument in:
2328///
2329/// (COPY_TO_REGCLASS GPR:$src, F8RC)
2330///
2331/// When Unnamed is false, return the type of a named DAG operand such as the
2332/// GPR:$src operand above.
2333///
2334static TypeSetByHwMode getImplicitType(const Record *R, unsigned ResNo,
2335 bool NotRegisters, bool Unnamed,
2336 TreePattern &TP) {
2337 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2338
2339 // Check to see if this is a register operand.
2340 if (R->isSubClassOf(Name: "RegisterOperand")) {
2341 assert(ResNo == 0 && "Regoperand ref only has one result!");
2342 if (NotRegisters)
2343 return TypeSetByHwMode(); // Unknown.
2344 const Record *RegClass = R->getValueAsDef(FieldName: "RegClass");
2345 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2346
2347 if (RegClass->isSubClassOf(Name: "RegClassByHwMode"))
2348 return getTypeForRegClassByHwMode(T, R: RegClass, Loc: TP.getRecord()->getLoc());
2349
2350 return TypeSetByHwMode(T.getRegisterClass(R: RegClass).getValueTypes());
2351 }
2352
2353 // Check to see if this is a register or a register class.
2354 if (R->isSubClassOf(Name: "RegisterClass")) {
2355 assert(ResNo == 0 && "Regclass ref only has one result!");
2356 // An unnamed register class represents itself as an i32 immediate, for
2357 // example on a COPY_TO_REGCLASS instruction.
2358 if (Unnamed)
2359 return TypeSetByHwMode(MVT::i32);
2360
2361 // In a named operand, the register class provides the possible set of
2362 // types.
2363 if (NotRegisters)
2364 return TypeSetByHwMode(); // Unknown.
2365 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2366 return TypeSetByHwMode(T.getRegisterClass(R).getValueTypes());
2367 }
2368
2369 if (R->isSubClassOf(Name: "RegClassByHwMode")) {
2370 if (NotRegisters)
2371 return TypeSetByHwMode(); // Unknown.
2372 const CodeGenTarget &T = CDP.getTargetInfo();
2373 return getTypeForRegClassByHwMode(T, R, Loc: TP.getRecord()->getLoc());
2374 }
2375
2376 if (R->isSubClassOf(Name: "PatFrags")) {
2377 assert(ResNo == 0 && "FIXME: PatFrag with multiple results?");
2378 // Pattern fragment types will be resolved when they are inlined.
2379 return TypeSetByHwMode(); // Unknown.
2380 }
2381
2382 if (R->isSubClassOf(Name: "Register")) {
2383 assert(ResNo == 0 && "Registers only produce one result!");
2384 if (NotRegisters)
2385 return TypeSetByHwMode(); // Unknown.
2386 const CodeGenTarget &T = TP.getDAGPatterns().getTargetInfo();
2387 return TypeSetByHwMode(T.getRegisterVTs(R));
2388 }
2389
2390 if (R->isSubClassOf(Name: "SubRegIndex")) {
2391 assert(ResNo == 0 && "SubRegisterIndices only produce one result!");
2392 return TypeSetByHwMode(MVT::i32);
2393 }
2394
2395 if (R->isSubClassOf(Name: "ValueType")) {
2396 assert(ResNo == 0 && "This node only has one result!");
2397 // An unnamed VTSDNode represents itself as an MVT::Other immediate.
2398 //
2399 // (sext_inreg GPR:$src, i16)
2400 // ~~~
2401 if (Unnamed)
2402 return TypeSetByHwMode(MVT::Other);
2403 // With a name, the ValueType simply provides the type of the named
2404 // variable.
2405 //
2406 // (sext_inreg i32:$src, i16)
2407 // ~~~~~~~~
2408 if (NotRegisters)
2409 return TypeSetByHwMode(); // Unknown.
2410 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2411 return TypeSetByHwMode(getValueTypeByHwMode(Rec: R, CGH));
2412 }
2413
2414 if (R->isSubClassOf(Name: "CondCode")) {
2415 assert(ResNo == 0 && "This node only has one result!");
2416 // Using a CondCodeSDNode.
2417 return TypeSetByHwMode(MVT::Other);
2418 }
2419
2420 if (R->isSubClassOf(Name: "ComplexPattern")) {
2421 assert(ResNo == 0 && "FIXME: ComplexPattern with multiple results?");
2422 if (NotRegisters)
2423 return TypeSetByHwMode(); // Unknown.
2424 const Record *T = CDP.getComplexPattern(R).getValueType();
2425 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2426 return TypeSetByHwMode(getValueTypeByHwMode(Rec: T, CGH));
2427 }
2428
2429 if (R->getName() == "node" || R->getName() == "srcvalue" ||
2430 R->getName() == "zero_reg" || R->getName() == "immAllOnesV" ||
2431 R->getName() == "immAllZerosV" || R->getName() == "undef_tied_input") {
2432 // Placeholder.
2433 return TypeSetByHwMode(); // Unknown.
2434 }
2435
2436 if (R->isSubClassOf(Name: "Operand")) {
2437 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2438 const Record *T = R->getValueAsDef(FieldName: "Type");
2439 return TypeSetByHwMode(getValueTypeByHwMode(Rec: T, CGH));
2440 }
2441
2442 TP.error(Msg: "Unknown node flavor used in pattern: " + R->getName());
2443 return TypeSetByHwMode(MVT::Other);
2444}
2445
2446/// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
2447/// CodeGenIntrinsic information for it, otherwise return a null pointer.
2448const CodeGenIntrinsic *
2449TreePatternNode::getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const {
2450 if (getOperator() != CDP.get_intrinsic_void_sdnode() &&
2451 getOperator() != CDP.get_intrinsic_w_chain_sdnode() &&
2452 getOperator() != CDP.get_intrinsic_wo_chain_sdnode())
2453 return nullptr;
2454
2455 unsigned IID = cast<IntInit>(Val: getChild(N: 0).getLeafValue())->getValue();
2456 return &CDP.getIntrinsicInfo(IID);
2457}
2458
2459/// getComplexPatternInfo - If this node corresponds to a ComplexPattern,
2460/// return the ComplexPattern information, otherwise return null.
2461const ComplexPattern *
2462TreePatternNode::getComplexPatternInfo(const CodeGenDAGPatterns &CGP) const {
2463 const Record *Rec;
2464 if (isLeaf()) {
2465 const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue());
2466 if (!DI)
2467 return nullptr;
2468 Rec = DI->getDef();
2469 } else {
2470 Rec = getOperator();
2471 }
2472
2473 if (!Rec->isSubClassOf(Name: "ComplexPattern"))
2474 return nullptr;
2475 return &CGP.getComplexPattern(R: Rec);
2476}
2477
2478unsigned TreePatternNode::getNumMIResults(const CodeGenDAGPatterns &CGP) const {
2479 // A ComplexPattern specifically declares how many results it fills in.
2480 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2481 return CP->getNumOperands();
2482
2483 // If MIOperandInfo is specified, that gives the count.
2484 if (isLeaf()) {
2485 const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue());
2486 if (DI && DI->getDef()->isSubClassOf(Name: "Operand")) {
2487 const DagInit *MIOps = DI->getDef()->getValueAsDag(FieldName: "MIOperandInfo");
2488 if (MIOps->getNumArgs())
2489 return MIOps->getNumArgs();
2490 }
2491 }
2492
2493 // Otherwise there is just one result.
2494 return 1;
2495}
2496
2497/// NodeHasProperty - Return true if this node has the specified property.
2498bool TreePatternNode::NodeHasProperty(SDNP Property,
2499 const CodeGenDAGPatterns &CGP) const {
2500 if (isLeaf()) {
2501 if (const ComplexPattern *CP = getComplexPatternInfo(CGP))
2502 return CP->hasProperty(Prop: Property);
2503
2504 return false;
2505 }
2506
2507 if (Property != SDNPHasChain) {
2508 // The chain proprety is already present on the different intrinsic node
2509 // types (intrinsic_w_chain, intrinsic_void), and is not explicitly listed
2510 // on the intrinsic. Anything else is specific to the individual intrinsic.
2511 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP: CGP))
2512 return Int->hasProperty(Prop: Property);
2513 }
2514
2515 if (!getOperator()->isSubClassOf(Name: "SDPatternOperator"))
2516 return false;
2517
2518 return CGP.getSDNodeInfo(R: getOperator()).hasProperty(Prop: Property);
2519}
2520
2521/// TreeHasProperty - Return true if any node in this tree has the specified
2522/// property.
2523bool TreePatternNode::TreeHasProperty(SDNP Property,
2524 const CodeGenDAGPatterns &CGP) const {
2525 if (NodeHasProperty(Property, CGP))
2526 return true;
2527 for (const TreePatternNode &Child : children())
2528 if (Child.TreeHasProperty(Property, CGP))
2529 return true;
2530 return false;
2531}
2532
2533/// isCommutativeIntrinsic - Return true if the node corresponds to a
2534/// commutative intrinsic.
2535bool TreePatternNode::isCommutativeIntrinsic(
2536 const CodeGenDAGPatterns &CDP) const {
2537 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP))
2538 return Int->isCommutative;
2539 return false;
2540}
2541
2542static bool isOperandClass(const TreePatternNode &N, StringRef Class) {
2543 if (!N.isLeaf())
2544 return N.getOperator()->isSubClassOf(Name: Class);
2545
2546 const DefInit *DI = dyn_cast<DefInit>(Val: N.getLeafValue());
2547 if (DI && DI->getDef()->isSubClassOf(Name: Class))
2548 return true;
2549
2550 return false;
2551}
2552
2553static void emitTooManyOperandsError(TreePattern &TP, StringRef InstName,
2554 unsigned Expected, unsigned Actual) {
2555 TP.error(Msg: "Instruction '" + InstName + "' was provided " + Twine(Actual) +
2556 " operands but expected only " + Twine(Expected) + "!");
2557}
2558
2559static void emitTooFewOperandsError(TreePattern &TP, StringRef InstName,
2560 unsigned Actual) {
2561 TP.error(Msg: "Instruction '" + InstName + "' expects more than the provided " +
2562 Twine(Actual) + " operands!");
2563}
2564
2565/// ApplyTypeConstraints - Apply all of the type constraints relevant to
2566/// this node and its children in the tree. This returns true if it makes a
2567/// change, false otherwise. If a type contradiction is found, flag an error.
2568bool TreePatternNode::ApplyTypeConstraints(TreePattern &TP, bool NotRegisters) {
2569 if (TP.hasError())
2570 return false;
2571
2572 CodeGenDAGPatterns &CDP = TP.getDAGPatterns();
2573 if (isLeaf()) {
2574 if (const DefInit *DI = dyn_cast<DefInit>(Val: getLeafValue())) {
2575 // If it's a regclass or something else known, include the type.
2576 bool MadeChange = false;
2577 for (unsigned i = 0, e = Types.size(); i != e; ++i)
2578 MadeChange |= UpdateNodeType(
2579 ResNo: i, InTy: getImplicitType(R: DI->getDef(), ResNo: i, NotRegisters, Unnamed: !hasName(), TP),
2580 TP);
2581 return MadeChange;
2582 }
2583
2584 if (const IntInit *II = dyn_cast<IntInit>(Val: getLeafValue())) {
2585 assert(Types.size() == 1 && "Invalid IntInit");
2586
2587 // Int inits are always integers. :)
2588 bool MadeChange = TP.getInfer().EnforceInteger(Out&: Types[0]);
2589
2590 if (!Types[0].isValueTypeByHwMode(/*AllowEmpty=*/false))
2591 return MadeChange;
2592
2593 ValueTypeByHwMode VVT = Types[0].getValueTypeByHwMode();
2594 for (auto &P : VVT) {
2595 MVT VT = P.second;
2596 // Can only check for types of a known size
2597 if (VT == MVT::iPTR)
2598 continue;
2599
2600 // Check that the value doesn't use more bits than we have. It must
2601 // either be a sign- or zero-extended equivalent of the original.
2602 unsigned Width = VT.getFixedSizeInBits();
2603 int64_t Val = II->getValue();
2604 if (!isIntN(N: Width, x: Val) && !isUIntN(N: Width, x: Val)) {
2605 TP.error(Msg: "Integer value '" + Twine(Val) +
2606 "' is out of range for type '" + getEnumName(T: VT) + "'!");
2607 break;
2608 }
2609 }
2610 return MadeChange;
2611 }
2612
2613 return false;
2614 }
2615
2616 if (const CodeGenIntrinsic *Int = getIntrinsicInfo(CDP)) {
2617 bool MadeChange = false;
2618
2619 // Apply the result type to the node.
2620 unsigned NumRetVTs = Int->IS.RetTys.size();
2621 unsigned NumParamVTs = Int->IS.ParamTys.size();
2622
2623 for (unsigned i = 0, e = NumRetVTs; i != e; ++i)
2624 MadeChange |= UpdateNodeType(
2625 ResNo: i, InTy: getValueType(Rec: Int->IS.RetTys[i]->getValueAsDef(FieldName: "VT")), TP);
2626
2627 if (getNumChildren() != NumParamVTs + 1) {
2628 TP.error(Msg: "Intrinsic '" + Int->Name + "' expects " + Twine(NumParamVTs) +
2629 " operands, not " + Twine(getNumChildren() - 1) + " operands!");
2630 return false;
2631 }
2632
2633 // Apply type info to the intrinsic ID.
2634 MadeChange |= getChild(N: 0).UpdateNodeType(ResNo: 0, InTy: MVT::iPTR, TP);
2635
2636 for (unsigned i = 0, e = getNumChildren() - 1; i != e; ++i) {
2637 MadeChange |= getChild(N: i + 1).ApplyTypeConstraints(TP, NotRegisters);
2638
2639 MVT OpVT = getValueType(Rec: Int->IS.ParamTys[i]->getValueAsDef(FieldName: "VT"));
2640 assert(getChild(i + 1).getNumTypes() == 1 && "Unhandled case");
2641 MadeChange |= getChild(N: i + 1).UpdateNodeType(ResNo: 0, InTy: OpVT, TP);
2642 }
2643 return MadeChange;
2644 }
2645
2646 if (getOperator()->isSubClassOf(Name: "SDNode")) {
2647 const SDNodeInfo &NI = CDP.getSDNodeInfo(R: getOperator());
2648
2649 // Check that the number of operands is sane. Negative operands -> varargs.
2650 if (NI.getNumOperands() >= 0 &&
2651 getNumChildren() != (unsigned)NI.getNumOperands()) {
2652 TP.error(Msg: getOperator()->getName() + " node requires exactly " +
2653 Twine(NI.getNumOperands()) + " operands!");
2654 return false;
2655 }
2656
2657 bool MadeChange = false;
2658 for (TreePatternNode &Child : children())
2659 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2660 MadeChange |= NI.ApplyTypeConstraints(N&: *this, TP);
2661 return MadeChange;
2662 }
2663
2664 if (getOperator()->isSubClassOf(Name: "Instruction")) {
2665 const DAGInstruction &Inst = CDP.getInstruction(R: getOperator());
2666 const CodeGenInstruction &InstInfo =
2667 CDP.getTargetInfo().getInstruction(InstRec: getOperator());
2668
2669 bool MadeChange = false;
2670
2671 // Apply the result types to the node, these come from the things in the
2672 // (outs) list of the instruction.
2673 unsigned NumResultsToAdd =
2674 std::min(a: InstInfo.Operands.NumDefs, b: Inst.getNumResults());
2675 for (unsigned ResNo = 0; ResNo != NumResultsToAdd; ++ResNo)
2676 MadeChange |= UpdateNodeTypeFromInst(ResNo, Operand: Inst.getResult(RN: ResNo), TP);
2677
2678 // If the instruction has implicit defs, we apply the first one as a result.
2679 // FIXME: This sucks, it should apply all implicit defs.
2680 if (!InstInfo.ImplicitDefs.empty()) {
2681 unsigned ResNo = NumResultsToAdd;
2682
2683 // FIXME: Generalize to multiple possible types and multiple possible
2684 // ImplicitDefs.
2685 MVT VT = InstInfo.HasOneImplicitDefWithKnownVT(TargetInfo: CDP.getTargetInfo());
2686
2687 if (VT != MVT::Other)
2688 MadeChange |= UpdateNodeType(ResNo, InTy: VT, TP);
2689 }
2690
2691 // If this is an INSERT_SUBREG, constrain the source and destination VTs to
2692 // be the same.
2693 if (getOperator()->getName() == "INSERT_SUBREG") {
2694 assert(getChild(0).getNumTypes() == 1 && "FIXME: Unhandled");
2695 MadeChange |= UpdateNodeType(ResNo: 0, InTy: getChild(N: 0).getExtType(ResNo: 0), TP);
2696 MadeChange |= getChild(N: 0).UpdateNodeType(ResNo: 0, InTy: getExtType(ResNo: 0), TP);
2697 } else if (getOperator()->getName() == "REG_SEQUENCE") {
2698 // We need to do extra, custom typechecking for REG_SEQUENCE since it is
2699 // variadic.
2700
2701 unsigned NChild = getNumChildren();
2702 if (NChild < 3) {
2703 TP.error(Msg: "REG_SEQUENCE requires at least 3 operands!");
2704 return false;
2705 }
2706
2707 if (NChild % 2 == 0) {
2708 TP.error(Msg: "REG_SEQUENCE requires an odd number of operands!");
2709 return false;
2710 }
2711
2712 if (!isOperandClass(N: getChild(N: 0), Class: "RegisterClass")) {
2713 TP.error(Msg: "REG_SEQUENCE requires a RegisterClass for first operand!");
2714 return false;
2715 }
2716
2717 for (unsigned I = 1; I < NChild; I += 2) {
2718 TreePatternNode &SubIdxChild = getChild(N: I + 1);
2719 if (!isOperandClass(N: SubIdxChild, Class: "SubRegIndex")) {
2720 TP.error(Msg: "REG_SEQUENCE requires a SubRegIndex for operand " +
2721 Twine(I + 1) + "!");
2722 return false;
2723 }
2724 }
2725 }
2726
2727 unsigned NumResults = Inst.getNumResults();
2728 unsigned NumFixedOperands = InstInfo.Operands.size();
2729
2730 // If one or more operands with a default value appear at the end of the
2731 // formal operand list for an instruction, we allow them to be overridden
2732 // by optional operands provided in the pattern.
2733 //
2734 // But if an operand B without a default appears at any point after an
2735 // operand A with a default, then we don't allow A to be overridden,
2736 // because there would be no way to specify whether the next operand in
2737 // the pattern was intended to override A or skip it.
2738 unsigned NonOverridableOperands = NumFixedOperands;
2739 while (NonOverridableOperands > NumResults &&
2740 CDP.operandHasDefault(
2741 Op: InstInfo.Operands[NonOverridableOperands - 1].Rec))
2742 --NonOverridableOperands;
2743
2744 unsigned ChildNo = 0;
2745 assert(NumResults <= NumFixedOperands);
2746 for (unsigned i = NumResults, e = NumFixedOperands; i != e; ++i) {
2747 const Record *OperandNode = InstInfo.Operands[i].Rec;
2748
2749 // If the operand has a default value, do we use it? We must use the
2750 // default if we've run out of children of the pattern DAG to consume,
2751 // or if the operand is followed by a non-defaulted one.
2752 if (CDP.operandHasDefault(Op: OperandNode) &&
2753 (i < NonOverridableOperands || ChildNo >= getNumChildren()))
2754 continue;
2755
2756 // If we have run out of child nodes and there _isn't_ a default
2757 // value we can use for the next operand, give an error.
2758 if (ChildNo >= getNumChildren()) {
2759 emitTooFewOperandsError(TP, InstName: getOperator()->getName(), Actual: getNumChildren());
2760 return false;
2761 }
2762
2763 TreePatternNode *Child = &getChild(N: ChildNo++);
2764 unsigned ChildResNo = 0; // Instructions always use res #0 of their op.
2765
2766 // If the operand has sub-operands, they may be provided by distinct
2767 // child patterns, so attempt to match each sub-operand separately.
2768 if (OperandNode->isSubClassOf(Name: "Operand")) {
2769 const DagInit *MIOpInfo = OperandNode->getValueAsDag(FieldName: "MIOperandInfo");
2770 if (unsigned NumArgs = MIOpInfo->getNumArgs()) {
2771 // But don't do that if the whole operand is being provided by
2772 // a single ComplexPattern-related Operand.
2773
2774 if (Child->getNumMIResults(CGP: CDP) < NumArgs) {
2775 // Match first sub-operand against the child we already have.
2776 const Record *SubRec = cast<DefInit>(Val: MIOpInfo->getArg(Num: 0))->getDef();
2777 MadeChange |= Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: SubRec, TP);
2778
2779 // And the remaining sub-operands against subsequent children.
2780 for (unsigned Arg = 1; Arg < NumArgs; ++Arg) {
2781 if (ChildNo >= getNumChildren()) {
2782 emitTooFewOperandsError(TP, InstName: getOperator()->getName(),
2783 Actual: getNumChildren());
2784 return false;
2785 }
2786 Child = &getChild(N: ChildNo++);
2787
2788 SubRec = cast<DefInit>(Val: MIOpInfo->getArg(Num: Arg))->getDef();
2789 MadeChange |=
2790 Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: SubRec, TP);
2791 }
2792 continue;
2793 }
2794 }
2795 }
2796
2797 // If we didn't match by pieces above, attempt to match the whole
2798 // operand now.
2799 MadeChange |= Child->UpdateNodeTypeFromInst(ResNo: ChildResNo, Operand: OperandNode, TP);
2800 }
2801
2802 if (!InstInfo.Operands.isVariadic && ChildNo != getNumChildren()) {
2803 emitTooManyOperandsError(TP, InstName: getOperator()->getName(), Expected: ChildNo,
2804 Actual: getNumChildren());
2805 return false;
2806 }
2807
2808 for (TreePatternNode &Child : children())
2809 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2810 return MadeChange;
2811 }
2812
2813 if (getOperator()->isSubClassOf(Name: "ComplexPattern")) {
2814 bool MadeChange = false;
2815
2816 if (!NotRegisters) {
2817 assert(Types.size() == 1 && "ComplexPatterns only produce one result!");
2818 const Record *T = CDP.getComplexPattern(R: getOperator()).getValueType();
2819 const CodeGenHwModes &CGH = CDP.getTargetInfo().getHwModes();
2820 const ValueTypeByHwMode VVT = getValueTypeByHwMode(Rec: T, CGH);
2821 // TODO: AArch64 and AMDGPU use ComplexPattern<untyped, ...> and then
2822 // exclusively use those as non-leaf nodes with explicit type casts, so
2823 // for backwards compatibility we do no inference in that case. This is
2824 // not supported when the ComplexPattern is used as a leaf value,
2825 // however; this inconsistency should be resolved, either by adding this
2826 // case there or by altering the backends to not do this (e.g. using Any
2827 // instead may work).
2828 if (!VVT.isSimple() || VVT.getSimple() != MVT::Untyped)
2829 MadeChange |= UpdateNodeType(ResNo: 0, InTy: VVT, TP);
2830 }
2831
2832 for (TreePatternNode &Child : children())
2833 MadeChange |= Child.ApplyTypeConstraints(TP, NotRegisters);
2834
2835 return MadeChange;
2836 }
2837
2838 if (!getOperator()->isSubClassOf(Name: "SDNodeXForm")) {
2839 TP.error(Msg: "unknown node type '" + getOperator()->getName() +
2840 "' in input pattern");
2841 return false;
2842 }
2843
2844 // Node transforms always take one operand.
2845 if (getNumChildren() != 1) {
2846 TP.error(Msg: "Node transform '" + getOperator()->getName() +
2847 "' requires one operand!");
2848 return false;
2849 }
2850
2851 bool MadeChange = getChild(N: 0).ApplyTypeConstraints(TP, NotRegisters);
2852 return MadeChange;
2853}
2854
2855/// OnlyOnRHSOfCommutative - Return true if this value is only allowed on the
2856/// RHS of a commutative operation, not the on LHS.
2857static bool OnlyOnRHSOfCommutative(const TreePatternNode &N) {
2858 if (!N.isLeaf() && N.getOperator()->getName() == "imm")
2859 return true;
2860 if (N.isLeaf() && isa<IntInit>(Val: N.getLeafValue()))
2861 return true;
2862 if (isImmAllOnesAllZerosMatch(P: N))
2863 return true;
2864 return false;
2865}
2866
2867/// canPatternMatch - If it is impossible for this pattern to match on this
2868/// target, fill in Reason and return false. Otherwise, return true. This is
2869/// used as a sanity check for .td files (to prevent people from writing stuff
2870/// that can never possibly work), and to prevent the pattern permuter from
2871/// generating stuff that is useless.
2872bool TreePatternNode::canPatternMatch(std::string &Reason,
2873 const CodeGenDAGPatterns &CDP) const {
2874 if (isLeaf())
2875 return true;
2876
2877 for (const TreePatternNode &Child : children())
2878 if (!Child.canPatternMatch(Reason, CDP))
2879 return false;
2880
2881 // If this is an intrinsic, handle cases that would make it not match. For
2882 // example, if an operand is required to be an immediate.
2883 if (getOperator()->isSubClassOf(Name: "Intrinsic")) {
2884 // TODO:
2885 return true;
2886 }
2887
2888 if (getOperator()->isSubClassOf(Name: "ComplexPattern"))
2889 return true;
2890
2891 // If this node is a commutative operator, check that the LHS isn't an
2892 // immediate.
2893 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(R: getOperator());
2894 bool isCommIntrinsic = isCommutativeIntrinsic(CDP);
2895 if (NodeInfo.hasProperty(Prop: SDNPCommutative) || isCommIntrinsic) {
2896 // Scan all of the operands of the node and make sure that only the last one
2897 // is a constant node, unless the RHS also is.
2898 if (!OnlyOnRHSOfCommutative(N: getChild(N: getNumChildren() - 1))) {
2899 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
2900 for (unsigned i = Skip, e = getNumChildren() - 1; i != e; ++i)
2901 if (OnlyOnRHSOfCommutative(N: getChild(N: i))) {
2902 Reason =
2903 "Immediate value must be on the RHS of commutative operators!";
2904 return false;
2905 }
2906 }
2907 }
2908
2909 return true;
2910}
2911
2912//===----------------------------------------------------------------------===//
2913// TreePattern implementation
2914//
2915
2916TreePattern::TreePattern(const Record *TheRec, const ListInit *RawPat,
2917 bool isInput, CodeGenDAGPatterns &cdp)
2918 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2919 Infer(*this) {
2920 for (const Init *I : RawPat->getElements()) {
2921 TreePatternNodePtr Node = ParseTreePattern(DI: I, OpName: "");
2922 if (!Node)
2923 return;
2924 Trees.push_back(x: Node);
2925 }
2926}
2927
2928TreePattern::TreePattern(const Record *TheRec, const DagInit *Pat, bool isInput,
2929 CodeGenDAGPatterns &cdp)
2930 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2931 Infer(*this) {
2932 TreePatternNodePtr Node = ParseTreePattern(DI: Pat, OpName: "");
2933 if (!Node)
2934 return;
2935 Trees.push_back(x: Node);
2936}
2937
2938TreePattern::TreePattern(const Record *TheRec, ArrayRef<const Init *> Args,
2939 ArrayRef<const StringInit *> ArgNames, bool isInput,
2940 CodeGenDAGPatterns &cdp)
2941 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2942 Infer(*this) {
2943 Trees.push_back(x: ParseRootlessTreePattern(Args, ArgNames));
2944}
2945
2946TreePattern::TreePattern(const Record *TheRec, TreePatternNodePtr Pat,
2947 bool isInput, CodeGenDAGPatterns &cdp)
2948 : TheRecord(TheRec), CDP(cdp), isInputPattern(isInput), HasError(false),
2949 Infer(*this) {
2950 Trees.push_back(x: Pat);
2951}
2952
2953void TreePattern::error(const Twine &Msg) {
2954 if (HasError)
2955 return;
2956 dump();
2957 PrintError(ErrorLoc: TheRecord->getLoc(), Msg: "In " + TheRecord->getName() + ": " + Msg);
2958 HasError = true;
2959}
2960
2961void TreePattern::ComputeNamedNodes() {
2962 for (TreePatternNodePtr &Tree : Trees)
2963 ComputeNamedNodes(N&: *Tree);
2964}
2965
2966void TreePattern::ComputeNamedNodes(TreePatternNode &N) {
2967 if (!N.getName().empty())
2968 NamedNodes[N.getName()].push_back(Elt: &N);
2969
2970 for (TreePatternNode &Child : N.children())
2971 ComputeNamedNodes(N&: Child);
2972}
2973
2974TreePatternNodePtr
2975TreePattern::ParseRootlessTreePattern(ArrayRef<const Init *> Args,
2976 ArrayRef<const StringInit *> ArgNames) {
2977 std::vector<TreePatternNodePtr> Children;
2978
2979 for (auto [Arg, ArgName] : llvm::zip_equal(t&: Args, u&: ArgNames)) {
2980 StringRef NameStr = ArgName ? ArgName->getValue() : "";
2981 Children.push_back(x: ParseTreePattern(DI: Arg, OpName: NameStr));
2982 }
2983
2984 return makeIntrusiveRefCnt<TreePatternNode>(A: nullptr, A: std::move(Children), A: 1);
2985}
2986
2987TreePatternNodePtr TreePattern::ParseTreePattern(const Init *TheInit,
2988 StringRef OpName) {
2989 RecordKeeper &RK = TheInit->getRecordKeeper();
2990 // Here, we are creating new records (BitsInit->InitInit), so const_cast
2991 // TheInit back to non-const pointer.
2992 if (const DefInit *DI = dyn_cast<DefInit>(Val: TheInit)) {
2993 const Record *R = DI->getDef();
2994
2995 // Direct reference to a leaf DagNode or PatFrag? Turn it into a
2996 // TreePatternNode of its own. For example:
2997 /// (foo GPR, imm) -> (foo GPR, (imm))
2998 if (R->isSubClassOf(Name: "SDNode") || R->isSubClassOf(Name: "PatFrags"))
2999 return ParseTreePattern(TheInit: DagInit::get(V: DI, ArgAndNames: {}), OpName);
3000
3001 // Input argument?
3002 TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(A&: DI, A: 1);
3003 if (R->getName() == "node" && !OpName.empty()) {
3004 if (OpName.empty())
3005 error(Msg: "'node' argument requires a name to match with operand list");
3006 Args.push_back(x: OpName.str());
3007 }
3008
3009 Res->setName(OpName);
3010 return Res;
3011 }
3012
3013 // ?:$name or just $name.
3014 if (isa<UnsetInit>(Val: TheInit)) {
3015 if (OpName.empty())
3016 error(Msg: "'?' argument requires a name to match with operand list");
3017 TreePatternNodePtr Res = makeIntrusiveRefCnt<TreePatternNode>(A&: TheInit, A: 1);
3018 Args.push_back(x: OpName.str());
3019 Res->setName(OpName);
3020 return Res;
3021 }
3022
3023 if (isa<IntInit>(Val: TheInit) || isa<BitInit>(Val: TheInit)) {
3024 if (!OpName.empty())
3025 error(Msg: "Constant int or bit argument should not have a name!");
3026 if (isa<BitInit>(Val: TheInit))
3027 TheInit = TheInit->convertInitializerTo(Ty: IntRecTy::get(RK));
3028 return makeIntrusiveRefCnt<TreePatternNode>(A&: TheInit, A: 1);
3029 }
3030
3031 if (const BitsInit *BI = dyn_cast<BitsInit>(Val: TheInit)) {
3032 // Turn this into an IntInit.
3033 const Init *II = BI->convertInitializerTo(Ty: IntRecTy::get(RK));
3034 if (!II || !isa<IntInit>(Val: II))
3035 error(Msg: "Bits value must be constants!");
3036 return II ? ParseTreePattern(TheInit: II, OpName) : nullptr;
3037 }
3038
3039 const DagInit *Dag = dyn_cast<DagInit>(Val: TheInit);
3040 if (!Dag) {
3041 TheInit->print(OS&: errs());
3042 error(Msg: "Pattern has unexpected init kind!");
3043 return nullptr;
3044 }
3045
3046 auto ParseCastOperand = [this](const DagInit *Dag,
3047 StringRef OpName) -> TreePatternNodePtr {
3048 if (Dag->getNumArgs() != 1) {
3049 error(Msg: "Type cast only takes one operand!");
3050 return nullptr;
3051 }
3052
3053 if (!OpName.empty()) {
3054 error(Msg: "Type cast should not have a name!");
3055 return nullptr;
3056 }
3057
3058 return ParseTreePattern(TheInit: Dag->getArg(Num: 0), OpName: Dag->getArgNameStr(Num: 0));
3059 };
3060
3061 if (const ListInit *LI = dyn_cast<ListInit>(Val: Dag->getOperator())) {
3062 // If the operator is a list (of value types), then this must be "type cast"
3063 // of a leaf node with multiple results.
3064 TreePatternNodePtr New = ParseCastOperand(Dag, OpName);
3065 if (!New)
3066 return nullptr;
3067
3068 size_t NumTypes = New->getNumTypes();
3069 if (LI->empty() || LI->size() != NumTypes)
3070 error(Msg: "Invalid number of type casts!");
3071
3072 // Apply the type casts.
3073 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
3074 for (unsigned i = 0; i < std::min(a: NumTypes, b: LI->size()); ++i)
3075 New->UpdateNodeType(
3076 ResNo: i, InTy: getValueTypeByHwMode(Rec: LI->getElementAsRecord(Idx: i), CGH), TP&: *this);
3077
3078 return New;
3079 }
3080
3081 const DefInit *OpDef = dyn_cast<DefInit>(Val: Dag->getOperator());
3082 if (!OpDef) {
3083 error(Msg: "Pattern has unexpected operator type!");
3084 return nullptr;
3085 }
3086 const Record *Operator = OpDef->getDef();
3087
3088 if (Operator->isSubClassOf(Name: "ValueType")) {
3089 // If the operator is a ValueType, then this must be "type cast" of a leaf
3090 // node.
3091 TreePatternNodePtr New = ParseCastOperand(Dag, OpName);
3092 if (!New)
3093 return nullptr;
3094
3095 if (New->getNumTypes() != 1)
3096 error(Msg: "ValueType cast can only have one type!");
3097
3098 // Apply the type cast.
3099 const CodeGenHwModes &CGH = getDAGPatterns().getTargetInfo().getHwModes();
3100 New->UpdateNodeType(ResNo: 0, InTy: getValueTypeByHwMode(Rec: Operator, CGH), TP&: *this);
3101
3102 return New;
3103 }
3104
3105 // Verify that this is something that makes sense for an operator.
3106 if (!Operator->isSubClassOf(Name: "PatFrags") &&
3107 !Operator->isSubClassOf(Name: "SDNode") &&
3108 !Operator->isSubClassOf(Name: "Instruction") &&
3109 !Operator->isSubClassOf(Name: "SDNodeXForm") &&
3110 !Operator->isSubClassOf(Name: "Intrinsic") &&
3111 !Operator->isSubClassOf(Name: "ComplexPattern") && Operator->getName() != "set")
3112 error(Msg: "Unrecognized node '" + Operator->getName() + "'!");
3113
3114 // Check to see if this is something that is illegal in an input pattern.
3115 if (isInputPattern) {
3116 if (Operator->isSubClassOf(Name: "Instruction") ||
3117 Operator->isSubClassOf(Name: "SDNodeXForm"))
3118 error(Msg: "Cannot use '" + Operator->getName() + "' in an input pattern!");
3119 } else {
3120 if (Operator->isSubClassOf(Name: "Intrinsic"))
3121 error(Msg: "Cannot use '" + Operator->getName() + "' in an output pattern!");
3122
3123 if (Operator->isSubClassOf(Name: "SDNode") && Operator->getName() != "imm" &&
3124 Operator->getName() != "timm" && Operator->getName() != "fpimm" &&
3125 Operator->getName() != "tglobaltlsaddr" &&
3126 Operator->getName() != "tconstpool" &&
3127 Operator->getName() != "tjumptable" &&
3128 Operator->getName() != "tframeindex" &&
3129 Operator->getName() != "texternalsym" &&
3130 Operator->getName() != "tblockaddress" &&
3131 Operator->getName() != "tglobaladdr" && Operator->getName() != "bb" &&
3132 Operator->getName() != "vt" && Operator->getName() != "mcsym")
3133 error(Msg: "Cannot use '" + Operator->getName() + "' in an output pattern!");
3134 }
3135
3136 std::vector<TreePatternNodePtr> Children;
3137
3138 // Parse all the operands.
3139 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
3140 TreePatternNodePtr Child =
3141 ParseTreePattern(TheInit: Dag->getArg(Num: i), OpName: Dag->getArgNameStr(Num: i));
3142 if (!Child)
3143 return nullptr;
3144 Children.push_back(x: Child);
3145 }
3146
3147 // Get the actual number of results before Operator is converted to an
3148 // intrinsic node (which is hard-coded to have either zero or one result).
3149 unsigned NumResults = GetNumNodeResults(Operator, CDP);
3150
3151 // If the operator is an intrinsic, then this is just syntactic sugar for
3152 // (intrinsic_* <number>, ..children..). Pick the right intrinsic node, and
3153 // convert the intrinsic name to a number.
3154 if (Operator->isSubClassOf(Name: "Intrinsic")) {
3155 const CodeGenIntrinsic &Int = getDAGPatterns().getIntrinsic(R: Operator);
3156 unsigned IID = getDAGPatterns().getIntrinsicID(R: Operator) + 1;
3157
3158 // If this intrinsic returns void, it must have side-effects and thus a
3159 // chain.
3160 if (Int.IS.RetTys.empty())
3161 Operator = getDAGPatterns().get_intrinsic_void_sdnode();
3162 else if (!Int.ME.doesNotAccessMemory() || Int.hasSideEffects)
3163 // Has side-effects, requires chain.
3164 Operator = getDAGPatterns().get_intrinsic_w_chain_sdnode();
3165 else // Otherwise, no chain.
3166 Operator = getDAGPatterns().get_intrinsic_wo_chain_sdnode();
3167
3168 Children.insert(position: Children.begin(), x: makeIntrusiveRefCnt<TreePatternNode>(
3169 A: IntInit::get(RK, V: IID), A: 1));
3170 }
3171
3172 if (Operator->isSubClassOf(Name: "ComplexPattern")) {
3173 for (unsigned i = 0; i < Children.size(); ++i) {
3174 TreePatternNodePtr Child = Children[i];
3175
3176 if (Child->getName().empty())
3177 error(Msg: "All arguments to a ComplexPattern must be named");
3178
3179 // Check that the ComplexPattern uses are consistent: "(MY_PAT $a, $b)"
3180 // and "(MY_PAT $b, $a)" should not be allowed in the same pattern;
3181 // neither should "(MY_PAT_1 $a, $b)" and "(MY_PAT_2 $a, $b)".
3182 auto OperandId = std::pair(Operator, i);
3183 auto [PrevOp, Inserted] =
3184 ComplexPatternOperands.try_emplace(Key: Child->getName(), Args&: OperandId);
3185 if (!Inserted && PrevOp->getValue() != OperandId) {
3186 error(Msg: "All ComplexPattern operands must appear consistently: "
3187 "in the same order in just one ComplexPattern instance.");
3188 }
3189 }
3190 }
3191
3192 TreePatternNodePtr Result = makeIntrusiveRefCnt<TreePatternNode>(
3193 A&: Operator, A: std::move(Children), A&: NumResults);
3194 Result->setName(OpName);
3195
3196 if (Dag->getName()) {
3197 assert(Result->getName().empty());
3198 Result->setName(Dag->getNameStr());
3199 }
3200 return Result;
3201}
3202
3203/// SimplifyTree - See if we can simplify this tree to eliminate something that
3204/// will never match in favor of something obvious that will. This is here
3205/// strictly as a convenience to target authors because it allows them to write
3206/// more type generic things and have useless type casts fold away.
3207///
3208/// This returns true if any change is made.
3209static bool SimplifyTree(TreePatternNodePtr &N) {
3210 if (N->isLeaf())
3211 return false;
3212
3213 // If we have a bitconvert with a resolved type and if the source and
3214 // destination types are the same, then the bitconvert is useless, remove it.
3215 //
3216 // We make an exception if the types are completely empty. This can come up
3217 // when the pattern being simplified is in the Fragments list of a PatFrags,
3218 // so that the operand is just an untyped "node". In that situation we leave
3219 // bitconverts unsimplified, and simplify them later once the fragment is
3220 // expanded into its true context.
3221 if (N->getOperator()->getName() == "bitconvert" &&
3222 N->getExtType(ResNo: 0).isValueTypeByHwMode(AllowEmpty: false) &&
3223 !N->getExtType(ResNo: 0).empty() &&
3224 N->getExtType(ResNo: 0) == N->getChild(N: 0).getExtType(ResNo: 0) &&
3225 N->getName().empty()) {
3226 if (!N->getPredicateCalls().empty()) {
3227 std::string Str;
3228 raw_string_ostream OS(Str);
3229 OS << *N
3230 << "\n trivial bitconvert node should not have predicate calls\n";
3231 PrintFatalError(Msg: Str);
3232 return false;
3233 }
3234 N = N->getChildShared(N: 0);
3235 SimplifyTree(N);
3236 return true;
3237 }
3238
3239 // Walk all children.
3240 bool MadeChange = false;
3241 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
3242 MadeChange |= SimplifyTree(N&: N->getChildSharedPtr(N: i));
3243
3244 return MadeChange;
3245}
3246
3247/// InferAllTypes - Infer/propagate as many types throughout the expression
3248/// patterns as possible. Return true if all types are inferred, false
3249/// otherwise. Flags an error if a type contradiction is found.
3250bool TreePattern::InferAllTypes(
3251 const StringMap<SmallVector<TreePatternNode *, 1>> *InNamedTypes) {
3252 if (NamedNodes.empty())
3253 ComputeNamedNodes();
3254
3255 bool MadeChange = true;
3256 while (MadeChange) {
3257 MadeChange = false;
3258 for (TreePatternNodePtr &Tree : Trees) {
3259 MadeChange |= Tree->ApplyTypeConstraints(TP&: *this, NotRegisters: false);
3260 MadeChange |= SimplifyTree(N&: Tree);
3261 }
3262
3263 // If there are constraints on our named nodes, apply them.
3264 for (auto &Entry : NamedNodes) {
3265 SmallVectorImpl<TreePatternNode *> &Nodes = Entry.second;
3266
3267 // If we have input named node types, propagate their types to the named
3268 // values here.
3269 if (InNamedTypes) {
3270 auto InIter = InNamedTypes->find(Key: Entry.getKey());
3271 if (InIter == InNamedTypes->end()) {
3272 error(Msg: "Node '" + Entry.getKey().str() +
3273 "' in output pattern but not input pattern");
3274 return true;
3275 }
3276
3277 ArrayRef<TreePatternNode *> InNodes = InIter->second;
3278
3279 // The input types should be fully resolved by now.
3280 for (TreePatternNode *Node : Nodes) {
3281 // If this node is a register class, and it is the root of the pattern
3282 // then we're mapping something onto an input register. We allow
3283 // changing the type of the input register in this case. This allows
3284 // us to match things like:
3285 // def : Pat<(v1i64 (bitconvert(v2i32 DPR:$src))), (v1i64 DPR:$src)>;
3286 if (Node == Trees[0].get() && Node->isLeaf()) {
3287 const DefInit *DI = dyn_cast<DefInit>(Val: Node->getLeafValue());
3288 if (DI && (DI->getDef()->isSubClassOf(Name: "RegisterClass") ||
3289 DI->getDef()->isSubClassOf(Name: "RegisterOperand")))
3290 continue;
3291 }
3292
3293 assert(Node->getNumTypes() == 1 && InNodes[0]->getNumTypes() == 1 &&
3294 "FIXME: cannot name multiple result nodes yet");
3295 MadeChange |=
3296 Node->UpdateNodeType(ResNo: 0, InTy: InNodes[0]->getExtType(ResNo: 0), TP&: *this);
3297 }
3298 }
3299
3300 // If there are multiple nodes with the same name, they must all have the
3301 // same type.
3302 if (Entry.second.size() > 1) {
3303 for (unsigned i = 0, e = Nodes.size() - 1; i != e; ++i) {
3304 TreePatternNode *N1 = Nodes[i], *N2 = Nodes[i + 1];
3305 assert(N1->getNumTypes() == 1 && N2->getNumTypes() == 1 &&
3306 "FIXME: cannot name multiple result nodes yet");
3307
3308 MadeChange |= N1->UpdateNodeType(ResNo: 0, InTy: N2->getExtType(ResNo: 0), TP&: *this);
3309 MadeChange |= N2->UpdateNodeType(ResNo: 0, InTy: N1->getExtType(ResNo: 0), TP&: *this);
3310 }
3311 }
3312 }
3313 }
3314
3315 bool HasUnresolvedTypes = false;
3316 for (const TreePatternNodePtr &Tree : Trees)
3317 HasUnresolvedTypes |= Tree->ContainsUnresolvedType(TP&: *this);
3318 return !HasUnresolvedTypes;
3319}
3320
3321void TreePattern::print(raw_ostream &OS) const {
3322 OS << getRecord()->getName();
3323 if (!Args.empty())
3324 OS << '(' << llvm::interleaved(R: Args) << ')';
3325 OS << ": ";
3326
3327 if (Trees.size() > 1)
3328 OS << "[\n";
3329 for (const TreePatternNodePtr &Tree : Trees) {
3330 OS << "\t";
3331 Tree->print(OS);
3332 OS << "\n";
3333 }
3334
3335 if (Trees.size() > 1)
3336 OS << "]\n";
3337}
3338
3339void TreePattern::dump() const { print(OS&: dbgs()); }
3340
3341//===----------------------------------------------------------------------===//
3342// CodeGenDAGPatterns implementation
3343//
3344
3345CodeGenDAGPatterns::CodeGenDAGPatterns(const RecordKeeper &R, bool ExpandHwMode)
3346 : Records(R), Target(R), Intrinsics(R),
3347 LegalVTS(Target.getLegalValueTypes()),
3348 LegalPtrVTS(ComputeLegalPtrTypes()) {
3349 IntrinsicIDs.reserve(NumEntries: Intrinsics.size());
3350 for (auto [ID, Intrinsic] : enumerate(First&: Intrinsics))
3351 IntrinsicIDs.try_emplace(Key: Intrinsic.TheDef, Args&: ID);
3352
3353 ParseNodeInfo();
3354 ParseNodeTransforms();
3355 ParseComplexPatterns();
3356 ParsePatternFragments();
3357 ParseDefaultOperands();
3358 ParseInstructions();
3359 ParsePatternFragments(/*OutFrags*/ true);
3360 ParsePatterns();
3361
3362 // Generate variants. For example, commutative patterns can match
3363 // multiple ways. Add them to PatternsToMatch as well.
3364 GenerateVariants();
3365
3366 // Break patterns with parameterized types into a series of patterns,
3367 // where each one has a fixed type and is predicated on the conditions
3368 // of the associated HW mode.
3369 if (ExpandHwMode)
3370 ExpandHwModeBasedTypes();
3371
3372 // Infer instruction flags. For example, we can detect loads,
3373 // stores, and side effects in many cases by examining an
3374 // instruction's pattern.
3375 InferInstructionFlags();
3376
3377 // Verify that instruction flags match the patterns.
3378 VerifyInstructionFlags();
3379}
3380
3381const Record *CodeGenDAGPatterns::getSDNodeNamed(StringRef Name) const {
3382 const Record *N = Records.getDef(Name);
3383 if (!N || !N->isSubClassOf(Name: "SDNode"))
3384 PrintFatalError(Msg: "Error getting SDNode '" + Name + "'!");
3385 return N;
3386}
3387
3388// Compute the subset of iPTR and cPTR legal for each mode, coalescing into the
3389// default mode where possible to avoid predicate explosion.
3390TypeSetByHwMode CodeGenDAGPatterns::ComputeLegalPtrTypes() const {
3391 auto LegalPtrsForSet = [](const MachineValueTypeSet &In) {
3392 MachineValueTypeSet Out;
3393 Out.insert(T: MVT::iPTR);
3394 for (MVT T : MVT::cheri_capability_valuetypes()) {
3395 if (In.count(T)) {
3396 Out.insert(T: MVT::cPTR);
3397 break;
3398 }
3399 }
3400 return Out;
3401 };
3402
3403 const TypeSetByHwMode &LegalTypes = getLegalTypes();
3404 MachineValueTypeSet LegalPtrsDefault =
3405 LegalPtrsForSet(LegalTypes.get(Mode: DefaultMode));
3406
3407 TypeSetByHwMode LegalPtrTypes;
3408 for (const auto &I : LegalTypes) {
3409 MachineValueTypeSet S = LegalPtrsForSet(I.second);
3410 if (I.first != DefaultMode && S == LegalPtrsDefault)
3411 continue;
3412 LegalPtrTypes.getOrCreate(Mode: I.first).insert(S);
3413 }
3414
3415 return LegalPtrTypes;
3416}
3417
3418// Parse all of the SDNode definitions for the target, populating SDNodes.
3419void CodeGenDAGPatterns::ParseNodeInfo() {
3420 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
3421
3422 for (const Record *R : reverse(C: Records.getAllDerivedDefinitions(ClassName: "SDNode")))
3423 SDNodes.try_emplace(k: R, args: SDNodeInfo(R, CGH));
3424
3425 // Get the builtin intrinsic nodes.
3426 intrinsic_void_sdnode = getSDNodeNamed(Name: "intrinsic_void");
3427 intrinsic_w_chain_sdnode = getSDNodeNamed(Name: "intrinsic_w_chain");
3428 intrinsic_wo_chain_sdnode = getSDNodeNamed(Name: "intrinsic_wo_chain");
3429}
3430
3431/// ParseNodeTransforms - Parse all SDNodeXForm instances into the SDNodeXForms
3432/// map, and emit them to the file as functions.
3433void CodeGenDAGPatterns::ParseNodeTransforms() {
3434 for (const Record *XFormNode :
3435 reverse(C: Records.getAllDerivedDefinitions(ClassName: "SDNodeXForm"))) {
3436 const Record *SDNode = XFormNode->getValueAsDef(FieldName: "Opcode");
3437 StringRef Code = XFormNode->getValueAsString(FieldName: "XFormFunction");
3438 SDNodeXForms.try_emplace(k: XFormNode, args: NodeXForm(SDNode, Code.str()));
3439 }
3440}
3441
3442void CodeGenDAGPatterns::ParseComplexPatterns() {
3443 for (const Record *R :
3444 reverse(C: Records.getAllDerivedDefinitions(ClassName: "ComplexPattern")))
3445 ComplexPatterns.try_emplace(k: R, args&: R);
3446}
3447
3448/// ParsePatternFragments - Parse all of the PatFrag definitions in the .td
3449/// file, building up the PatternFragments map. After we've collected them all,
3450/// inline fragments together as necessary, so that there are no references left
3451/// inside a pattern fragment to a pattern fragment.
3452///
3453void CodeGenDAGPatterns::ParsePatternFragments(bool OutFrags) {
3454 // First step, parse all of the fragments.
3455 ArrayRef<const Record *> Fragments =
3456 Records.getAllDerivedDefinitions(ClassName: "PatFrags");
3457 for (const Record *Frag : Fragments) {
3458 if (OutFrags != Frag->isSubClassOf(Name: "OutPatFrag"))
3459 continue;
3460
3461 const ListInit *LI = Frag->getValueAsListInit(FieldName: "Fragments");
3462 TreePattern *P = (PatternFragments[Frag] = std::make_unique<TreePattern>(
3463 args&: Frag, args&: LI, args: !Frag->isSubClassOf(Name: "OutPatFrag"), args&: *this))
3464 .get();
3465
3466 // Validate the argument list, converting it to set, to discard duplicates.
3467 std::vector<std::string> &Args = P->getArgList();
3468 // Copy the args so we can take StringRefs to them.
3469 auto ArgsCopy = Args;
3470 SmallDenseSet<StringRef, 4> OperandsSet(llvm::from_range, ArgsCopy);
3471
3472 if (OperandsSet.contains(V: ""))
3473 P->error(Msg: "Cannot have unnamed 'node' values in pattern fragment!");
3474
3475 // Parse the operands list.
3476 const DagInit *OpsList = Frag->getValueAsDag(FieldName: "Operands");
3477 const DefInit *OpsOp = dyn_cast<DefInit>(Val: OpsList->getOperator());
3478 // Special cases: ops == outs == ins. Different names are used to
3479 // improve readability.
3480 if (!OpsOp || (OpsOp->getDef()->getName() != "ops" &&
3481 OpsOp->getDef()->getName() != "outs" &&
3482 OpsOp->getDef()->getName() != "ins"))
3483 P->error(Msg: "Operands list should start with '(ops ... '!");
3484
3485 // Copy over the arguments.
3486 Args.clear();
3487 for (unsigned j = 0, e = OpsList->getNumArgs(); j != e; ++j) {
3488 if (!isa<DefInit>(Val: OpsList->getArg(Num: j)) ||
3489 cast<DefInit>(Val: OpsList->getArg(Num: j))->getDef()->getName() != "node")
3490 P->error(Msg: "Operands list should all be 'node' values.");
3491 if (!OpsList->getArgName(Num: j))
3492 P->error(Msg: "Operands list should have names for each operand!");
3493 StringRef ArgNameStr = OpsList->getArgNameStr(Num: j);
3494 if (!OperandsSet.erase(V: ArgNameStr))
3495 P->error(Msg: "'" + ArgNameStr +
3496 "' does not occur in pattern or was multiply specified!");
3497 Args.push_back(x: ArgNameStr.str());
3498 }
3499
3500 if (!OperandsSet.empty())
3501 P->error(Msg: "Operands list does not contain an entry for operand '" +
3502 *OperandsSet.begin() + "'!");
3503
3504 // If there is a node transformation corresponding to this, keep track of
3505 // it.
3506 const Record *Transform = Frag->getValueAsDef(FieldName: "OperandTransform");
3507 if (!getSDNodeTransform(R: Transform).second.empty()) // not noop xform?
3508 for (const auto &T : P->getTrees())
3509 T->setTransformFn(Transform);
3510 }
3511
3512 // Now that we've parsed all of the tree fragments, do a closure on them so
3513 // that there are not references to PatFrags left inside of them.
3514 for (const Record *Frag : Fragments) {
3515 if (OutFrags != Frag->isSubClassOf(Name: "OutPatFrag"))
3516 continue;
3517
3518 TreePattern &ThePat = *PatternFragments[Frag];
3519 ThePat.InlinePatternFragments();
3520
3521 // Infer as many types as possible. Don't worry about it if we don't infer
3522 // all of them, some may depend on the inputs of the pattern. Also, don't
3523 // validate type sets; validation may cause spurious failures e.g. if a
3524 // fragment needs floating-point types but the current target does not have
3525 // any (this is only an error if that fragment is ever used!).
3526 {
3527 TypeInfer::SuppressValidation SV(ThePat.getInfer());
3528 ThePat.InferAllTypes();
3529 ThePat.resetError();
3530 }
3531
3532 // If debugging, print out the pattern fragment result.
3533 LLVM_DEBUG(ThePat.dump());
3534 }
3535}
3536
3537void CodeGenDAGPatterns::ParseDefaultOperands() {
3538 ArrayRef<const Record *> DefaultOps =
3539 Records.getAllDerivedDefinitions(ClassName: "OperandWithDefaultOps");
3540
3541 for (unsigned i = 0, e = DefaultOps.size(); i != e; ++i) {
3542 const DagInit *DefaultInfo = DefaultOps[i]->getValueAsDag(FieldName: "DefaultOps");
3543
3544 // Create a TreePattern to parse this.
3545 TreePattern P(DefaultOps[i], DefaultInfo->getArgs(),
3546 DefaultInfo->getArgNames(), false, *this);
3547 assert(P.getNumTrees() == 1 && "This ctor can only produce one tree!");
3548
3549 // Copy the operands over into a DAGDefaultOperand.
3550 DAGDefaultOperand DefaultOpInfo;
3551
3552 const TreePatternNodePtr &T = P.getTree(i: 0);
3553 for (unsigned op = 0, e = T->getNumChildren(); op != e; ++op) {
3554 TreePatternNodePtr TPN = T->getChildShared(N: op);
3555 while (TPN->ApplyTypeConstraints(TP&: P, NotRegisters: false))
3556 /* Resolve all types */;
3557
3558 if (TPN->ContainsUnresolvedType(TP&: P)) {
3559 PrintFatalError(Msg: "Value #" + Twine(i) + " of OperandWithDefaultOps '" +
3560 DefaultOps[i]->getName() +
3561 "' doesn't have a concrete type!");
3562 }
3563 DefaultOpInfo.DefaultOps.push_back(x: std::move(TPN));
3564 }
3565
3566 // Insert it into the DefaultOperands map so we can find it later.
3567 DefaultOperands[DefaultOps[i]] = DefaultOpInfo;
3568 }
3569}
3570
3571/// HandleUse - Given "Pat" a leaf in the pattern, check to see if it is an
3572/// instruction input. Return true if this is a real use.
3573static bool HandleUse(TreePattern &I, TreePatternNodePtr Pat,
3574 std::map<StringRef, TreePatternNodePtr> &InstInputs) {
3575 // No name -> not interesting.
3576 if (Pat->getName().empty()) {
3577 if (Pat->isLeaf()) {
3578 const DefInit *DI = dyn_cast<DefInit>(Val: Pat->getLeafValue());
3579 if (DI && (DI->getDef()->isSubClassOf(Name: "RegisterClass") ||
3580 DI->getDef()->isSubClassOf(Name: "RegisterOperand")))
3581 I.error(Msg: "Input " + DI->getDef()->getName() + " must be named!");
3582 }
3583 return false;
3584 }
3585
3586 const Record *Rec;
3587 if (Pat->isLeaf()) {
3588 const DefInit *DI = dyn_cast<DefInit>(Val: Pat->getLeafValue());
3589 if (!DI) {
3590 I.error(Msg: "Input $" + Pat->getName() + " must be an identifier!");
3591 return false;
3592 }
3593 Rec = DI->getDef();
3594 } else {
3595 Rec = Pat->getOperator();
3596 }
3597
3598 // SRCVALUE nodes are ignored.
3599 if (Rec->getName() == "srcvalue")
3600 return false;
3601
3602 TreePatternNodePtr &Slot = InstInputs[Pat->getName()];
3603 if (!Slot) {
3604 Slot = Pat;
3605 return true;
3606 }
3607 const Record *SlotRec;
3608 if (Slot->isLeaf()) {
3609 SlotRec = cast<DefInit>(Val: Slot->getLeafValue())->getDef();
3610 } else {
3611 assert(Slot->getNumChildren() == 0 && "can't be a use with children!");
3612 SlotRec = Slot->getOperator();
3613 }
3614
3615 // Ensure that the inputs agree if we've already seen this input.
3616 if (Rec != SlotRec)
3617 I.error(Msg: "All $" + Pat->getName() + " inputs must agree with each other");
3618 // Ensure that the types can agree as well.
3619 Slot->UpdateNodeType(ResNo: 0, InTy: Pat->getExtType(ResNo: 0), TP&: I);
3620 Pat->UpdateNodeType(ResNo: 0, InTy: Slot->getExtType(ResNo: 0), TP&: I);
3621 if (Slot->getExtTypes() != Pat->getExtTypes())
3622 I.error(Msg: "All $" + Pat->getName() + " inputs must agree with each other");
3623 return true;
3624}
3625
3626/// FindPatternInputsAndOutputs - Scan the specified TreePatternNode (which is
3627/// part of "I", the instruction), computing the set of inputs and outputs of
3628/// the pattern. Report errors if we see anything naughty.
3629void CodeGenDAGPatterns::FindPatternInputsAndOutputs(
3630 TreePattern &I, TreePatternNodePtr Pat, InstInputsTy &InstInputs,
3631 InstResultsTy &InstResults, std::vector<const Record *> &InstImpResults) {
3632 // The instruction pattern still has unresolved fragments. For *named*
3633 // nodes we must resolve those here. This may not result in multiple
3634 // alternatives.
3635 if (!Pat->getName().empty()) {
3636 TreePattern SrcPattern(I.getRecord(), Pat, true, *this);
3637 SrcPattern.InlinePatternFragments();
3638 SrcPattern.InferAllTypes();
3639 Pat = SrcPattern.getOnlyTree();
3640 }
3641
3642 if (Pat->isLeaf()) {
3643 bool isUse = HandleUse(I, Pat, InstInputs);
3644 if (!isUse && Pat->getTransformFn())
3645 I.error(Msg: "Cannot specify a transform function for a non-input value!");
3646 return;
3647 }
3648
3649 if (Pat->getOperator()->getName() != "set") {
3650 // If this is not a set, verify that the children nodes are not void typed,
3651 // and recurse.
3652 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i) {
3653 if (Pat->getChild(N: i).getNumTypes() == 0)
3654 I.error(Msg: "Cannot have void nodes inside of patterns!");
3655 FindPatternInputsAndOutputs(I, Pat: Pat->getChildShared(N: i), InstInputs,
3656 InstResults, InstImpResults);
3657 }
3658
3659 // If this is a non-leaf node with no children, treat it basically as if
3660 // it were a leaf. This handles nodes like (imm).
3661 bool isUse = HandleUse(I, Pat, InstInputs);
3662
3663 if (!isUse && Pat->getTransformFn())
3664 I.error(Msg: "Cannot specify a transform function for a non-input value!");
3665 return;
3666 }
3667
3668 // Otherwise, this is a set, validate and collect instruction results.
3669 if (Pat->getNumChildren() == 0)
3670 I.error(Msg: "set requires operands!");
3671
3672 if (Pat->getTransformFn())
3673 I.error(Msg: "Cannot specify a transform function on a set node!");
3674
3675 // Check the set destinations.
3676 unsigned NumDests = Pat->getNumChildren() - 1;
3677 for (unsigned i = 0; i != NumDests; ++i) {
3678 TreePatternNodePtr Dest = Pat->getChildShared(N: i);
3679 // For set destinations we also must resolve fragments here.
3680 TreePattern DestPattern(I.getRecord(), Dest, false, *this);
3681 DestPattern.InlinePatternFragments();
3682 DestPattern.InferAllTypes();
3683 Dest = DestPattern.getOnlyTree();
3684
3685 if (!Dest->isLeaf())
3686 I.error(Msg: "set destination should be a register!");
3687
3688 const DefInit *Val = dyn_cast<DefInit>(Val: Dest->getLeafValue());
3689 if (!Val) {
3690 I.error(Msg: "set destination should be a register!");
3691 continue;
3692 }
3693
3694 if (Val->getDef()->isSubClassOf(Name: "RegisterClassLike") ||
3695 Val->getDef()->isSubClassOf(Name: "ValueType") ||
3696 Val->getDef()->isSubClassOf(Name: "RegisterOperand")) {
3697 if (Dest->getName().empty())
3698 I.error(Msg: "set destination must have a name!");
3699 if (!InstResults.insert_or_assign(Key: Dest->getName(), Val&: Dest).second)
3700 I.error(Msg: "cannot set '" + Dest->getName() + "' multiple times");
3701 } else if (Val->getDef()->isSubClassOf(Name: "Register")) {
3702 InstImpResults.push_back(x: Val->getDef());
3703 } else {
3704 I.error(Msg: "set destination should be a register!");
3705 }
3706 }
3707
3708 // Verify and collect info from the computation.
3709 FindPatternInputsAndOutputs(I, Pat: Pat->getChildShared(N: NumDests), InstInputs,
3710 InstResults, InstImpResults);
3711}
3712
3713//===----------------------------------------------------------------------===//
3714// Instruction Analysis
3715//===----------------------------------------------------------------------===//
3716
3717class InstAnalyzer {
3718 const CodeGenDAGPatterns &CDP;
3719
3720public:
3721 bool hasSideEffects = false;
3722 bool mayStore = false;
3723 bool mayLoad = false;
3724 bool isBitcast = false;
3725 bool isVariadic = false;
3726 bool hasChain = false;
3727
3728 InstAnalyzer(const CodeGenDAGPatterns &cdp) : CDP(cdp) {}
3729
3730 void Analyze(const PatternToMatch &Pat) {
3731 const TreePatternNode &N = Pat.getSrcPattern();
3732 AnalyzeNode(N);
3733 // These properties are detected only on the root node.
3734 isBitcast = IsNodeBitcast(N);
3735 }
3736
3737private:
3738 bool IsNodeBitcast(const TreePatternNode &N) const {
3739 if (hasSideEffects || mayLoad || mayStore || isVariadic)
3740 return false;
3741
3742 if (N.isLeaf())
3743 return false;
3744 if (N.getNumChildren() != 1 || !N.getChild(N: 0).isLeaf())
3745 return false;
3746
3747 if (N.getOperator()->isSubClassOf(Name: "ComplexPattern"))
3748 return false;
3749
3750 const SDNodeInfo &OpInfo = CDP.getSDNodeInfo(R: N.getOperator());
3751 if (OpInfo.getNumResults() != 1 || OpInfo.getNumOperands() != 1)
3752 return false;
3753 return OpInfo.getEnumName() == "ISD::BITCAST";
3754 }
3755
3756public:
3757 void AnalyzeNode(const TreePatternNode &N) {
3758 if (N.isLeaf()) {
3759 if (const DefInit *DI = dyn_cast<DefInit>(Val: N.getLeafValue())) {
3760 const Record *LeafRec = DI->getDef();
3761 // Handle ComplexPattern leaves.
3762 if (LeafRec->isSubClassOf(Name: "ComplexPattern")) {
3763 const ComplexPattern &CP = CDP.getComplexPattern(R: LeafRec);
3764 if (CP.hasProperty(Prop: SDNPMayStore))
3765 mayStore = true;
3766 if (CP.hasProperty(Prop: SDNPMayLoad))
3767 mayLoad = true;
3768 if (CP.hasProperty(Prop: SDNPSideEffect))
3769 hasSideEffects = true;
3770 }
3771 }
3772 return;
3773 }
3774
3775 // Analyze children.
3776 for (const TreePatternNode &Child : N.children())
3777 AnalyzeNode(N: Child);
3778
3779 // Notice properties of the node.
3780 if (N.NodeHasProperty(Property: SDNPMayStore, CGP: CDP))
3781 mayStore = true;
3782 if (N.NodeHasProperty(Property: SDNPMayLoad, CGP: CDP))
3783 mayLoad = true;
3784 if (N.NodeHasProperty(Property: SDNPSideEffect, CGP: CDP))
3785 hasSideEffects = true;
3786 if (N.NodeHasProperty(Property: SDNPVariadic, CGP: CDP))
3787 isVariadic = true;
3788 if (N.NodeHasProperty(Property: SDNPHasChain, CGP: CDP))
3789 hasChain = true;
3790
3791 if (const CodeGenIntrinsic *IntInfo = N.getIntrinsicInfo(CDP)) {
3792 ModRefInfo MR = IntInfo->ME.getModRef();
3793 // If this is an intrinsic, analyze it.
3794 if (isRefSet(MRI: MR))
3795 mayLoad = true; // These may load memory.
3796
3797 if (isModSet(MRI: MR))
3798 mayStore = true; // Intrinsics that can write to memory are 'mayStore'.
3799
3800 // Consider intrinsics that don't specify any restrictions on memory
3801 // effects as having a side-effect.
3802 if (IntInfo->ME == MemoryEffects::unknown() || IntInfo->hasSideEffects)
3803 hasSideEffects = true;
3804 }
3805 }
3806};
3807
3808static bool InferFromPattern(CodeGenInstruction &InstInfo,
3809 const InstAnalyzer &PatInfo,
3810 const Record *PatDef) {
3811 bool Error = false;
3812
3813 // Remember where InstInfo got its flags.
3814 if (InstInfo.hasUndefFlags())
3815 InstInfo.InferredFrom = PatDef;
3816
3817 // Check explicitly set flags for consistency.
3818 if (InstInfo.hasSideEffects != PatInfo.hasSideEffects &&
3819 !InstInfo.hasSideEffects_Unset) {
3820 // Allow explicitly setting hasSideEffects = 1 on instructions, even when
3821 // the pattern has no side effects. That could be useful for div/rem
3822 // instructions that may trap.
3823 if (!InstInfo.hasSideEffects) {
3824 Error = true;
3825 PrintError(ErrorLoc: PatDef->getLoc(), Msg: "Pattern doesn't match hasSideEffects = " +
3826 Twine(InstInfo.hasSideEffects));
3827 }
3828 }
3829
3830 if (InstInfo.mayStore != PatInfo.mayStore && !InstInfo.mayStore_Unset) {
3831 Error = true;
3832 PrintError(ErrorLoc: PatDef->getLoc(),
3833 Msg: "Pattern doesn't match mayStore = " + Twine(InstInfo.mayStore));
3834 }
3835
3836 if (InstInfo.mayLoad != PatInfo.mayLoad && !InstInfo.mayLoad_Unset) {
3837 // Allow explicitly setting mayLoad = 1, even when the pattern has no loads.
3838 // Some targets translate immediates to loads.
3839 if (!InstInfo.mayLoad) {
3840 Error = true;
3841 PrintError(ErrorLoc: PatDef->getLoc(),
3842 Msg: "Pattern doesn't match mayLoad = " + Twine(InstInfo.mayLoad));
3843 }
3844 }
3845
3846 // Transfer inferred flags.
3847 InstInfo.hasSideEffects |= PatInfo.hasSideEffects;
3848 InstInfo.mayStore |= PatInfo.mayStore;
3849 InstInfo.mayLoad |= PatInfo.mayLoad;
3850
3851 // These flags are silently added without any verification.
3852 // FIXME: To match historical behavior of TableGen, for now add those flags
3853 // only when we're inferring from the primary instruction pattern.
3854 if (PatDef->isSubClassOf(Name: "Instruction")) {
3855 InstInfo.isBitcast |= PatInfo.isBitcast;
3856 InstInfo.hasChain |= PatInfo.hasChain;
3857 InstInfo.hasChain_Inferred = true;
3858 }
3859
3860 // Don't infer isVariadic. This flag means something different on SDNodes and
3861 // instructions. For example, a CALL SDNode is variadic because it has the
3862 // call arguments as operands, but a CALL instruction is not variadic - it
3863 // has argument registers as implicit, not explicit uses.
3864
3865 return Error;
3866}
3867
3868/// hasNullFragReference - Return true if the DAG has any reference to the
3869/// null_frag operator.
3870static bool hasNullFragReference(const DagInit *DI) {
3871 const DefInit *OpDef = dyn_cast<DefInit>(Val: DI->getOperator());
3872 if (!OpDef)
3873 return false;
3874 const Record *Operator = OpDef->getDef();
3875
3876 // If this is the null fragment, return true.
3877 if (Operator->getName() == "null_frag")
3878 return true;
3879 // If any of the arguments reference the null fragment, return true.
3880 for (unsigned i = 0, e = DI->getNumArgs(); i != e; ++i) {
3881 if (auto Arg = dyn_cast<DefInit>(Val: DI->getArg(Num: i)))
3882 if (Arg->getDef()->getName() == "null_frag")
3883 return true;
3884 const DagInit *Arg = dyn_cast<DagInit>(Val: DI->getArg(Num: i));
3885 if (Arg && hasNullFragReference(DI: Arg))
3886 return true;
3887 }
3888
3889 return false;
3890}
3891
3892/// hasNullFragReference - Return true if any DAG in the list references
3893/// the null_frag operator.
3894static bool hasNullFragReference(const ListInit *LI) {
3895 for (const Init *I : LI->getElements()) {
3896 const DagInit *DI = dyn_cast<DagInit>(Val: I);
3897 assert(DI && "non-dag in an instruction Pattern list?!");
3898 if (hasNullFragReference(DI))
3899 return true;
3900 }
3901 return false;
3902}
3903
3904/// Get all the instructions in a tree.
3905static void getInstructionsInTree(TreePatternNode &Tree,
3906 SmallVectorImpl<const Record *> &Instrs) {
3907 if (Tree.isLeaf())
3908 return;
3909 if (Tree.getOperator()->isSubClassOf(Name: "Instruction"))
3910 Instrs.push_back(Elt: Tree.getOperator());
3911 for (TreePatternNode &Child : Tree.children())
3912 getInstructionsInTree(Tree&: Child, Instrs);
3913}
3914
3915/// Check the class of a pattern leaf node against the instruction operand it
3916/// represents.
3917static bool checkOperandClass(const CGIOperandList::OperandInfo &OI,
3918 const Record *Leaf) {
3919 if (OI.Rec == Leaf)
3920 return true;
3921
3922 // Allow direct value types to be used in instruction set patterns.
3923 // The type will be checked later.
3924 if (Leaf->isSubClassOf(Name: "ValueType"))
3925 return true;
3926
3927 // Patterns can also be ComplexPattern instances.
3928 if (Leaf->isSubClassOf(Name: "ComplexPattern"))
3929 return true;
3930
3931 return false;
3932}
3933
3934void CodeGenDAGPatterns::parseInstructionPattern(const CodeGenInstruction &CGI,
3935 const ListInit *Pat,
3936 DAGInstMap &DAGInsts) {
3937
3938 assert(!DAGInsts.count(CGI.TheDef) && "Instruction already parsed!");
3939
3940 // Parse the instruction.
3941 TreePattern I(CGI.TheDef, Pat, true, *this);
3942
3943 // InstInputs - Keep track of all of the inputs of the instruction, along
3944 // with the record they are declared as.
3945 std::map<StringRef, TreePatternNodePtr> InstInputs;
3946
3947 // InstResults - Keep track of all the virtual registers that are 'set'
3948 // in the instruction, including what reg class they are.
3949 MapVector<StringRef, TreePatternNodePtr, std::map<StringRef, unsigned>>
3950 InstResults;
3951
3952 std::vector<const Record *> InstImpResults;
3953
3954 // Verify that the top-level forms in the instruction are of void type, and
3955 // fill in the InstResults map.
3956 SmallString<32> TypesString;
3957 for (unsigned j = 0, e = I.getNumTrees(); j != e; ++j) {
3958 TypesString.clear();
3959 TreePatternNodePtr Pat = I.getTree(i: j);
3960 if (Pat->getNumTypes() != 0) {
3961 raw_svector_ostream OS(TypesString);
3962 ListSeparator LS;
3963 for (unsigned k = 0, ke = Pat->getNumTypes(); k != ke; ++k) {
3964 OS << LS;
3965 Pat->getExtType(ResNo: k).writeToStream(OS);
3966 }
3967 I.error(Msg: "Top-level forms in instruction pattern should have"
3968 " void types, has types " +
3969 OS.str());
3970 }
3971
3972 // Find inputs and outputs, and verify the structure of the uses/defs.
3973 FindPatternInputsAndOutputs(I, Pat, InstInputs, InstResults,
3974 InstImpResults);
3975 }
3976
3977 // Now that we have inputs and outputs of the pattern, inspect the operands
3978 // list for the instruction. This determines the order that operands are
3979 // added to the machine instruction the node corresponds to.
3980 unsigned NumResults = InstResults.size();
3981
3982 // Parse the operands list from the (ops) list, validating it.
3983 assert(I.getArgList().empty() && "Args list should still be empty here!");
3984
3985 // Check that all of the results occur first in the list.
3986 std::vector<const Record *> Results;
3987 std::vector<unsigned> ResultIndices;
3988 SmallVector<TreePatternNodePtr, 2> ResNodes;
3989 for (unsigned i = 0; i != NumResults; ++i) {
3990 if (i == CGI.Operands.size()) {
3991 StringRef OpName =
3992 llvm::find_if(Range&: InstResults,
3993 P: [](const std::pair<StringRef, TreePatternNodePtr> &P) {
3994 return P.second;
3995 })
3996 ->first;
3997
3998 I.error(Msg: "'" + OpName + "' set but does not appear in operand list!");
3999 }
4000
4001 StringRef OpName = CGI.Operands[i].Name;
4002
4003 // Check that it exists in InstResults.
4004 auto InstResultIter = InstResults.find(Key: OpName);
4005 if (InstResultIter == InstResults.end() || !InstResultIter->second)
4006 I.error(Msg: "Operand $" + OpName + " does not exist in operand list!");
4007
4008 TreePatternNodePtr RNode = InstResultIter->second;
4009 const Record *R = cast<DefInit>(Val: RNode->getLeafValue())->getDef();
4010 ResNodes.push_back(Elt: std::move(RNode));
4011 if (!R)
4012 I.error(Msg: "Operand $" + OpName +
4013 " should be a set destination: all "
4014 "outputs must occur before inputs in operand list!");
4015
4016 if (!checkOperandClass(OI: CGI.Operands[i], Leaf: R))
4017 I.error(Msg: "Operand $" + OpName + " class mismatch!");
4018
4019 // Remember the return type.
4020 Results.push_back(x: CGI.Operands[i].Rec);
4021
4022 // Remember the result index.
4023 ResultIndices.push_back(x: std::distance(first: InstResults.begin(), last: InstResultIter));
4024
4025 // Okay, this one checks out.
4026 InstResultIter->second = nullptr;
4027 }
4028
4029 // Loop over the inputs next.
4030 std::vector<TreePatternNodePtr> ResultNodeOperands;
4031 std::vector<const Record *> Operands;
4032 for (unsigned i = NumResults, e = CGI.Operands.size(); i != e; ++i) {
4033 const CGIOperandList::OperandInfo &Op = CGI.Operands[i];
4034 StringRef OpName = Op.Name;
4035 if (OpName.empty()) {
4036 I.error(Msg: "Operand #" + Twine(i) + " in operands list has no name!");
4037 continue;
4038 }
4039
4040 auto InIter = InstInputs.find(x: OpName);
4041 if (InIter == InstInputs.end()) {
4042 // If this is an operand with a DefaultOps set filled in, we can ignore
4043 // this. When we codegen it, we will do so as always executed.
4044 if (Op.Rec->isSubClassOf(Name: "OperandWithDefaultOps")) {
4045 // Does it have a non-empty DefaultOps field? If so, ignore this
4046 // operand.
4047 if (!getDefaultOperand(R: Op.Rec).DefaultOps.empty())
4048 continue;
4049 }
4050 I.error(Msg: "Operand $" + OpName +
4051 " does not appear in the instruction pattern");
4052 continue;
4053 }
4054 TreePatternNodePtr InVal = InIter->second;
4055 InstInputs.erase(position: InIter); // It occurred, remove from map.
4056
4057 if (InVal->isLeaf() && isa<DefInit>(Val: InVal->getLeafValue())) {
4058 const Record *InRec = cast<DefInit>(Val: InVal->getLeafValue())->getDef();
4059 if (!checkOperandClass(OI: Op, Leaf: InRec)) {
4060 I.error(Msg: "Operand $" + OpName +
4061 "'s register class disagrees"
4062 " between the operand and pattern");
4063 continue;
4064 }
4065 }
4066 Operands.push_back(x: Op.Rec);
4067
4068 // Construct the result for the dest-pattern operand list.
4069 TreePatternNodePtr OpNode = InVal->clone();
4070
4071 // No predicate is useful on the result.
4072 OpNode->clearPredicateCalls();
4073
4074 // Promote the xform function to be an explicit node if set.
4075 if (const Record *Xform = OpNode->getTransformFn()) {
4076 OpNode->setTransformFn(nullptr);
4077 std::vector<TreePatternNodePtr> Children;
4078 Children.push_back(x: OpNode);
4079 OpNode = makeIntrusiveRefCnt<TreePatternNode>(A&: Xform, A: std::move(Children),
4080 A: OpNode->getNumTypes());
4081 }
4082
4083 ResultNodeOperands.push_back(x: std::move(OpNode));
4084 }
4085
4086 if (!InstInputs.empty())
4087 I.error(Msg: "Input operand $" + InstInputs.begin()->first +
4088 " occurs in pattern but not in operands list!");
4089
4090 TreePatternNodePtr ResultPattern = makeIntrusiveRefCnt<TreePatternNode>(
4091 A: I.getRecord(), A: std::move(ResultNodeOperands),
4092 A: GetNumNodeResults(Operator: I.getRecord(), CDP&: *this));
4093 // Copy fully inferred output node types to instruction result pattern.
4094 for (unsigned i = 0; i != NumResults; ++i) {
4095 assert(ResNodes[i]->getNumTypes() == 1 && "FIXME: Unhandled");
4096 ResultPattern->setType(ResNo: i, T: ResNodes[i]->getExtType(ResNo: 0));
4097 ResultPattern->setResultIndex(ResNo: i, RI: ResultIndices[i]);
4098 }
4099
4100 // FIXME: Assume only the first tree is the pattern. The others are clobber
4101 // nodes.
4102 TreePatternNodePtr Pattern = I.getTree(i: 0);
4103 TreePatternNodePtr SrcPattern;
4104 if (Pattern->getOperator()->getName() == "set") {
4105 SrcPattern = Pattern->getChild(N: Pattern->getNumChildren() - 1).clone();
4106 } else {
4107 // Not a set (store or something?)
4108 SrcPattern = Pattern;
4109 }
4110
4111 // Create and insert the instruction.
4112 // FIXME: InstImpResults should not be part of DAGInstruction.
4113 DAGInsts.try_emplace(k: I.getRecord(), args: std::move(Results), args: std::move(Operands),
4114 args: std::move(InstImpResults), args&: SrcPattern, args&: ResultPattern);
4115
4116 LLVM_DEBUG(I.dump());
4117}
4118
4119/// ParseInstructions - Parse all of the instructions, inlining and resolving
4120/// any fragments involved. This populates the Instructions list with fully
4121/// resolved instructions.
4122void CodeGenDAGPatterns::ParseInstructions() {
4123 for (const Record *Instr : Records.getAllDerivedDefinitions(ClassName: "Instruction")) {
4124 const ListInit *LI = nullptr;
4125
4126 if (isa<ListInit>(Val: Instr->getValueInit(FieldName: "Pattern")))
4127 LI = Instr->getValueAsListInit(FieldName: "Pattern");
4128
4129 // If there is no pattern, only collect minimal information about the
4130 // instruction for its operand list. We have to assume that there is one
4131 // result, as we have no detailed info. A pattern which references the
4132 // null_frag operator is as-if no pattern were specified. Normally this
4133 // is from a multiclass expansion w/ a SDPatternOperator passed in as
4134 // null_frag.
4135 if (!LI || LI->empty() || hasNullFragReference(LI)) {
4136 std::vector<const Record *> Results;
4137 std::vector<const Record *> Operands;
4138
4139 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4140
4141 if (InstInfo.Operands.size() != 0) {
4142 for (unsigned j = 0, e = InstInfo.Operands.NumDefs; j < e; ++j)
4143 Results.push_back(x: InstInfo.Operands[j].Rec);
4144
4145 // The rest are inputs.
4146 for (unsigned j = InstInfo.Operands.NumDefs,
4147 e = InstInfo.Operands.size();
4148 j < e; ++j)
4149 Operands.push_back(x: InstInfo.Operands[j].Rec);
4150 }
4151
4152 // Create and insert the instruction.
4153 Instructions.try_emplace(k: Instr, args: std::move(Results), args: std::move(Operands),
4154 args: std::vector<const Record *>());
4155 continue; // no pattern.
4156 }
4157
4158 const CodeGenInstruction &CGI = Target.getInstruction(InstRec: Instr);
4159 parseInstructionPattern(CGI, Pat: LI, DAGInsts&: Instructions);
4160 }
4161
4162 // If we can, convert the instructions to be patterns that are matched!
4163 for (const auto &[Instr, TheInst] : Instructions) {
4164 TreePatternNodePtr SrcPattern = TheInst.getSrcPattern();
4165 TreePatternNodePtr ResultPattern = TheInst.getResultPattern();
4166
4167 if (SrcPattern && ResultPattern) {
4168 TreePattern Pattern(Instr, SrcPattern, true, *this);
4169 TreePattern Result(Instr, ResultPattern, false, *this);
4170 ParseOnePattern(TheDef: Instr, Pattern, Result, InstImpResults: TheInst.getImpResults());
4171 }
4172 }
4173}
4174
4175using NameRecord = std::pair<TreePatternNode *, unsigned>;
4176
4177static void FindNames(TreePatternNode &P,
4178 std::map<StringRef, NameRecord> &Names,
4179 TreePattern *PatternTop) {
4180 if (!P.getName().empty()) {
4181 NameRecord &Rec = Names[P.getName()];
4182 // If this is the first instance of the name, remember the node.
4183 if (Rec.second++ == 0)
4184 Rec.first = &P;
4185 else if (Rec.first->getExtTypes() != P.getExtTypes())
4186 PatternTop->error(Msg: "repetition of value: $" + P.getName() +
4187 " where different uses have different types!");
4188 }
4189
4190 if (!P.isLeaf()) {
4191 for (TreePatternNode &Child : P.children())
4192 FindNames(P&: Child, Names, PatternTop);
4193 }
4194}
4195
4196void CodeGenDAGPatterns::AddPatternToMatch(TreePattern *Pattern,
4197 PatternToMatch &&PTM) {
4198 // Do some sanity checking on the pattern we're about to match.
4199 std::string Reason;
4200 if (!PTM.getSrcPattern().canPatternMatch(Reason, CDP: *this)) {
4201 PrintWarning(WarningLoc: Pattern->getRecord()->getLoc(),
4202 Msg: Twine("Pattern can never match: ") + Reason);
4203 return;
4204 }
4205
4206 // If the source pattern's root is a complex pattern, that complex pattern
4207 // must specify the nodes it can potentially match.
4208 if (const ComplexPattern *CP =
4209 PTM.getSrcPattern().getComplexPatternInfo(CGP: *this))
4210 if (CP->getRootNodes().empty())
4211 Pattern->error(Msg: "ComplexPattern at root must specify list of opcodes it"
4212 " could match");
4213
4214 // Find all of the named values in the input and output, ensure they have the
4215 // same type.
4216 std::map<StringRef, NameRecord> SrcNames, DstNames;
4217 FindNames(P&: PTM.getSrcPattern(), Names&: SrcNames, PatternTop: Pattern);
4218 FindNames(P&: PTM.getDstPattern(), Names&: DstNames, PatternTop: Pattern);
4219
4220 // Scan all of the named values in the destination pattern, rejecting them if
4221 // they don't exist in the input pattern.
4222 for (const auto &Entry : DstNames) {
4223 if (SrcNames[Entry.first].first == nullptr)
4224 Pattern->error(Msg: "Pattern has input without matching name in output: $" +
4225 Entry.first);
4226 }
4227
4228 // Scan all of the named values in the source pattern, rejecting them if the
4229 // name isn't used in the dest, and isn't used to tie two values together.
4230 for (const auto &Entry : SrcNames)
4231 if (DstNames[Entry.first].first == nullptr &&
4232 SrcNames[Entry.first].second == 1)
4233 Pattern->error(Msg: "Pattern has dead named input: $" + Entry.first +
4234 " (use srcvalue for an intentionally unused input)");
4235
4236 PatternsToMatch.push_back(x: std::move(PTM));
4237}
4238
4239void CodeGenDAGPatterns::InferInstructionFlags() {
4240 ArrayRef<const CodeGenInstruction *> Instructions = Target.getInstructions();
4241
4242 unsigned Errors = 0;
4243
4244 // Try to infer flags from all patterns in PatternToMatch. These include
4245 // both the primary instruction patterns (which always come first) and
4246 // patterns defined outside the instruction.
4247 for (const PatternToMatch &PTM : ptms()) {
4248 // We can only infer from single-instruction patterns, otherwise we won't
4249 // know which instruction should get the flags.
4250 SmallVector<const Record *, 8> PatInstrs;
4251 getInstructionsInTree(Tree&: PTM.getDstPattern(), Instrs&: PatInstrs);
4252 if (PatInstrs.size() != 1)
4253 continue;
4254
4255 // Get the single instruction.
4256 CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: PatInstrs.front());
4257
4258 // Only infer properties from the first pattern. We'll verify the others.
4259 if (InstInfo.InferredFrom)
4260 continue;
4261
4262 InstAnalyzer PatInfo(*this);
4263 PatInfo.Analyze(Pat: PTM);
4264 Errors += InferFromPattern(InstInfo, PatInfo, PatDef: PTM.getSrcRecord());
4265 }
4266
4267 if (Errors)
4268 PrintFatalError(Msg: "pattern conflicts");
4269
4270 // If requested by the target, guess any undefined properties.
4271 if (Target.guessInstructionProperties()) {
4272 for (const CodeGenInstruction *InstInfo : Instructions) {
4273 if (InstInfo->InferredFrom)
4274 continue;
4275 // The mayLoad and mayStore flags default to false.
4276 // Conservatively assume hasSideEffects if it wasn't explicit.
4277 if (InstInfo->hasSideEffects_Unset)
4278 const_cast<CodeGenInstruction *>(InstInfo)->hasSideEffects = true;
4279 }
4280 return;
4281 }
4282
4283 // Complain about any flags that are still undefined.
4284 for (const CodeGenInstruction *InstInfo : Instructions) {
4285 if (InstInfo->InferredFrom)
4286 continue;
4287 if (InstInfo->hasSideEffects_Unset)
4288 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4289 Msg: "Can't infer hasSideEffects from patterns");
4290 if (InstInfo->mayStore_Unset)
4291 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4292 Msg: "Can't infer mayStore from patterns");
4293 if (InstInfo->mayLoad_Unset)
4294 PrintError(ErrorLoc: InstInfo->TheDef->getLoc(),
4295 Msg: "Can't infer mayLoad from patterns");
4296 }
4297}
4298
4299/// Verify instruction flags against pattern node properties.
4300void CodeGenDAGPatterns::VerifyInstructionFlags() {
4301 unsigned Errors = 0;
4302 for (const PatternToMatch &PTM : ptms()) {
4303 SmallVector<const Record *, 8> Instrs;
4304 getInstructionsInTree(Tree&: PTM.getDstPattern(), Instrs);
4305 if (Instrs.empty())
4306 continue;
4307
4308 // Count the number of instructions with each flag set.
4309 unsigned NumSideEffects = 0;
4310 unsigned NumStores = 0;
4311 unsigned NumLoads = 0;
4312 for (const Record *Instr : Instrs) {
4313 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4314 NumSideEffects += InstInfo.hasSideEffects;
4315 NumStores += InstInfo.mayStore;
4316 NumLoads += InstInfo.mayLoad;
4317 }
4318
4319 // Analyze the source pattern.
4320 InstAnalyzer PatInfo(*this);
4321 PatInfo.Analyze(Pat: PTM);
4322
4323 // Collect error messages.
4324 SmallVector<std::string, 4> Msgs;
4325
4326 // Check for missing flags in the output.
4327 // Permit extra flags for now at least.
4328 if (PatInfo.hasSideEffects && !NumSideEffects)
4329 Msgs.push_back(Elt: "pattern has side effects, but hasSideEffects isn't set");
4330
4331 // Don't verify store flags on instructions with side effects. At least for
4332 // intrinsics, side effects implies mayStore.
4333 if (!PatInfo.hasSideEffects && PatInfo.mayStore && !NumStores)
4334 Msgs.push_back(Elt: "pattern may store, but mayStore isn't set");
4335
4336 // Similarly, mayStore implies mayLoad on intrinsics.
4337 if (!PatInfo.mayStore && PatInfo.mayLoad && !NumLoads)
4338 Msgs.push_back(Elt: "pattern may load, but mayLoad isn't set");
4339
4340 // Print error messages.
4341 if (Msgs.empty())
4342 continue;
4343 ++Errors;
4344
4345 for (const std::string &Msg : Msgs)
4346 PrintError(
4347 ErrorLoc: PTM.getSrcRecord()->getLoc(),
4348 Msg: Twine(Msg) + " on the " +
4349 (Instrs.size() == 1 ? "instruction" : "output instructions"));
4350 // Provide the location of the relevant instruction definitions.
4351 for (const Record *Instr : Instrs) {
4352 if (Instr != PTM.getSrcRecord())
4353 PrintError(ErrorLoc: Instr->getLoc(), Msg: "defined here");
4354 const CodeGenInstruction &InstInfo = Target.getInstruction(InstRec: Instr);
4355 if (InstInfo.InferredFrom && InstInfo.InferredFrom != InstInfo.TheDef &&
4356 InstInfo.InferredFrom != PTM.getSrcRecord())
4357 PrintError(ErrorLoc: InstInfo.InferredFrom->getLoc(), Msg: "inferred from pattern");
4358 }
4359 }
4360 if (Errors)
4361 PrintFatalError(Msg: "Errors in DAG patterns");
4362}
4363
4364/// Given a pattern result with an unresolved type, see if we can find one
4365/// instruction with an unresolved result type. Force this result type to an
4366/// arbitrary element if it's possible types to converge results.
4367static bool ForceArbitraryInstResultType(TreePatternNode &N, TreePattern &TP) {
4368 if (N.isLeaf())
4369 return false;
4370
4371 // Analyze children.
4372 for (TreePatternNode &Child : N.children())
4373 if (ForceArbitraryInstResultType(N&: Child, TP))
4374 return true;
4375
4376 if (!N.getOperator()->isSubClassOf(Name: "Instruction"))
4377 return false;
4378
4379 // If this type is already concrete or completely unknown we can't do
4380 // anything.
4381 TypeInfer &TI = TP.getInfer();
4382 for (unsigned i = 0, e = N.getNumTypes(); i != e; ++i) {
4383 if (N.getExtType(ResNo: i).empty() ||
4384 N.getExtType(ResNo: i).isValueTypeByHwMode(/*AllowEmpty=*/false))
4385 continue;
4386
4387 // Otherwise, force its type to an arbitrary choice.
4388 if (TI.forceArbitrary(Out&: N.getExtType(ResNo: i)))
4389 return true;
4390 }
4391
4392 return false;
4393}
4394
4395// Promote xform function to be an explicit node wherever set.
4396static TreePatternNodePtr PromoteXForms(TreePatternNodePtr N) {
4397 if (const Record *Xform = N->getTransformFn()) {
4398 N->setTransformFn(nullptr);
4399 std::vector<TreePatternNodePtr> Children;
4400 Children.push_back(x: PromoteXForms(N));
4401 return makeIntrusiveRefCnt<TreePatternNode>(A&: Xform, A: std::move(Children),
4402 A: N->getNumTypes());
4403 }
4404
4405 if (!N->isLeaf())
4406 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
4407 TreePatternNodePtr Child = N->getChildShared(N: i);
4408 N->setChild(i, N: PromoteXForms(N: Child));
4409 }
4410 return N;
4411}
4412
4413void CodeGenDAGPatterns::ParseOnePattern(
4414 const Record *TheDef, TreePattern &Pattern, TreePattern &Result,
4415 ArrayRef<const Record *> InstImpResults, bool ShouldIgnore) {
4416 // Inline pattern fragments and expand multiple alternatives.
4417 Pattern.InlinePatternFragments();
4418 Result.InlinePatternFragments();
4419
4420 if (Result.getNumTrees() != 1) {
4421 Result.error(Msg: "Cannot use multi-alternative fragments in result pattern!");
4422 return;
4423 }
4424
4425 // Infer types.
4426 bool IterateInference;
4427 bool InferredAllPatternTypes, InferredAllResultTypes;
4428 do {
4429 // Infer as many types as possible. If we cannot infer all of them, we
4430 // can never do anything with this pattern: report it to the user.
4431 InferredAllPatternTypes =
4432 Pattern.InferAllTypes(InNamedTypes: &Pattern.getNamedNodesMap());
4433
4434 // Infer as many types as possible. If we cannot infer all of them, we
4435 // can never do anything with this pattern: report it to the user.
4436 InferredAllResultTypes = Result.InferAllTypes(InNamedTypes: &Pattern.getNamedNodesMap());
4437
4438 IterateInference = false;
4439
4440 // Apply the type of the result to the source pattern. This helps us
4441 // resolve cases where the input type is known to be a pointer type (which
4442 // is considered resolved), but the result knows it needs to be 32- or
4443 // 64-bits. Infer the other way for good measure.
4444 for (const auto &T : Pattern.getTrees())
4445 for (unsigned i = 0, e = std::min(a: Result.getOnlyTree()->getNumTypes(),
4446 b: T->getNumTypes());
4447 i != e; ++i) {
4448 IterateInference |=
4449 T->UpdateNodeType(ResNo: i, InTy: Result.getOnlyTree()->getExtType(ResNo: i), TP&: Result);
4450 IterateInference |=
4451 Result.getOnlyTree()->UpdateNodeType(ResNo: i, InTy: T->getExtType(ResNo: i), TP&: Result);
4452 }
4453
4454 // If our iteration has converged and the input pattern's types are fully
4455 // resolved but the result pattern is not fully resolved, we may have a
4456 // situation where we have two instructions in the result pattern and
4457 // the instructions require a common register class, but don't care about
4458 // what actual MVT is used. This is actually a bug in our modelling:
4459 // output patterns should have register classes, not MVTs.
4460 //
4461 // In any case, to handle this, we just go through and disambiguate some
4462 // arbitrary types to the result pattern's nodes.
4463 if (!IterateInference && InferredAllPatternTypes && !InferredAllResultTypes)
4464 IterateInference =
4465 ForceArbitraryInstResultType(N&: *Result.getTree(i: 0), TP&: Result);
4466 } while (IterateInference);
4467
4468 // Verify that we inferred enough types that we can do something with the
4469 // pattern and result. If these fire the user has to add type casts.
4470 if (!InferredAllPatternTypes)
4471 Pattern.error(Msg: "Could not infer all types in pattern!");
4472 if (!InferredAllResultTypes) {
4473 Pattern.dump();
4474 Result.error(Msg: "Could not infer all types in pattern result!");
4475 }
4476
4477 // Promote xform function to be an explicit node wherever set.
4478 TreePatternNodePtr DstShared = PromoteXForms(N: Result.getOnlyTree());
4479
4480 TreePattern Temp(Result.getRecord(), DstShared, false, *this);
4481 Temp.InferAllTypes();
4482
4483 const ListInit *Preds = TheDef->getValueAsListInit(FieldName: "Predicates");
4484 int Complexity = TheDef->getValueAsInt(FieldName: "AddedComplexity");
4485
4486 // A pattern may end up with an "impossible" type, i.e. a situation
4487 // where all types have been eliminated for some node in this pattern.
4488 // This could occur for intrinsics that only make sense for a specific
4489 // value type, and use a specific register class. If, for some mode,
4490 // that register class does not accept that type, the type inference
4491 // will lead to a contradiction, which is not an error however, but
4492 // a sign that this pattern will simply never match.
4493 if (Temp.getOnlyTree()->hasPossibleType()) {
4494 for (const auto &T : Pattern.getTrees()) {
4495 if (T->hasPossibleType())
4496 AddPatternToMatch(Pattern: &Pattern,
4497 PTM: PatternToMatch(TheDef, Preds, T, Temp.getOnlyTree(),
4498 InstImpResults, Complexity,
4499 TheDef->getID(), ShouldIgnore));
4500 }
4501 } else {
4502 // Show a message about a dropped pattern with some info to make it
4503 // easier to identify it in the .td files.
4504 LLVM_DEBUG({
4505 dbgs() << "Dropping: ";
4506 Pattern.dump();
4507 Temp.getOnlyTree()->dump();
4508 dbgs() << "\n";
4509 });
4510 }
4511}
4512
4513void CodeGenDAGPatterns::ParsePatterns() {
4514 for (const Record *CurPattern : Records.getAllDerivedDefinitions(ClassName: "Pattern")) {
4515 const DagInit *Tree = CurPattern->getValueAsDag(FieldName: "PatternToMatch");
4516
4517 // If the pattern references the null_frag, there's nothing to do.
4518 if (hasNullFragReference(DI: Tree))
4519 continue;
4520
4521 TreePattern Pattern(CurPattern, Tree, true, *this);
4522
4523 const ListInit *LI = CurPattern->getValueAsListInit(FieldName: "ResultInstrs");
4524 if (LI->empty())
4525 continue; // no pattern.
4526
4527 // Parse the instruction.
4528 TreePattern Result(CurPattern, LI, false, *this);
4529
4530 if (Result.getNumTrees() != 1)
4531 Result.error(Msg: "Cannot handle instructions producing instructions "
4532 "with temporaries yet!");
4533
4534 // Validate that the input pattern is correct.
4535 InstInputsTy InstInputs;
4536 InstResultsTy InstResults;
4537 std::vector<const Record *> InstImpResults;
4538 for (unsigned j = 0, ee = Pattern.getNumTrees(); j != ee; ++j)
4539 FindPatternInputsAndOutputs(I&: Pattern, Pat: Pattern.getTree(i: j), InstInputs,
4540 InstResults, InstImpResults);
4541
4542 ParseOnePattern(TheDef: CurPattern, Pattern, Result, InstImpResults,
4543 ShouldIgnore: CurPattern->getValueAsBit(FieldName: "GISelShouldIgnore"));
4544 }
4545}
4546
4547static void collectModes(std::set<unsigned> &Modes, const TreePatternNode &N) {
4548 for (const TypeSetByHwMode &VTS : N.getExtTypes())
4549 for (const auto &I : VTS)
4550 Modes.insert(x: I.first);
4551
4552 for (const TreePatternNode &Child : N.children())
4553 collectModes(Modes, N: Child);
4554}
4555
4556void CodeGenDAGPatterns::ExpandHwModeBasedTypes() {
4557 const CodeGenHwModes &CGH = getTargetInfo().getHwModes();
4558 if (CGH.getNumModeIds() == 1)
4559 return;
4560
4561 std::vector<PatternToMatch> Copy;
4562 PatternsToMatch.swap(x&: Copy);
4563
4564 auto AppendPattern = [this](PatternToMatch &P, unsigned Mode,
4565 StringRef Check) {
4566 TreePatternNodePtr NewSrc = P.getSrcPattern().clone();
4567 TreePatternNodePtr NewDst = P.getDstPattern().clone();
4568 if (!NewSrc->setDefaultMode(Mode) || !NewDst->setDefaultMode(Mode)) {
4569 return;
4570 }
4571
4572 PatternsToMatch.emplace_back(args: P.getSrcRecord(), args: P.getPredicates(),
4573 args: std::move(NewSrc), args: std::move(NewDst),
4574 args: P.getDstRegs(), args: P.getAddedComplexity(),
4575 args: getNewUID(), args: P.getGISelShouldIgnore(), args&: Check);
4576 };
4577
4578 for (PatternToMatch &P : Copy) {
4579 const TreePatternNode *SrcP = nullptr, *DstP = nullptr;
4580 if (P.getSrcPattern().hasProperTypeByHwMode())
4581 SrcP = &P.getSrcPattern();
4582 if (P.getDstPattern().hasProperTypeByHwMode())
4583 DstP = &P.getDstPattern();
4584 if (!SrcP && !DstP) {
4585 PatternsToMatch.push_back(x: P);
4586 continue;
4587 }
4588
4589 std::set<unsigned> Modes;
4590 if (SrcP)
4591 collectModes(Modes, N: *SrcP);
4592 if (DstP)
4593 collectModes(Modes, N: *DstP);
4594
4595 // The predicate for the default mode needs to be constructed for each
4596 // pattern separately.
4597 // Since not all modes must be present in each pattern, if a mode m is
4598 // absent, then there is no point in constructing a check for m. If such
4599 // a check was created, it would be equivalent to checking the default
4600 // mode, except not all modes' predicates would be a part of the checking
4601 // code. The subsequently generated check for the default mode would then
4602 // have the exact same patterns, but a different predicate code. To avoid
4603 // duplicated patterns with different predicate checks, construct the
4604 // default check as a negation of all predicates that are actually present
4605 // in the source/destination patterns.
4606 SmallString<128> DefaultCheck;
4607
4608 for (unsigned M : Modes) {
4609 if (M == DefaultMode)
4610 continue;
4611
4612 // Fill the map entry for this mode.
4613 const HwMode &HM = CGH.getMode(Id: M);
4614
4615 SmallString<128> PredicateCheck;
4616 raw_svector_ostream PS(PredicateCheck);
4617 SubtargetFeatureInfo::emitPredicateCheck(OS&: PS, Predicates: HM.Predicates);
4618 AppendPattern(P, M, PredicateCheck);
4619
4620 // Add negations of the HM's predicates to the default predicate.
4621 if (!DefaultCheck.empty())
4622 DefaultCheck += " && ";
4623 DefaultCheck += "!(";
4624 DefaultCheck.append(RHS: PredicateCheck);
4625 DefaultCheck += ")";
4626 }
4627
4628 bool HasDefault = Modes.count(x: DefaultMode);
4629 if (HasDefault)
4630 AppendPattern(P, DefaultMode, DefaultCheck);
4631 }
4632}
4633
4634/// Dependent variable map for CodeGenDAGPattern variant generation
4635using DepVarMap = StringMap<int>;
4636
4637static void FindDepVarsOf(TreePatternNode &N, DepVarMap &DepMap) {
4638 if (N.isLeaf()) {
4639 if (N.hasName() && isa<DefInit>(Val: N.getLeafValue()))
4640 DepMap[N.getName()]++;
4641 } else {
4642 for (TreePatternNode &Child : N.children())
4643 FindDepVarsOf(N&: Child, DepMap);
4644 }
4645}
4646
4647/// Find dependent variables within child patterns
4648static void FindDepVars(TreePatternNode &N, MultipleUseVarSet &DepVars) {
4649 DepVarMap depcounts;
4650 FindDepVarsOf(N, DepMap&: depcounts);
4651 for (const auto &Pair : depcounts) {
4652 if (Pair.getValue() > 1)
4653 DepVars.insert(key: Pair.getKey());
4654 }
4655}
4656
4657#ifndef NDEBUG
4658/// Dump the dependent variable set:
4659static void DumpDepVars(MultipleUseVarSet &DepVars) {
4660 if (DepVars.empty()) {
4661 LLVM_DEBUG(dbgs() << "<empty set>");
4662 } else {
4663 LLVM_DEBUG(dbgs() << "[ ");
4664 for (const auto &DepVar : DepVars) {
4665 LLVM_DEBUG(dbgs() << DepVar.getKey() << " ");
4666 }
4667 LLVM_DEBUG(dbgs() << "]");
4668 }
4669}
4670#endif
4671
4672/// CombineChildVariants - Given a bunch of permutations of each child of the
4673/// 'operator' node, put them together in all possible ways.
4674static void CombineChildVariants(
4675 TreePatternNodePtr Orig,
4676 const std::vector<std::vector<TreePatternNodePtr>> &ChildVariants,
4677 std::vector<TreePatternNodePtr> &OutVariants, CodeGenDAGPatterns &CDP,
4678 const MultipleUseVarSet &DepVars) {
4679 // Make sure that each operand has at least one variant to choose from.
4680 for (const auto &Variants : ChildVariants)
4681 if (Variants.empty())
4682 return;
4683
4684 // The end result is an all-pairs construction of the resultant pattern.
4685 std::vector<unsigned> Idxs(ChildVariants.size());
4686 bool NotDone;
4687 do {
4688#ifndef NDEBUG
4689 LLVM_DEBUG(if (!Idxs.empty()) {
4690 dbgs() << Orig->getOperator()->getName() << ": Idxs = [ ";
4691 for (unsigned Idx : Idxs) {
4692 dbgs() << Idx << " ";
4693 }
4694 dbgs() << "]\n";
4695 });
4696#endif
4697 // Create the variant and add it to the output list.
4698 std::vector<TreePatternNodePtr> NewChildren;
4699 NewChildren.reserve(n: ChildVariants.size());
4700 for (unsigned i = 0, e = ChildVariants.size(); i != e; ++i)
4701 NewChildren.push_back(x: ChildVariants[i][Idxs[i]]);
4702 TreePatternNodePtr R = makeIntrusiveRefCnt<TreePatternNode>(
4703 A: Orig->getOperator(), A: std::move(NewChildren), A: Orig->getNumTypes());
4704
4705 // Copy over properties.
4706 R->setName(Orig->getName());
4707 R->setNamesAsPredicateArg(Orig->getNamesAsPredicateArg());
4708 R->setPredicateCalls(Orig->getPredicateCalls());
4709 R->setGISelFlagsRecord(Orig->getGISelFlagsRecord());
4710 R->setTransformFn(Orig->getTransformFn());
4711 for (unsigned i = 0, e = Orig->getNumTypes(); i != e; ++i)
4712 R->setType(ResNo: i, T: Orig->getExtType(ResNo: i));
4713
4714 // If this pattern cannot match, do not include it as a variant.
4715 std::string ErrString;
4716 // Scan to see if this pattern has already been emitted. We can get
4717 // duplication due to things like commuting:
4718 // (and GPRC:$a, GPRC:$b) -> (and GPRC:$b, GPRC:$a)
4719 // which are the same pattern. Ignore the dups.
4720 if (R->canPatternMatch(Reason&: ErrString, CDP) &&
4721 none_of(Range&: OutVariants, P: [&](TreePatternNodePtr Variant) {
4722 return R->isIsomorphicTo(N: *Variant, DepVars);
4723 }))
4724 OutVariants.push_back(x: R);
4725
4726 // Increment indices to the next permutation by incrementing the
4727 // indices from last index backward, e.g., generate the sequence
4728 // [0, 0], [0, 1], [1, 0], [1, 1].
4729 int IdxsIdx;
4730 for (IdxsIdx = Idxs.size() - 1; IdxsIdx >= 0; --IdxsIdx) {
4731 if (++Idxs[IdxsIdx] == ChildVariants[IdxsIdx].size())
4732 Idxs[IdxsIdx] = 0;
4733 else
4734 break;
4735 }
4736 NotDone = (IdxsIdx >= 0);
4737 } while (NotDone);
4738}
4739
4740/// CombineChildVariants - A helper function for binary operators.
4741///
4742static void CombineChildVariants(TreePatternNodePtr Orig,
4743 const std::vector<TreePatternNodePtr> &LHS,
4744 const std::vector<TreePatternNodePtr> &RHS,
4745 std::vector<TreePatternNodePtr> &OutVariants,
4746 CodeGenDAGPatterns &CDP,
4747 const MultipleUseVarSet &DepVars) {
4748 std::vector<std::vector<TreePatternNodePtr>> ChildVariants;
4749 ChildVariants.push_back(x: LHS);
4750 ChildVariants.push_back(x: RHS);
4751 CombineChildVariants(Orig, ChildVariants, OutVariants, CDP, DepVars);
4752}
4753
4754static void
4755GatherChildrenOfAssociativeOpcode(TreePatternNodePtr N,
4756 std::vector<TreePatternNodePtr> &Children) {
4757 assert(N->getNumChildren() == 2 &&
4758 "Associative but doesn't have 2 children!");
4759 const Record *Operator = N->getOperator();
4760
4761 // Only permit raw nodes.
4762 if (!N->getName().empty() || !N->getPredicateCalls().empty() ||
4763 N->getTransformFn()) {
4764 Children.push_back(x: N);
4765 return;
4766 }
4767
4768 if (N->getChild(N: 0).isLeaf() || N->getChild(N: 0).getOperator() != Operator)
4769 Children.push_back(x: N->getChildShared(N: 0));
4770 else
4771 GatherChildrenOfAssociativeOpcode(N: N->getChildShared(N: 0), Children);
4772
4773 if (N->getChild(N: 1).isLeaf() || N->getChild(N: 1).getOperator() != Operator)
4774 Children.push_back(x: N->getChildShared(N: 1));
4775 else
4776 GatherChildrenOfAssociativeOpcode(N: N->getChildShared(N: 1), Children);
4777}
4778
4779/// GenerateVariantsOf - Given a pattern N, generate all permutations we can of
4780/// the (potentially recursive) pattern by using algebraic laws.
4781///
4782static void GenerateVariantsOf(TreePatternNodePtr N,
4783 std::vector<TreePatternNodePtr> &OutVariants,
4784 CodeGenDAGPatterns &CDP,
4785 const MultipleUseVarSet &DepVars) {
4786 // We cannot permute leaves or ComplexPattern uses.
4787 if (N->isLeaf() || N->getOperator()->isSubClassOf(Name: "ComplexPattern")) {
4788 OutVariants.push_back(x: N);
4789 return;
4790 }
4791
4792 // Look up interesting info about the node.
4793 const SDNodeInfo &NodeInfo = CDP.getSDNodeInfo(R: N->getOperator());
4794
4795 // If this node is associative, re-associate.
4796 if (NodeInfo.hasProperty(Prop: SDNPAssociative)) {
4797 // Re-associate by pulling together all of the linked operators
4798 std::vector<TreePatternNodePtr> MaximalChildren;
4799 GatherChildrenOfAssociativeOpcode(N, Children&: MaximalChildren);
4800
4801 // Only handle child sizes of 3. Otherwise we'll end up trying too many
4802 // permutations.
4803 if (MaximalChildren.size() == 3) {
4804 // Find the variants of all of our maximal children.
4805 std::vector<TreePatternNodePtr> AVariants, BVariants, CVariants;
4806 GenerateVariantsOf(N: MaximalChildren[0], OutVariants&: AVariants, CDP, DepVars);
4807 GenerateVariantsOf(N: MaximalChildren[1], OutVariants&: BVariants, CDP, DepVars);
4808 GenerateVariantsOf(N: MaximalChildren[2], OutVariants&: CVariants, CDP, DepVars);
4809
4810 // There are only two ways we can permute the tree:
4811 // (A op B) op C and A op (B op C)
4812 // Within these forms, we can also permute A/B/C.
4813
4814 // Generate legal pair permutations of A/B/C.
4815 std::vector<TreePatternNodePtr> ABVariants;
4816 std::vector<TreePatternNodePtr> BAVariants;
4817 std::vector<TreePatternNodePtr> ACVariants;
4818 std::vector<TreePatternNodePtr> CAVariants;
4819 std::vector<TreePatternNodePtr> BCVariants;
4820 std::vector<TreePatternNodePtr> CBVariants;
4821 CombineChildVariants(Orig: N, LHS: AVariants, RHS: BVariants, OutVariants&: ABVariants, CDP, DepVars);
4822 CombineChildVariants(Orig: N, LHS: BVariants, RHS: AVariants, OutVariants&: BAVariants, CDP, DepVars);
4823 CombineChildVariants(Orig: N, LHS: AVariants, RHS: CVariants, OutVariants&: ACVariants, CDP, DepVars);
4824 CombineChildVariants(Orig: N, LHS: CVariants, RHS: AVariants, OutVariants&: CAVariants, CDP, DepVars);
4825 CombineChildVariants(Orig: N, LHS: BVariants, RHS: CVariants, OutVariants&: BCVariants, CDP, DepVars);
4826 CombineChildVariants(Orig: N, LHS: CVariants, RHS: BVariants, OutVariants&: CBVariants, CDP, DepVars);
4827
4828 // Combine those into the result: (x op x) op x
4829 CombineChildVariants(Orig: N, LHS: ABVariants, RHS: CVariants, OutVariants, CDP, DepVars);
4830 CombineChildVariants(Orig: N, LHS: BAVariants, RHS: CVariants, OutVariants, CDP, DepVars);
4831 CombineChildVariants(Orig: N, LHS: ACVariants, RHS: BVariants, OutVariants, CDP, DepVars);
4832 CombineChildVariants(Orig: N, LHS: CAVariants, RHS: BVariants, OutVariants, CDP, DepVars);
4833 CombineChildVariants(Orig: N, LHS: BCVariants, RHS: AVariants, OutVariants, CDP, DepVars);
4834 CombineChildVariants(Orig: N, LHS: CBVariants, RHS: AVariants, OutVariants, CDP, DepVars);
4835
4836 // Combine those into the result: x op (x op x)
4837 CombineChildVariants(Orig: N, LHS: CVariants, RHS: ABVariants, OutVariants, CDP, DepVars);
4838 CombineChildVariants(Orig: N, LHS: CVariants, RHS: BAVariants, OutVariants, CDP, DepVars);
4839 CombineChildVariants(Orig: N, LHS: BVariants, RHS: ACVariants, OutVariants, CDP, DepVars);
4840 CombineChildVariants(Orig: N, LHS: BVariants, RHS: CAVariants, OutVariants, CDP, DepVars);
4841 CombineChildVariants(Orig: N, LHS: AVariants, RHS: BCVariants, OutVariants, CDP, DepVars);
4842 CombineChildVariants(Orig: N, LHS: AVariants, RHS: CBVariants, OutVariants, CDP, DepVars);
4843 return;
4844 }
4845 }
4846
4847 // Compute permutations of all children.
4848 std::vector<std::vector<TreePatternNodePtr>> ChildVariants(
4849 N->getNumChildren());
4850 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
4851 GenerateVariantsOf(N: N->getChildShared(N: i), OutVariants&: ChildVariants[i], CDP, DepVars);
4852
4853 // Build all permutations based on how the children were formed.
4854 CombineChildVariants(Orig: N, ChildVariants, OutVariants, CDP, DepVars);
4855
4856 // If this node is commutative, consider the commuted order.
4857 bool isCommIntrinsic = N->isCommutativeIntrinsic(CDP);
4858 if (NodeInfo.hasProperty(Prop: SDNPCommutative) || isCommIntrinsic) {
4859 unsigned Skip = isCommIntrinsic ? 1 : 0; // First operand is intrinsic id.
4860 assert(N->getNumChildren() >= (2 + Skip) &&
4861 "Commutative but doesn't have 2 children!");
4862 // Don't allow commuting children which are actually register references.
4863 bool NoRegisters = true;
4864 unsigned i = 0 + Skip;
4865 unsigned e = 2 + Skip;
4866 for (; i != e; ++i) {
4867 TreePatternNode &Child = N->getChild(N: i);
4868 if (Child.isLeaf())
4869 if (const DefInit *DI = dyn_cast<DefInit>(Val: Child.getLeafValue())) {
4870 const Record *RR = DI->getDef();
4871 if (RR->isSubClassOf(Name: "Register"))
4872 NoRegisters = false;
4873 }
4874 }
4875 // Consider the commuted order.
4876 if (NoRegisters) {
4877 // Swap the first two operands after the intrinsic id, if present.
4878 unsigned i = isCommIntrinsic ? 1 : 0;
4879 std::swap(x&: ChildVariants[i], y&: ChildVariants[i + 1]);
4880 CombineChildVariants(Orig: N, ChildVariants, OutVariants, CDP, DepVars);
4881 }
4882 }
4883}
4884
4885// GenerateVariants - Generate variants. For example, commutative patterns can
4886// match multiple ways. Add them to PatternsToMatch as well.
4887void CodeGenDAGPatterns::GenerateVariants() {
4888 LLVM_DEBUG(dbgs() << "Generating instruction variants.\n");
4889
4890 // Loop over all of the patterns we've collected, checking to see if we can
4891 // generate variants of the instruction, through the exploitation of
4892 // identities. This permits the target to provide aggressive matching without
4893 // the .td file having to contain tons of variants of instructions.
4894 //
4895 // Note that this loop adds new patterns to the PatternsToMatch list, but we
4896 // intentionally do not reconsider these. Any variants of added patterns have
4897 // already been added.
4898 //
4899 for (unsigned i = 0, e = PatternsToMatch.size(); i != e; ++i) {
4900 MultipleUseVarSet DepVars;
4901 std::vector<TreePatternNodePtr> Variants;
4902 FindDepVars(N&: PatternsToMatch[i].getSrcPattern(), DepVars);
4903 LLVM_DEBUG(dbgs() << "Dependent/multiply used variables: ");
4904 LLVM_DEBUG(DumpDepVars(DepVars));
4905 LLVM_DEBUG(dbgs() << "\n");
4906 GenerateVariantsOf(N: PatternsToMatch[i].getSrcPatternShared(), OutVariants&: Variants,
4907 CDP&: *this, DepVars);
4908
4909 assert(PatternsToMatch[i].getHwModeFeatures().empty() &&
4910 "HwModes should not have been expanded yet!");
4911
4912 assert(!Variants.empty() && "Must create at least original variant!");
4913 if (Variants.size() == 1) // No additional variants for this pattern.
4914 continue;
4915
4916 LLVM_DEBUG(dbgs() << "FOUND VARIANTS OF: ";
4917 PatternsToMatch[i].getSrcPattern().dump(); dbgs() << "\n");
4918
4919 for (unsigned v = 0, e = Variants.size(); v != e; ++v) {
4920 TreePatternNodePtr Variant = Variants[v];
4921
4922 LLVM_DEBUG(dbgs() << " VAR#" << v << ": "; Variant->dump();
4923 dbgs() << "\n");
4924
4925 // Scan to see if an instruction or explicit pattern already matches this.
4926 bool AlreadyExists = false;
4927 for (unsigned p = 0, e = PatternsToMatch.size(); p != e; ++p) {
4928 // Skip if the top level predicates do not match.
4929 if ((i != p) && (PatternsToMatch[i].getPredicates() !=
4930 PatternsToMatch[p].getPredicates()))
4931 continue;
4932 // Check to see if this variant already exists.
4933 if (Variant->isIsomorphicTo(N: PatternsToMatch[p].getSrcPattern(),
4934 DepVars)) {
4935 LLVM_DEBUG(dbgs() << " *** ALREADY EXISTS, ignoring variant.\n");
4936 AlreadyExists = true;
4937 break;
4938 }
4939 }
4940 // If we already have it, ignore the variant.
4941 if (AlreadyExists)
4942 continue;
4943
4944 // Otherwise, add it to the list of patterns we have.
4945 PatternsToMatch.emplace_back(
4946 args: PatternsToMatch[i].getSrcRecord(), args: PatternsToMatch[i].getPredicates(),
4947 args&: Variant, args: PatternsToMatch[i].getDstPatternShared(),
4948 args: PatternsToMatch[i].getDstRegs(),
4949 args: PatternsToMatch[i].getAddedComplexity(), args: getNewUID(),
4950 args: PatternsToMatch[i].getGISelShouldIgnore(),
4951 args: PatternsToMatch[i].getHwModeFeatures());
4952 }
4953
4954 LLVM_DEBUG(dbgs() << "\n");
4955 }
4956}
4957
4958unsigned CodeGenDAGPatterns::getNewUID() {
4959 RecordKeeper &MutableRC = const_cast<RecordKeeper &>(Records);
4960 return Record::getNewUID(RK&: MutableRC);
4961}
4962