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