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