xref: /freebsd/contrib/llvm-project/llvm/include/llvm/IR/PatternMatch.h (revision e0c4386e7e71d93b0edc0c8fa156263fc4a8b0b6)
1 //===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===//
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 provides a simple and efficient mechanism for performing general
10 // tree-based pattern matches on the LLVM IR. The power of these routines is
11 // that it allows you to write concise patterns that are expressive and easy to
12 // understand. The other major advantage of this is that it allows you to
13 // trivially capture/bind elements in the pattern to variables. For example,
14 // you can do something like this:
15 //
16 //  Value *Exp = ...
17 //  Value *X, *Y;  ConstantInt *C1, *C2;      // (X & C1) | (Y & C2)
18 //  if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)),
19 //                      m_And(m_Value(Y), m_ConstantInt(C2))))) {
20 //    ... Pattern is matched and variables are bound ...
21 //  }
22 //
23 // This is primarily useful to things like the instruction combiner, but can
24 // also be useful for static analysis tools or code generators.
25 //
26 //===----------------------------------------------------------------------===//
27 
28 #ifndef LLVM_IR_PATTERNMATCH_H
29 #define LLVM_IR_PATTERNMATCH_H
30 
31 #include "llvm/ADT/APFloat.h"
32 #include "llvm/ADT/APInt.h"
33 #include "llvm/IR/Constant.h"
34 #include "llvm/IR/Constants.h"
35 #include "llvm/IR/DataLayout.h"
36 #include "llvm/IR/InstrTypes.h"
37 #include "llvm/IR/Instruction.h"
38 #include "llvm/IR/Instructions.h"
39 #include "llvm/IR/IntrinsicInst.h"
40 #include "llvm/IR/Intrinsics.h"
41 #include "llvm/IR/Operator.h"
42 #include "llvm/IR/Value.h"
43 #include "llvm/Support/Casting.h"
44 #include <cstdint>
45 
46 namespace llvm {
47 namespace PatternMatch {
48 
49 template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) {
50   return const_cast<Pattern &>(P).match(V);
51 }
52 
53 template <typename Pattern> bool match(ArrayRef<int> Mask, const Pattern &P) {
54   return const_cast<Pattern &>(P).match(Mask);
55 }
56 
57 template <typename SubPattern_t> struct OneUse_match {
58   SubPattern_t SubPattern;
59 
60   OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
61 
62   template <typename OpTy> bool match(OpTy *V) {
63     return V->hasOneUse() && SubPattern.match(V);
64   }
65 };
66 
67 template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) {
68   return SubPattern;
69 }
70 
71 template <typename Class> struct class_match {
72   template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
73 };
74 
75 /// Match an arbitrary value and ignore it.
76 inline class_match<Value> m_Value() { return class_match<Value>(); }
77 
78 /// Match an arbitrary unary operation and ignore it.
79 inline class_match<UnaryOperator> m_UnOp() {
80   return class_match<UnaryOperator>();
81 }
82 
83 /// Match an arbitrary binary operation and ignore it.
84 inline class_match<BinaryOperator> m_BinOp() {
85   return class_match<BinaryOperator>();
86 }
87 
88 /// Matches any compare instruction and ignore it.
89 inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
90 
91 struct undef_match {
92   static bool check(const Value *V) {
93     if (isa<UndefValue>(V))
94       return true;
95 
96     const auto *CA = dyn_cast<ConstantAggregate>(V);
97     if (!CA)
98       return false;
99 
100     SmallPtrSet<const ConstantAggregate *, 8> Seen;
101     SmallVector<const ConstantAggregate *, 8> Worklist;
102 
103     // Either UndefValue, PoisonValue, or an aggregate that only contains
104     // these is accepted by matcher.
105     // CheckValue returns false if CA cannot satisfy this constraint.
106     auto CheckValue = [&](const ConstantAggregate *CA) {
107       for (const Value *Op : CA->operand_values()) {
108         if (isa<UndefValue>(Op))
109           continue;
110 
111         const auto *CA = dyn_cast<ConstantAggregate>(Op);
112         if (!CA)
113           return false;
114         if (Seen.insert(CA).second)
115           Worklist.emplace_back(CA);
116       }
117 
118       return true;
119     };
120 
121     if (!CheckValue(CA))
122       return false;
123 
124     while (!Worklist.empty()) {
125       if (!CheckValue(Worklist.pop_back_val()))
126         return false;
127     }
128     return true;
129   }
130   template <typename ITy> bool match(ITy *V) { return check(V); }
131 };
132 
133 /// Match an arbitrary undef constant. This matches poison as well.
134 /// If this is an aggregate and contains a non-aggregate element that is
135 /// neither undef nor poison, the aggregate is not matched.
136 inline auto m_Undef() { return undef_match(); }
137 
138 /// Match an arbitrary poison constant.
139 inline class_match<PoisonValue> m_Poison() {
140   return class_match<PoisonValue>();
141 }
142 
143 /// Match an arbitrary Constant and ignore it.
144 inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
145 
146 /// Match an arbitrary ConstantInt and ignore it.
147 inline class_match<ConstantInt> m_ConstantInt() {
148   return class_match<ConstantInt>();
149 }
150 
151 /// Match an arbitrary ConstantFP and ignore it.
152 inline class_match<ConstantFP> m_ConstantFP() {
153   return class_match<ConstantFP>();
154 }
155 
156 struct constantexpr_match {
157   template <typename ITy> bool match(ITy *V) {
158     auto *C = dyn_cast<Constant>(V);
159     return C && (isa<ConstantExpr>(C) || C->containsConstantExpression());
160   }
161 };
162 
163 /// Match a constant expression or a constant that contains a constant
164 /// expression.
165 inline constantexpr_match m_ConstantExpr() { return constantexpr_match(); }
166 
167 /// Match an arbitrary basic block value and ignore it.
168 inline class_match<BasicBlock> m_BasicBlock() {
169   return class_match<BasicBlock>();
170 }
171 
172 /// Inverting matcher
173 template <typename Ty> struct match_unless {
174   Ty M;
175 
176   match_unless(const Ty &Matcher) : M(Matcher) {}
177 
178   template <typename ITy> bool match(ITy *V) { return !M.match(V); }
179 };
180 
181 /// Match if the inner matcher does *NOT* match.
182 template <typename Ty> inline match_unless<Ty> m_Unless(const Ty &M) {
183   return match_unless<Ty>(M);
184 }
185 
186 /// Matching combinators
187 template <typename LTy, typename RTy> struct match_combine_or {
188   LTy L;
189   RTy R;
190 
191   match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
192 
193   template <typename ITy> bool match(ITy *V) {
194     if (L.match(V))
195       return true;
196     if (R.match(V))
197       return true;
198     return false;
199   }
200 };
201 
202 template <typename LTy, typename RTy> struct match_combine_and {
203   LTy L;
204   RTy R;
205 
206   match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
207 
208   template <typename ITy> bool match(ITy *V) {
209     if (L.match(V))
210       if (R.match(V))
211         return true;
212     return false;
213   }
214 };
215 
216 /// Combine two pattern matchers matching L || R
217 template <typename LTy, typename RTy>
218 inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
219   return match_combine_or<LTy, RTy>(L, R);
220 }
221 
222 /// Combine two pattern matchers matching L && R
223 template <typename LTy, typename RTy>
224 inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
225   return match_combine_and<LTy, RTy>(L, R);
226 }
227 
228 struct apint_match {
229   const APInt *&Res;
230   bool AllowUndef;
231 
232   apint_match(const APInt *&Res, bool AllowUndef)
233       : Res(Res), AllowUndef(AllowUndef) {}
234 
235   template <typename ITy> bool match(ITy *V) {
236     if (auto *CI = dyn_cast<ConstantInt>(V)) {
237       Res = &CI->getValue();
238       return true;
239     }
240     if (V->getType()->isVectorTy())
241       if (const auto *C = dyn_cast<Constant>(V))
242         if (auto *CI =
243                 dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowUndef))) {
244           Res = &CI->getValue();
245           return true;
246         }
247     return false;
248   }
249 };
250 // Either constexpr if or renaming ConstantFP::getValueAPF to
251 // ConstantFP::getValue is needed to do it via single template
252 // function for both apint/apfloat.
253 struct apfloat_match {
254   const APFloat *&Res;
255   bool AllowUndef;
256 
257   apfloat_match(const APFloat *&Res, bool AllowUndef)
258       : Res(Res), AllowUndef(AllowUndef) {}
259 
260   template <typename ITy> bool match(ITy *V) {
261     if (auto *CI = dyn_cast<ConstantFP>(V)) {
262       Res = &CI->getValueAPF();
263       return true;
264     }
265     if (V->getType()->isVectorTy())
266       if (const auto *C = dyn_cast<Constant>(V))
267         if (auto *CI =
268                 dyn_cast_or_null<ConstantFP>(C->getSplatValue(AllowUndef))) {
269           Res = &CI->getValueAPF();
270           return true;
271         }
272     return false;
273   }
274 };
275 
276 /// Match a ConstantInt or splatted ConstantVector, binding the
277 /// specified pointer to the contained APInt.
278 inline apint_match m_APInt(const APInt *&Res) {
279   // Forbid undefs by default to maintain previous behavior.
280   return apint_match(Res, /* AllowUndef */ false);
281 }
282 
283 /// Match APInt while allowing undefs in splat vector constants.
284 inline apint_match m_APIntAllowUndef(const APInt *&Res) {
285   return apint_match(Res, /* AllowUndef */ true);
286 }
287 
288 /// Match APInt while forbidding undefs in splat vector constants.
289 inline apint_match m_APIntForbidUndef(const APInt *&Res) {
290   return apint_match(Res, /* AllowUndef */ false);
291 }
292 
293 /// Match a ConstantFP or splatted ConstantVector, binding the
294 /// specified pointer to the contained APFloat.
295 inline apfloat_match m_APFloat(const APFloat *&Res) {
296   // Forbid undefs by default to maintain previous behavior.
297   return apfloat_match(Res, /* AllowUndef */ false);
298 }
299 
300 /// Match APFloat while allowing undefs in splat vector constants.
301 inline apfloat_match m_APFloatAllowUndef(const APFloat *&Res) {
302   return apfloat_match(Res, /* AllowUndef */ true);
303 }
304 
305 /// Match APFloat while forbidding undefs in splat vector constants.
306 inline apfloat_match m_APFloatForbidUndef(const APFloat *&Res) {
307   return apfloat_match(Res, /* AllowUndef */ false);
308 }
309 
310 template <int64_t Val> struct constantint_match {
311   template <typename ITy> bool match(ITy *V) {
312     if (const auto *CI = dyn_cast<ConstantInt>(V)) {
313       const APInt &CIV = CI->getValue();
314       if (Val >= 0)
315         return CIV == static_cast<uint64_t>(Val);
316       // If Val is negative, and CI is shorter than it, truncate to the right
317       // number of bits.  If it is larger, then we have to sign extend.  Just
318       // compare their negated values.
319       return -CIV == -Val;
320     }
321     return false;
322   }
323 };
324 
325 /// Match a ConstantInt with a specific value.
326 template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
327   return constantint_match<Val>();
328 }
329 
330 /// This helper class is used to match constant scalars, vector splats,
331 /// and fixed width vectors that satisfy a specified predicate.
332 /// For fixed width vector constants, undefined elements are ignored.
333 template <typename Predicate, typename ConstantVal>
334 struct cstval_pred_ty : public Predicate {
335   template <typename ITy> bool match(ITy *V) {
336     if (const auto *CV = dyn_cast<ConstantVal>(V))
337       return this->isValue(CV->getValue());
338     if (const auto *VTy = dyn_cast<VectorType>(V->getType())) {
339       if (const auto *C = dyn_cast<Constant>(V)) {
340         if (const auto *CV = dyn_cast_or_null<ConstantVal>(C->getSplatValue()))
341           return this->isValue(CV->getValue());
342 
343         // Number of elements of a scalable vector unknown at compile time
344         auto *FVTy = dyn_cast<FixedVectorType>(VTy);
345         if (!FVTy)
346           return false;
347 
348         // Non-splat vector constant: check each element for a match.
349         unsigned NumElts = FVTy->getNumElements();
350         assert(NumElts != 0 && "Constant vector with no elements?");
351         bool HasNonUndefElements = false;
352         for (unsigned i = 0; i != NumElts; ++i) {
353           Constant *Elt = C->getAggregateElement(i);
354           if (!Elt)
355             return false;
356           if (isa<UndefValue>(Elt))
357             continue;
358           auto *CV = dyn_cast<ConstantVal>(Elt);
359           if (!CV || !this->isValue(CV->getValue()))
360             return false;
361           HasNonUndefElements = true;
362         }
363         return HasNonUndefElements;
364       }
365     }
366     return false;
367   }
368 };
369 
370 /// specialization of cstval_pred_ty for ConstantInt
371 template <typename Predicate>
372 using cst_pred_ty = cstval_pred_ty<Predicate, ConstantInt>;
373 
374 /// specialization of cstval_pred_ty for ConstantFP
375 template <typename Predicate>
376 using cstfp_pred_ty = cstval_pred_ty<Predicate, ConstantFP>;
377 
378 /// This helper class is used to match scalar and vector constants that
379 /// satisfy a specified predicate, and bind them to an APInt.
380 template <typename Predicate> struct api_pred_ty : public Predicate {
381   const APInt *&Res;
382 
383   api_pred_ty(const APInt *&R) : Res(R) {}
384 
385   template <typename ITy> bool match(ITy *V) {
386     if (const auto *CI = dyn_cast<ConstantInt>(V))
387       if (this->isValue(CI->getValue())) {
388         Res = &CI->getValue();
389         return true;
390       }
391     if (V->getType()->isVectorTy())
392       if (const auto *C = dyn_cast<Constant>(V))
393         if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
394           if (this->isValue(CI->getValue())) {
395             Res = &CI->getValue();
396             return true;
397           }
398 
399     return false;
400   }
401 };
402 
403 /// This helper class is used to match scalar and vector constants that
404 /// satisfy a specified predicate, and bind them to an APFloat.
405 /// Undefs are allowed in splat vector constants.
406 template <typename Predicate> struct apf_pred_ty : public Predicate {
407   const APFloat *&Res;
408 
409   apf_pred_ty(const APFloat *&R) : Res(R) {}
410 
411   template <typename ITy> bool match(ITy *V) {
412     if (const auto *CI = dyn_cast<ConstantFP>(V))
413       if (this->isValue(CI->getValue())) {
414         Res = &CI->getValue();
415         return true;
416       }
417     if (V->getType()->isVectorTy())
418       if (const auto *C = dyn_cast<Constant>(V))
419         if (auto *CI = dyn_cast_or_null<ConstantFP>(
420                 C->getSplatValue(/* AllowUndef */ true)))
421           if (this->isValue(CI->getValue())) {
422             Res = &CI->getValue();
423             return true;
424           }
425 
426     return false;
427   }
428 };
429 
430 ///////////////////////////////////////////////////////////////////////////////
431 //
432 // Encapsulate constant value queries for use in templated predicate matchers.
433 // This allows checking if constants match using compound predicates and works
434 // with vector constants, possibly with relaxed constraints. For example, ignore
435 // undef values.
436 //
437 ///////////////////////////////////////////////////////////////////////////////
438 
439 struct is_any_apint {
440   bool isValue(const APInt &C) { return true; }
441 };
442 /// Match an integer or vector with any integral constant.
443 /// For vectors, this includes constants with undefined elements.
444 inline cst_pred_ty<is_any_apint> m_AnyIntegralConstant() {
445   return cst_pred_ty<is_any_apint>();
446 }
447 
448 struct is_shifted_mask {
449   bool isValue(const APInt &C) { return C.isShiftedMask(); }
450 };
451 
452 inline cst_pred_ty<is_shifted_mask> m_ShiftedMask() {
453   return cst_pred_ty<is_shifted_mask>();
454 }
455 
456 struct is_all_ones {
457   bool isValue(const APInt &C) { return C.isAllOnes(); }
458 };
459 /// Match an integer or vector with all bits set.
460 /// For vectors, this includes constants with undefined elements.
461 inline cst_pred_ty<is_all_ones> m_AllOnes() {
462   return cst_pred_ty<is_all_ones>();
463 }
464 
465 struct is_maxsignedvalue {
466   bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
467 };
468 /// Match an integer or vector with values having all bits except for the high
469 /// bit set (0x7f...).
470 /// For vectors, this includes constants with undefined elements.
471 inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
472   return cst_pred_ty<is_maxsignedvalue>();
473 }
474 inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
475   return V;
476 }
477 
478 struct is_negative {
479   bool isValue(const APInt &C) { return C.isNegative(); }
480 };
481 /// Match an integer or vector of negative values.
482 /// For vectors, this includes constants with undefined elements.
483 inline cst_pred_ty<is_negative> m_Negative() {
484   return cst_pred_ty<is_negative>();
485 }
486 inline api_pred_ty<is_negative> m_Negative(const APInt *&V) { return V; }
487 
488 struct is_nonnegative {
489   bool isValue(const APInt &C) { return C.isNonNegative(); }
490 };
491 /// Match an integer or vector of non-negative values.
492 /// For vectors, this includes constants with undefined elements.
493 inline cst_pred_ty<is_nonnegative> m_NonNegative() {
494   return cst_pred_ty<is_nonnegative>();
495 }
496 inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) { return V; }
497 
498 struct is_strictlypositive {
499   bool isValue(const APInt &C) { return C.isStrictlyPositive(); }
500 };
501 /// Match an integer or vector of strictly positive values.
502 /// For vectors, this includes constants with undefined elements.
503 inline cst_pred_ty<is_strictlypositive> m_StrictlyPositive() {
504   return cst_pred_ty<is_strictlypositive>();
505 }
506 inline api_pred_ty<is_strictlypositive> m_StrictlyPositive(const APInt *&V) {
507   return V;
508 }
509 
510 struct is_nonpositive {
511   bool isValue(const APInt &C) { return C.isNonPositive(); }
512 };
513 /// Match an integer or vector of non-positive values.
514 /// For vectors, this includes constants with undefined elements.
515 inline cst_pred_ty<is_nonpositive> m_NonPositive() {
516   return cst_pred_ty<is_nonpositive>();
517 }
518 inline api_pred_ty<is_nonpositive> m_NonPositive(const APInt *&V) { return V; }
519 
520 struct is_one {
521   bool isValue(const APInt &C) { return C.isOne(); }
522 };
523 /// Match an integer 1 or a vector with all elements equal to 1.
524 /// For vectors, this includes constants with undefined elements.
525 inline cst_pred_ty<is_one> m_One() { return cst_pred_ty<is_one>(); }
526 
527 struct is_zero_int {
528   bool isValue(const APInt &C) { return C.isZero(); }
529 };
530 /// Match an integer 0 or a vector with all elements equal to 0.
531 /// For vectors, this includes constants with undefined elements.
532 inline cst_pred_ty<is_zero_int> m_ZeroInt() {
533   return cst_pred_ty<is_zero_int>();
534 }
535 
536 struct is_zero {
537   template <typename ITy> bool match(ITy *V) {
538     auto *C = dyn_cast<Constant>(V);
539     // FIXME: this should be able to do something for scalable vectors
540     return C && (C->isNullValue() || cst_pred_ty<is_zero_int>().match(C));
541   }
542 };
543 /// Match any null constant or a vector with all elements equal to 0.
544 /// For vectors, this includes constants with undefined elements.
545 inline is_zero m_Zero() { return is_zero(); }
546 
547 struct is_power2 {
548   bool isValue(const APInt &C) { return C.isPowerOf2(); }
549 };
550 /// Match an integer or vector power-of-2.
551 /// For vectors, this includes constants with undefined elements.
552 inline cst_pred_ty<is_power2> m_Power2() { return cst_pred_ty<is_power2>(); }
553 inline api_pred_ty<is_power2> m_Power2(const APInt *&V) { return V; }
554 
555 struct is_negated_power2 {
556   bool isValue(const APInt &C) { return C.isNegatedPowerOf2(); }
557 };
558 /// Match a integer or vector negated power-of-2.
559 /// For vectors, this includes constants with undefined elements.
560 inline cst_pred_ty<is_negated_power2> m_NegatedPower2() {
561   return cst_pred_ty<is_negated_power2>();
562 }
563 inline api_pred_ty<is_negated_power2> m_NegatedPower2(const APInt *&V) {
564   return V;
565 }
566 
567 struct is_power2_or_zero {
568   bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
569 };
570 /// Match an integer or vector of 0 or power-of-2 values.
571 /// For vectors, this includes constants with undefined elements.
572 inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
573   return cst_pred_ty<is_power2_or_zero>();
574 }
575 inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
576   return V;
577 }
578 
579 struct is_sign_mask {
580   bool isValue(const APInt &C) { return C.isSignMask(); }
581 };
582 /// Match an integer or vector with only the sign bit(s) set.
583 /// For vectors, this includes constants with undefined elements.
584 inline cst_pred_ty<is_sign_mask> m_SignMask() {
585   return cst_pred_ty<is_sign_mask>();
586 }
587 
588 struct is_lowbit_mask {
589   bool isValue(const APInt &C) { return C.isMask(); }
590 };
591 /// Match an integer or vector with only the low bit(s) set.
592 /// For vectors, this includes constants with undefined elements.
593 inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() {
594   return cst_pred_ty<is_lowbit_mask>();
595 }
596 inline api_pred_ty<is_lowbit_mask> m_LowBitMask(const APInt *&V) { return V; }
597 
598 struct icmp_pred_with_threshold {
599   ICmpInst::Predicate Pred;
600   const APInt *Thr;
601   bool isValue(const APInt &C) { return ICmpInst::compare(C, *Thr, Pred); }
602 };
603 /// Match an integer or vector with every element comparing 'pred' (eg/ne/...)
604 /// to Threshold. For vectors, this includes constants with undefined elements.
605 inline cst_pred_ty<icmp_pred_with_threshold>
606 m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold) {
607   cst_pred_ty<icmp_pred_with_threshold> P;
608   P.Pred = Predicate;
609   P.Thr = &Threshold;
610   return P;
611 }
612 
613 struct is_nan {
614   bool isValue(const APFloat &C) { return C.isNaN(); }
615 };
616 /// Match an arbitrary NaN constant. This includes quiet and signalling nans.
617 /// For vectors, this includes constants with undefined elements.
618 inline cstfp_pred_ty<is_nan> m_NaN() { return cstfp_pred_ty<is_nan>(); }
619 
620 struct is_nonnan {
621   bool isValue(const APFloat &C) { return !C.isNaN(); }
622 };
623 /// Match a non-NaN FP constant.
624 /// For vectors, this includes constants with undefined elements.
625 inline cstfp_pred_ty<is_nonnan> m_NonNaN() {
626   return cstfp_pred_ty<is_nonnan>();
627 }
628 
629 struct is_inf {
630   bool isValue(const APFloat &C) { return C.isInfinity(); }
631 };
632 /// Match a positive or negative infinity FP constant.
633 /// For vectors, this includes constants with undefined elements.
634 inline cstfp_pred_ty<is_inf> m_Inf() { return cstfp_pred_ty<is_inf>(); }
635 
636 struct is_noninf {
637   bool isValue(const APFloat &C) { return !C.isInfinity(); }
638 };
639 /// Match a non-infinity FP constant, i.e. finite or NaN.
640 /// For vectors, this includes constants with undefined elements.
641 inline cstfp_pred_ty<is_noninf> m_NonInf() {
642   return cstfp_pred_ty<is_noninf>();
643 }
644 
645 struct is_finite {
646   bool isValue(const APFloat &C) { return C.isFinite(); }
647 };
648 /// Match a finite FP constant, i.e. not infinity or NaN.
649 /// For vectors, this includes constants with undefined elements.
650 inline cstfp_pred_ty<is_finite> m_Finite() {
651   return cstfp_pred_ty<is_finite>();
652 }
653 inline apf_pred_ty<is_finite> m_Finite(const APFloat *&V) { return V; }
654 
655 struct is_finitenonzero {
656   bool isValue(const APFloat &C) { return C.isFiniteNonZero(); }
657 };
658 /// Match a finite non-zero FP constant.
659 /// For vectors, this includes constants with undefined elements.
660 inline cstfp_pred_ty<is_finitenonzero> m_FiniteNonZero() {
661   return cstfp_pred_ty<is_finitenonzero>();
662 }
663 inline apf_pred_ty<is_finitenonzero> m_FiniteNonZero(const APFloat *&V) {
664   return V;
665 }
666 
667 struct is_any_zero_fp {
668   bool isValue(const APFloat &C) { return C.isZero(); }
669 };
670 /// Match a floating-point negative zero or positive zero.
671 /// For vectors, this includes constants with undefined elements.
672 inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
673   return cstfp_pred_ty<is_any_zero_fp>();
674 }
675 
676 struct is_pos_zero_fp {
677   bool isValue(const APFloat &C) { return C.isPosZero(); }
678 };
679 /// Match a floating-point positive zero.
680 /// For vectors, this includes constants with undefined elements.
681 inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
682   return cstfp_pred_ty<is_pos_zero_fp>();
683 }
684 
685 struct is_neg_zero_fp {
686   bool isValue(const APFloat &C) { return C.isNegZero(); }
687 };
688 /// Match a floating-point negative zero.
689 /// For vectors, this includes constants with undefined elements.
690 inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
691   return cstfp_pred_ty<is_neg_zero_fp>();
692 }
693 
694 struct is_non_zero_fp {
695   bool isValue(const APFloat &C) { return C.isNonZero(); }
696 };
697 /// Match a floating-point non-zero.
698 /// For vectors, this includes constants with undefined elements.
699 inline cstfp_pred_ty<is_non_zero_fp> m_NonZeroFP() {
700   return cstfp_pred_ty<is_non_zero_fp>();
701 }
702 
703 ///////////////////////////////////////////////////////////////////////////////
704 
705 template <typename Class> struct bind_ty {
706   Class *&VR;
707 
708   bind_ty(Class *&V) : VR(V) {}
709 
710   template <typename ITy> bool match(ITy *V) {
711     if (auto *CV = dyn_cast<Class>(V)) {
712       VR = CV;
713       return true;
714     }
715     return false;
716   }
717 };
718 
719 /// Match a value, capturing it if we match.
720 inline bind_ty<Value> m_Value(Value *&V) { return V; }
721 inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
722 
723 /// Match an instruction, capturing it if we match.
724 inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
725 /// Match a unary operator, capturing it if we match.
726 inline bind_ty<UnaryOperator> m_UnOp(UnaryOperator *&I) { return I; }
727 /// Match a binary operator, capturing it if we match.
728 inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
729 /// Match a with overflow intrinsic, capturing it if we match.
730 inline bind_ty<WithOverflowInst> m_WithOverflowInst(WithOverflowInst *&I) {
731   return I;
732 }
733 inline bind_ty<const WithOverflowInst>
734 m_WithOverflowInst(const WithOverflowInst *&I) {
735   return I;
736 }
737 
738 /// Match a Constant, capturing the value if we match.
739 inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
740 
741 /// Match a ConstantInt, capturing the value if we match.
742 inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
743 
744 /// Match a ConstantFP, capturing the value if we match.
745 inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
746 
747 /// Match a ConstantExpr, capturing the value if we match.
748 inline bind_ty<ConstantExpr> m_ConstantExpr(ConstantExpr *&C) { return C; }
749 
750 /// Match a basic block value, capturing it if we match.
751 inline bind_ty<BasicBlock> m_BasicBlock(BasicBlock *&V) { return V; }
752 inline bind_ty<const BasicBlock> m_BasicBlock(const BasicBlock *&V) {
753   return V;
754 }
755 
756 /// Match an arbitrary immediate Constant and ignore it.
757 inline match_combine_and<class_match<Constant>,
758                          match_unless<constantexpr_match>>
759 m_ImmConstant() {
760   return m_CombineAnd(m_Constant(), m_Unless(m_ConstantExpr()));
761 }
762 
763 /// Match an immediate Constant, capturing the value if we match.
764 inline match_combine_and<bind_ty<Constant>,
765                          match_unless<constantexpr_match>>
766 m_ImmConstant(Constant *&C) {
767   return m_CombineAnd(m_Constant(C), m_Unless(m_ConstantExpr()));
768 }
769 
770 /// Match a specified Value*.
771 struct specificval_ty {
772   const Value *Val;
773 
774   specificval_ty(const Value *V) : Val(V) {}
775 
776   template <typename ITy> bool match(ITy *V) { return V == Val; }
777 };
778 
779 /// Match if we have a specific specified value.
780 inline specificval_ty m_Specific(const Value *V) { return V; }
781 
782 /// Stores a reference to the Value *, not the Value * itself,
783 /// thus can be used in commutative matchers.
784 template <typename Class> struct deferredval_ty {
785   Class *const &Val;
786 
787   deferredval_ty(Class *const &V) : Val(V) {}
788 
789   template <typename ITy> bool match(ITy *const V) { return V == Val; }
790 };
791 
792 /// Like m_Specific(), but works if the specific value to match is determined
793 /// as part of the same match() expression. For example:
794 /// m_Add(m_Value(X), m_Specific(X)) is incorrect, because m_Specific() will
795 /// bind X before the pattern match starts.
796 /// m_Add(m_Value(X), m_Deferred(X)) is correct, and will check against
797 /// whichever value m_Value(X) populated.
798 inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; }
799 inline deferredval_ty<const Value> m_Deferred(const Value *const &V) {
800   return V;
801 }
802 
803 /// Match a specified floating point value or vector of all elements of
804 /// that value.
805 struct specific_fpval {
806   double Val;
807 
808   specific_fpval(double V) : Val(V) {}
809 
810   template <typename ITy> bool match(ITy *V) {
811     if (const auto *CFP = dyn_cast<ConstantFP>(V))
812       return CFP->isExactlyValue(Val);
813     if (V->getType()->isVectorTy())
814       if (const auto *C = dyn_cast<Constant>(V))
815         if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
816           return CFP->isExactlyValue(Val);
817     return false;
818   }
819 };
820 
821 /// Match a specific floating point value or vector with all elements
822 /// equal to the value.
823 inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
824 
825 /// Match a float 1.0 or vector with all elements equal to 1.0.
826 inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
827 
828 struct bind_const_intval_ty {
829   uint64_t &VR;
830 
831   bind_const_intval_ty(uint64_t &V) : VR(V) {}
832 
833   template <typename ITy> bool match(ITy *V) {
834     if (const auto *CV = dyn_cast<ConstantInt>(V))
835       if (CV->getValue().ule(UINT64_MAX)) {
836         VR = CV->getZExtValue();
837         return true;
838       }
839     return false;
840   }
841 };
842 
843 /// Match a specified integer value or vector of all elements of that
844 /// value.
845 template <bool AllowUndefs> struct specific_intval {
846   APInt Val;
847 
848   specific_intval(APInt V) : Val(std::move(V)) {}
849 
850   template <typename ITy> bool match(ITy *V) {
851     const auto *CI = dyn_cast<ConstantInt>(V);
852     if (!CI && V->getType()->isVectorTy())
853       if (const auto *C = dyn_cast<Constant>(V))
854         CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowUndefs));
855 
856     return CI && APInt::isSameValue(CI->getValue(), Val);
857   }
858 };
859 
860 /// Match a specific integer value or vector with all elements equal to
861 /// the value.
862 inline specific_intval<false> m_SpecificInt(APInt V) {
863   return specific_intval<false>(std::move(V));
864 }
865 
866 inline specific_intval<false> m_SpecificInt(uint64_t V) {
867   return m_SpecificInt(APInt(64, V));
868 }
869 
870 inline specific_intval<true> m_SpecificIntAllowUndef(APInt V) {
871   return specific_intval<true>(std::move(V));
872 }
873 
874 inline specific_intval<true> m_SpecificIntAllowUndef(uint64_t V) {
875   return m_SpecificIntAllowUndef(APInt(64, V));
876 }
877 
878 /// Match a ConstantInt and bind to its value.  This does not match
879 /// ConstantInts wider than 64-bits.
880 inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
881 
882 /// Match a specified basic block value.
883 struct specific_bbval {
884   BasicBlock *Val;
885 
886   specific_bbval(BasicBlock *Val) : Val(Val) {}
887 
888   template <typename ITy> bool match(ITy *V) {
889     const auto *BB = dyn_cast<BasicBlock>(V);
890     return BB && BB == Val;
891   }
892 };
893 
894 /// Match a specific basic block value.
895 inline specific_bbval m_SpecificBB(BasicBlock *BB) {
896   return specific_bbval(BB);
897 }
898 
899 /// A commutative-friendly version of m_Specific().
900 inline deferredval_ty<BasicBlock> m_Deferred(BasicBlock *const &BB) {
901   return BB;
902 }
903 inline deferredval_ty<const BasicBlock>
904 m_Deferred(const BasicBlock *const &BB) {
905   return BB;
906 }
907 
908 //===----------------------------------------------------------------------===//
909 // Matcher for any binary operator.
910 //
911 template <typename LHS_t, typename RHS_t, bool Commutable = false>
912 struct AnyBinaryOp_match {
913   LHS_t L;
914   RHS_t R;
915 
916   // The evaluation order is always stable, regardless of Commutability.
917   // The LHS is always matched first.
918   AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
919 
920   template <typename OpTy> bool match(OpTy *V) {
921     if (auto *I = dyn_cast<BinaryOperator>(V))
922       return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
923              (Commutable && L.match(I->getOperand(1)) &&
924               R.match(I->getOperand(0)));
925     return false;
926   }
927 };
928 
929 template <typename LHS, typename RHS>
930 inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
931   return AnyBinaryOp_match<LHS, RHS>(L, R);
932 }
933 
934 //===----------------------------------------------------------------------===//
935 // Matcher for any unary operator.
936 // TODO fuse unary, binary matcher into n-ary matcher
937 //
938 template <typename OP_t> struct AnyUnaryOp_match {
939   OP_t X;
940 
941   AnyUnaryOp_match(const OP_t &X) : X(X) {}
942 
943   template <typename OpTy> bool match(OpTy *V) {
944     if (auto *I = dyn_cast<UnaryOperator>(V))
945       return X.match(I->getOperand(0));
946     return false;
947   }
948 };
949 
950 template <typename OP_t> inline AnyUnaryOp_match<OP_t> m_UnOp(const OP_t &X) {
951   return AnyUnaryOp_match<OP_t>(X);
952 }
953 
954 //===----------------------------------------------------------------------===//
955 // Matchers for specific binary operators.
956 //
957 
958 template <typename LHS_t, typename RHS_t, unsigned Opcode,
959           bool Commutable = false>
960 struct BinaryOp_match {
961   LHS_t L;
962   RHS_t R;
963 
964   // The evaluation order is always stable, regardless of Commutability.
965   // The LHS is always matched first.
966   BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
967 
968   template <typename OpTy> inline bool match(unsigned Opc, OpTy *V) {
969     if (V->getValueID() == Value::InstructionVal + Opc) {
970       auto *I = cast<BinaryOperator>(V);
971       return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
972              (Commutable && L.match(I->getOperand(1)) &&
973               R.match(I->getOperand(0)));
974     }
975     if (auto *CE = dyn_cast<ConstantExpr>(V))
976       return CE->getOpcode() == Opc &&
977              ((L.match(CE->getOperand(0)) && R.match(CE->getOperand(1))) ||
978               (Commutable && L.match(CE->getOperand(1)) &&
979                R.match(CE->getOperand(0))));
980     return false;
981   }
982 
983   template <typename OpTy> bool match(OpTy *V) { return match(Opcode, V); }
984 };
985 
986 template <typename LHS, typename RHS>
987 inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
988                                                         const RHS &R) {
989   return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
990 }
991 
992 template <typename LHS, typename RHS>
993 inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
994                                                           const RHS &R) {
995   return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
996 }
997 
998 template <typename LHS, typename RHS>
999 inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
1000                                                         const RHS &R) {
1001   return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
1002 }
1003 
1004 template <typename LHS, typename RHS>
1005 inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
1006                                                           const RHS &R) {
1007   return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
1008 }
1009 
1010 template <typename Op_t> struct FNeg_match {
1011   Op_t X;
1012 
1013   FNeg_match(const Op_t &Op) : X(Op) {}
1014   template <typename OpTy> bool match(OpTy *V) {
1015     auto *FPMO = dyn_cast<FPMathOperator>(V);
1016     if (!FPMO)
1017       return false;
1018 
1019     if (FPMO->getOpcode() == Instruction::FNeg)
1020       return X.match(FPMO->getOperand(0));
1021 
1022     if (FPMO->getOpcode() == Instruction::FSub) {
1023       if (FPMO->hasNoSignedZeros()) {
1024         // With 'nsz', any zero goes.
1025         if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0)))
1026           return false;
1027       } else {
1028         // Without 'nsz', we need fsub -0.0, X exactly.
1029         if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0)))
1030           return false;
1031       }
1032 
1033       return X.match(FPMO->getOperand(1));
1034     }
1035 
1036     return false;
1037   }
1038 };
1039 
1040 /// Match 'fneg X' as 'fsub -0.0, X'.
1041 template <typename OpTy> inline FNeg_match<OpTy> m_FNeg(const OpTy &X) {
1042   return FNeg_match<OpTy>(X);
1043 }
1044 
1045 /// Match 'fneg X' as 'fsub +-0.0, X'.
1046 template <typename RHS>
1047 inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub>
1048 m_FNegNSZ(const RHS &X) {
1049   return m_FSub(m_AnyZeroFP(), X);
1050 }
1051 
1052 template <typename LHS, typename RHS>
1053 inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
1054                                                         const RHS &R) {
1055   return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
1056 }
1057 
1058 template <typename LHS, typename RHS>
1059 inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
1060                                                           const RHS &R) {
1061   return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
1062 }
1063 
1064 template <typename LHS, typename RHS>
1065 inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
1066                                                           const RHS &R) {
1067   return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
1068 }
1069 
1070 template <typename LHS, typename RHS>
1071 inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
1072                                                           const RHS &R) {
1073   return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
1074 }
1075 
1076 template <typename LHS, typename RHS>
1077 inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
1078                                                           const RHS &R) {
1079   return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
1080 }
1081 
1082 template <typename LHS, typename RHS>
1083 inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
1084                                                           const RHS &R) {
1085   return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
1086 }
1087 
1088 template <typename LHS, typename RHS>
1089 inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
1090                                                           const RHS &R) {
1091   return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
1092 }
1093 
1094 template <typename LHS, typename RHS>
1095 inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
1096                                                           const RHS &R) {
1097   return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
1098 }
1099 
1100 template <typename LHS, typename RHS>
1101 inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
1102                                                         const RHS &R) {
1103   return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
1104 }
1105 
1106 template <typename LHS, typename RHS>
1107 inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
1108                                                       const RHS &R) {
1109   return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
1110 }
1111 
1112 template <typename LHS, typename RHS>
1113 inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
1114                                                         const RHS &R) {
1115   return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
1116 }
1117 
1118 template <typename LHS, typename RHS>
1119 inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
1120                                                         const RHS &R) {
1121   return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
1122 }
1123 
1124 template <typename LHS, typename RHS>
1125 inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
1126                                                           const RHS &R) {
1127   return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
1128 }
1129 
1130 template <typename LHS, typename RHS>
1131 inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
1132                                                           const RHS &R) {
1133   return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
1134 }
1135 
1136 template <typename LHS_t, typename RHS_t, unsigned Opcode,
1137           unsigned WrapFlags = 0>
1138 struct OverflowingBinaryOp_match {
1139   LHS_t L;
1140   RHS_t R;
1141 
1142   OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
1143       : L(LHS), R(RHS) {}
1144 
1145   template <typename OpTy> bool match(OpTy *V) {
1146     if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
1147       if (Op->getOpcode() != Opcode)
1148         return false;
1149       if ((WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap) &&
1150           !Op->hasNoUnsignedWrap())
1151         return false;
1152       if ((WrapFlags & OverflowingBinaryOperator::NoSignedWrap) &&
1153           !Op->hasNoSignedWrap())
1154         return false;
1155       return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
1156     }
1157     return false;
1158   }
1159 };
1160 
1161 template <typename LHS, typename RHS>
1162 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1163                                  OverflowingBinaryOperator::NoSignedWrap>
1164 m_NSWAdd(const LHS &L, const RHS &R) {
1165   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1166                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1167                                                                             R);
1168 }
1169 template <typename LHS, typename RHS>
1170 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1171                                  OverflowingBinaryOperator::NoSignedWrap>
1172 m_NSWSub(const LHS &L, const RHS &R) {
1173   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1174                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1175                                                                             R);
1176 }
1177 template <typename LHS, typename RHS>
1178 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1179                                  OverflowingBinaryOperator::NoSignedWrap>
1180 m_NSWMul(const LHS &L, const RHS &R) {
1181   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1182                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1183                                                                             R);
1184 }
1185 template <typename LHS, typename RHS>
1186 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1187                                  OverflowingBinaryOperator::NoSignedWrap>
1188 m_NSWShl(const LHS &L, const RHS &R) {
1189   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1190                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1191                                                                             R);
1192 }
1193 
1194 template <typename LHS, typename RHS>
1195 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1196                                  OverflowingBinaryOperator::NoUnsignedWrap>
1197 m_NUWAdd(const LHS &L, const RHS &R) {
1198   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1199                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1200       L, R);
1201 }
1202 template <typename LHS, typename RHS>
1203 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1204                                  OverflowingBinaryOperator::NoUnsignedWrap>
1205 m_NUWSub(const LHS &L, const RHS &R) {
1206   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1207                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1208       L, R);
1209 }
1210 template <typename LHS, typename RHS>
1211 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1212                                  OverflowingBinaryOperator::NoUnsignedWrap>
1213 m_NUWMul(const LHS &L, const RHS &R) {
1214   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1215                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1216       L, R);
1217 }
1218 template <typename LHS, typename RHS>
1219 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1220                                  OverflowingBinaryOperator::NoUnsignedWrap>
1221 m_NUWShl(const LHS &L, const RHS &R) {
1222   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1223                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1224       L, R);
1225 }
1226 
1227 template <typename LHS_t, typename RHS_t, bool Commutable = false>
1228 struct SpecificBinaryOp_match
1229     : public BinaryOp_match<LHS_t, RHS_t, 0, Commutable> {
1230   unsigned Opcode;
1231 
1232   SpecificBinaryOp_match(unsigned Opcode, const LHS_t &LHS, const RHS_t &RHS)
1233       : BinaryOp_match<LHS_t, RHS_t, 0, Commutable>(LHS, RHS), Opcode(Opcode) {}
1234 
1235   template <typename OpTy> bool match(OpTy *V) {
1236     return BinaryOp_match<LHS_t, RHS_t, 0, Commutable>::match(Opcode, V);
1237   }
1238 };
1239 
1240 /// Matches a specific opcode.
1241 template <typename LHS, typename RHS>
1242 inline SpecificBinaryOp_match<LHS, RHS> m_BinOp(unsigned Opcode, const LHS &L,
1243                                                 const RHS &R) {
1244   return SpecificBinaryOp_match<LHS, RHS>(Opcode, L, R);
1245 }
1246 
1247 //===----------------------------------------------------------------------===//
1248 // Class that matches a group of binary opcodes.
1249 //
1250 template <typename LHS_t, typename RHS_t, typename Predicate>
1251 struct BinOpPred_match : Predicate {
1252   LHS_t L;
1253   RHS_t R;
1254 
1255   BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1256 
1257   template <typename OpTy> bool match(OpTy *V) {
1258     if (auto *I = dyn_cast<Instruction>(V))
1259       return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) &&
1260              R.match(I->getOperand(1));
1261     if (auto *CE = dyn_cast<ConstantExpr>(V))
1262       return this->isOpType(CE->getOpcode()) && L.match(CE->getOperand(0)) &&
1263              R.match(CE->getOperand(1));
1264     return false;
1265   }
1266 };
1267 
1268 struct is_shift_op {
1269   bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); }
1270 };
1271 
1272 struct is_right_shift_op {
1273   bool isOpType(unsigned Opcode) {
1274     return Opcode == Instruction::LShr || Opcode == Instruction::AShr;
1275   }
1276 };
1277 
1278 struct is_logical_shift_op {
1279   bool isOpType(unsigned Opcode) {
1280     return Opcode == Instruction::LShr || Opcode == Instruction::Shl;
1281   }
1282 };
1283 
1284 struct is_bitwiselogic_op {
1285   bool isOpType(unsigned Opcode) {
1286     return Instruction::isBitwiseLogicOp(Opcode);
1287   }
1288 };
1289 
1290 struct is_idiv_op {
1291   bool isOpType(unsigned Opcode) {
1292     return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
1293   }
1294 };
1295 
1296 struct is_irem_op {
1297   bool isOpType(unsigned Opcode) {
1298     return Opcode == Instruction::SRem || Opcode == Instruction::URem;
1299   }
1300 };
1301 
1302 /// Matches shift operations.
1303 template <typename LHS, typename RHS>
1304 inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L,
1305                                                       const RHS &R) {
1306   return BinOpPred_match<LHS, RHS, is_shift_op>(L, R);
1307 }
1308 
1309 /// Matches logical shift operations.
1310 template <typename LHS, typename RHS>
1311 inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L,
1312                                                           const RHS &R) {
1313   return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R);
1314 }
1315 
1316 /// Matches logical shift operations.
1317 template <typename LHS, typename RHS>
1318 inline BinOpPred_match<LHS, RHS, is_logical_shift_op>
1319 m_LogicalShift(const LHS &L, const RHS &R) {
1320   return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R);
1321 }
1322 
1323 /// Matches bitwise logic operations.
1324 template <typename LHS, typename RHS>
1325 inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op>
1326 m_BitwiseLogic(const LHS &L, const RHS &R) {
1327   return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R);
1328 }
1329 
1330 /// Matches integer division operations.
1331 template <typename LHS, typename RHS>
1332 inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L,
1333                                                     const RHS &R) {
1334   return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R);
1335 }
1336 
1337 /// Matches integer remainder operations.
1338 template <typename LHS, typename RHS>
1339 inline BinOpPred_match<LHS, RHS, is_irem_op> m_IRem(const LHS &L,
1340                                                     const RHS &R) {
1341   return BinOpPred_match<LHS, RHS, is_irem_op>(L, R);
1342 }
1343 
1344 //===----------------------------------------------------------------------===//
1345 // Class that matches exact binary ops.
1346 //
1347 template <typename SubPattern_t> struct Exact_match {
1348   SubPattern_t SubPattern;
1349 
1350   Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
1351 
1352   template <typename OpTy> bool match(OpTy *V) {
1353     if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
1354       return PEO->isExact() && SubPattern.match(V);
1355     return false;
1356   }
1357 };
1358 
1359 template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
1360   return SubPattern;
1361 }
1362 
1363 //===----------------------------------------------------------------------===//
1364 // Matchers for CmpInst classes
1365 //
1366 
1367 template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy,
1368           bool Commutable = false>
1369 struct CmpClass_match {
1370   PredicateTy &Predicate;
1371   LHS_t L;
1372   RHS_t R;
1373 
1374   // The evaluation order is always stable, regardless of Commutability.
1375   // The LHS is always matched first.
1376   CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
1377       : Predicate(Pred), L(LHS), R(RHS) {}
1378 
1379   template <typename OpTy> bool match(OpTy *V) {
1380     if (auto *I = dyn_cast<Class>(V)) {
1381       if (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) {
1382         Predicate = I->getPredicate();
1383         return true;
1384       } else if (Commutable && L.match(I->getOperand(1)) &&
1385                  R.match(I->getOperand(0))) {
1386         Predicate = I->getSwappedPredicate();
1387         return true;
1388       }
1389     }
1390     return false;
1391   }
1392 };
1393 
1394 template <typename LHS, typename RHS>
1395 inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
1396 m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1397   return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
1398 }
1399 
1400 template <typename LHS, typename RHS>
1401 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
1402 m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1403   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
1404 }
1405 
1406 template <typename LHS, typename RHS>
1407 inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
1408 m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1409   return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
1410 }
1411 
1412 //===----------------------------------------------------------------------===//
1413 // Matchers for instructions with a given opcode and number of operands.
1414 //
1415 
1416 /// Matches instructions with Opcode and three operands.
1417 template <typename T0, unsigned Opcode> struct OneOps_match {
1418   T0 Op1;
1419 
1420   OneOps_match(const T0 &Op1) : Op1(Op1) {}
1421 
1422   template <typename OpTy> bool match(OpTy *V) {
1423     if (V->getValueID() == Value::InstructionVal + Opcode) {
1424       auto *I = cast<Instruction>(V);
1425       return Op1.match(I->getOperand(0));
1426     }
1427     return false;
1428   }
1429 };
1430 
1431 /// Matches instructions with Opcode and three operands.
1432 template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match {
1433   T0 Op1;
1434   T1 Op2;
1435 
1436   TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {}
1437 
1438   template <typename OpTy> bool match(OpTy *V) {
1439     if (V->getValueID() == Value::InstructionVal + Opcode) {
1440       auto *I = cast<Instruction>(V);
1441       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1));
1442     }
1443     return false;
1444   }
1445 };
1446 
1447 /// Matches instructions with Opcode and three operands.
1448 template <typename T0, typename T1, typename T2, unsigned Opcode>
1449 struct ThreeOps_match {
1450   T0 Op1;
1451   T1 Op2;
1452   T2 Op3;
1453 
1454   ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3)
1455       : Op1(Op1), Op2(Op2), Op3(Op3) {}
1456 
1457   template <typename OpTy> bool match(OpTy *V) {
1458     if (V->getValueID() == Value::InstructionVal + Opcode) {
1459       auto *I = cast<Instruction>(V);
1460       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1461              Op3.match(I->getOperand(2));
1462     }
1463     return false;
1464   }
1465 };
1466 
1467 /// Matches SelectInst.
1468 template <typename Cond, typename LHS, typename RHS>
1469 inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select>
1470 m_Select(const Cond &C, const LHS &L, const RHS &R) {
1471   return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R);
1472 }
1473 
1474 /// This matches a select of two constants, e.g.:
1475 /// m_SelectCst<-1, 0>(m_Value(V))
1476 template <int64_t L, int64_t R, typename Cond>
1477 inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>,
1478                       Instruction::Select>
1479 m_SelectCst(const Cond &C) {
1480   return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
1481 }
1482 
1483 /// Matches FreezeInst.
1484 template <typename OpTy>
1485 inline OneOps_match<OpTy, Instruction::Freeze> m_Freeze(const OpTy &Op) {
1486   return OneOps_match<OpTy, Instruction::Freeze>(Op);
1487 }
1488 
1489 /// Matches InsertElementInst.
1490 template <typename Val_t, typename Elt_t, typename Idx_t>
1491 inline ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>
1492 m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) {
1493   return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>(
1494       Val, Elt, Idx);
1495 }
1496 
1497 /// Matches ExtractElementInst.
1498 template <typename Val_t, typename Idx_t>
1499 inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>
1500 m_ExtractElt(const Val_t &Val, const Idx_t &Idx) {
1501   return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx);
1502 }
1503 
1504 /// Matches shuffle.
1505 template <typename T0, typename T1, typename T2> struct Shuffle_match {
1506   T0 Op1;
1507   T1 Op2;
1508   T2 Mask;
1509 
1510   Shuffle_match(const T0 &Op1, const T1 &Op2, const T2 &Mask)
1511       : Op1(Op1), Op2(Op2), Mask(Mask) {}
1512 
1513   template <typename OpTy> bool match(OpTy *V) {
1514     if (auto *I = dyn_cast<ShuffleVectorInst>(V)) {
1515       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1516              Mask.match(I->getShuffleMask());
1517     }
1518     return false;
1519   }
1520 };
1521 
1522 struct m_Mask {
1523   ArrayRef<int> &MaskRef;
1524   m_Mask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
1525   bool match(ArrayRef<int> Mask) {
1526     MaskRef = Mask;
1527     return true;
1528   }
1529 };
1530 
1531 struct m_ZeroMask {
1532   bool match(ArrayRef<int> Mask) {
1533     return all_of(Mask, [](int Elem) { return Elem == 0 || Elem == -1; });
1534   }
1535 };
1536 
1537 struct m_SpecificMask {
1538   ArrayRef<int> &MaskRef;
1539   m_SpecificMask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
1540   bool match(ArrayRef<int> Mask) { return MaskRef == Mask; }
1541 };
1542 
1543 struct m_SplatOrUndefMask {
1544   int &SplatIndex;
1545   m_SplatOrUndefMask(int &SplatIndex) : SplatIndex(SplatIndex) {}
1546   bool match(ArrayRef<int> Mask) {
1547     const auto *First = find_if(Mask, [](int Elem) { return Elem != -1; });
1548     if (First == Mask.end())
1549       return false;
1550     SplatIndex = *First;
1551     return all_of(Mask,
1552                   [First](int Elem) { return Elem == *First || Elem == -1; });
1553   }
1554 };
1555 
1556 /// Matches ShuffleVectorInst independently of mask value.
1557 template <typename V1_t, typename V2_t>
1558 inline TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>
1559 m_Shuffle(const V1_t &v1, const V2_t &v2) {
1560   return TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>(v1, v2);
1561 }
1562 
1563 template <typename V1_t, typename V2_t, typename Mask_t>
1564 inline Shuffle_match<V1_t, V2_t, Mask_t>
1565 m_Shuffle(const V1_t &v1, const V2_t &v2, const Mask_t &mask) {
1566   return Shuffle_match<V1_t, V2_t, Mask_t>(v1, v2, mask);
1567 }
1568 
1569 /// Matches LoadInst.
1570 template <typename OpTy>
1571 inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) {
1572   return OneOps_match<OpTy, Instruction::Load>(Op);
1573 }
1574 
1575 /// Matches StoreInst.
1576 template <typename ValueOpTy, typename PointerOpTy>
1577 inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>
1578 m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) {
1579   return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp,
1580                                                                   PointerOp);
1581 }
1582 
1583 //===----------------------------------------------------------------------===//
1584 // Matchers for CastInst classes
1585 //
1586 
1587 template <typename Op_t, unsigned Opcode> struct CastClass_match {
1588   Op_t Op;
1589 
1590   CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {}
1591 
1592   template <typename OpTy> bool match(OpTy *V) {
1593     if (auto *O = dyn_cast<Operator>(V))
1594       return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
1595     return false;
1596   }
1597 };
1598 
1599 template <typename Op_t> struct PtrToIntSameSize_match {
1600   const DataLayout &DL;
1601   Op_t Op;
1602 
1603   PtrToIntSameSize_match(const DataLayout &DL, const Op_t &OpMatch)
1604       : DL(DL), Op(OpMatch) {}
1605 
1606   template <typename OpTy> bool match(OpTy *V) {
1607     if (auto *O = dyn_cast<Operator>(V))
1608       return O->getOpcode() == Instruction::PtrToInt &&
1609              DL.getTypeSizeInBits(O->getType()) ==
1610                  DL.getTypeSizeInBits(O->getOperand(0)->getType()) &&
1611              Op.match(O->getOperand(0));
1612     return false;
1613   }
1614 };
1615 
1616 /// Matches BitCast.
1617 template <typename OpTy>
1618 inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) {
1619   return CastClass_match<OpTy, Instruction::BitCast>(Op);
1620 }
1621 
1622 /// Matches PtrToInt.
1623 template <typename OpTy>
1624 inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) {
1625   return CastClass_match<OpTy, Instruction::PtrToInt>(Op);
1626 }
1627 
1628 template <typename OpTy>
1629 inline PtrToIntSameSize_match<OpTy> m_PtrToIntSameSize(const DataLayout &DL,
1630                                                        const OpTy &Op) {
1631   return PtrToIntSameSize_match<OpTy>(DL, Op);
1632 }
1633 
1634 /// Matches IntToPtr.
1635 template <typename OpTy>
1636 inline CastClass_match<OpTy, Instruction::IntToPtr> m_IntToPtr(const OpTy &Op) {
1637   return CastClass_match<OpTy, Instruction::IntToPtr>(Op);
1638 }
1639 
1640 /// Matches Trunc.
1641 template <typename OpTy>
1642 inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) {
1643   return CastClass_match<OpTy, Instruction::Trunc>(Op);
1644 }
1645 
1646 template <typename OpTy>
1647 inline match_combine_or<CastClass_match<OpTy, Instruction::Trunc>, OpTy>
1648 m_TruncOrSelf(const OpTy &Op) {
1649   return m_CombineOr(m_Trunc(Op), Op);
1650 }
1651 
1652 /// Matches SExt.
1653 template <typename OpTy>
1654 inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) {
1655   return CastClass_match<OpTy, Instruction::SExt>(Op);
1656 }
1657 
1658 /// Matches ZExt.
1659 template <typename OpTy>
1660 inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) {
1661   return CastClass_match<OpTy, Instruction::ZExt>(Op);
1662 }
1663 
1664 template <typename OpTy>
1665 inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>, OpTy>
1666 m_ZExtOrSelf(const OpTy &Op) {
1667   return m_CombineOr(m_ZExt(Op), Op);
1668 }
1669 
1670 template <typename OpTy>
1671 inline match_combine_or<CastClass_match<OpTy, Instruction::SExt>, OpTy>
1672 m_SExtOrSelf(const OpTy &Op) {
1673   return m_CombineOr(m_SExt(Op), Op);
1674 }
1675 
1676 template <typename OpTy>
1677 inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1678                         CastClass_match<OpTy, Instruction::SExt>>
1679 m_ZExtOrSExt(const OpTy &Op) {
1680   return m_CombineOr(m_ZExt(Op), m_SExt(Op));
1681 }
1682 
1683 template <typename OpTy>
1684 inline match_combine_or<
1685     match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1686                      CastClass_match<OpTy, Instruction::SExt>>,
1687     OpTy>
1688 m_ZExtOrSExtOrSelf(const OpTy &Op) {
1689   return m_CombineOr(m_ZExtOrSExt(Op), Op);
1690 }
1691 
1692 template <typename OpTy>
1693 inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) {
1694   return CastClass_match<OpTy, Instruction::UIToFP>(Op);
1695 }
1696 
1697 template <typename OpTy>
1698 inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) {
1699   return CastClass_match<OpTy, Instruction::SIToFP>(Op);
1700 }
1701 
1702 template <typename OpTy>
1703 inline CastClass_match<OpTy, Instruction::FPToUI> m_FPToUI(const OpTy &Op) {
1704   return CastClass_match<OpTy, Instruction::FPToUI>(Op);
1705 }
1706 
1707 template <typename OpTy>
1708 inline CastClass_match<OpTy, Instruction::FPToSI> m_FPToSI(const OpTy &Op) {
1709   return CastClass_match<OpTy, Instruction::FPToSI>(Op);
1710 }
1711 
1712 template <typename OpTy>
1713 inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) {
1714   return CastClass_match<OpTy, Instruction::FPTrunc>(Op);
1715 }
1716 
1717 template <typename OpTy>
1718 inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) {
1719   return CastClass_match<OpTy, Instruction::FPExt>(Op);
1720 }
1721 
1722 //===----------------------------------------------------------------------===//
1723 // Matchers for control flow.
1724 //
1725 
1726 struct br_match {
1727   BasicBlock *&Succ;
1728 
1729   br_match(BasicBlock *&Succ) : Succ(Succ) {}
1730 
1731   template <typename OpTy> bool match(OpTy *V) {
1732     if (auto *BI = dyn_cast<BranchInst>(V))
1733       if (BI->isUnconditional()) {
1734         Succ = BI->getSuccessor(0);
1735         return true;
1736       }
1737     return false;
1738   }
1739 };
1740 
1741 inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
1742 
1743 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1744 struct brc_match {
1745   Cond_t Cond;
1746   TrueBlock_t T;
1747   FalseBlock_t F;
1748 
1749   brc_match(const Cond_t &C, const TrueBlock_t &t, const FalseBlock_t &f)
1750       : Cond(C), T(t), F(f) {}
1751 
1752   template <typename OpTy> bool match(OpTy *V) {
1753     if (auto *BI = dyn_cast<BranchInst>(V))
1754       if (BI->isConditional() && Cond.match(BI->getCondition()))
1755         return T.match(BI->getSuccessor(0)) && F.match(BI->getSuccessor(1));
1756     return false;
1757   }
1758 };
1759 
1760 template <typename Cond_t>
1761 inline brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>
1762 m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
1763   return brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>(
1764       C, m_BasicBlock(T), m_BasicBlock(F));
1765 }
1766 
1767 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1768 inline brc_match<Cond_t, TrueBlock_t, FalseBlock_t>
1769 m_Br(const Cond_t &C, const TrueBlock_t &T, const FalseBlock_t &F) {
1770   return brc_match<Cond_t, TrueBlock_t, FalseBlock_t>(C, T, F);
1771 }
1772 
1773 //===----------------------------------------------------------------------===//
1774 // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
1775 //
1776 
1777 template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t,
1778           bool Commutable = false>
1779 struct MaxMin_match {
1780   using PredType = Pred_t;
1781   LHS_t L;
1782   RHS_t R;
1783 
1784   // The evaluation order is always stable, regardless of Commutability.
1785   // The LHS is always matched first.
1786   MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1787 
1788   template <typename OpTy> bool match(OpTy *V) {
1789     if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1790       Intrinsic::ID IID = II->getIntrinsicID();
1791       if ((IID == Intrinsic::smax && Pred_t::match(ICmpInst::ICMP_SGT)) ||
1792           (IID == Intrinsic::smin && Pred_t::match(ICmpInst::ICMP_SLT)) ||
1793           (IID == Intrinsic::umax && Pred_t::match(ICmpInst::ICMP_UGT)) ||
1794           (IID == Intrinsic::umin && Pred_t::match(ICmpInst::ICMP_ULT))) {
1795         Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
1796         return (L.match(LHS) && R.match(RHS)) ||
1797                (Commutable && L.match(RHS) && R.match(LHS));
1798       }
1799     }
1800     // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1801     auto *SI = dyn_cast<SelectInst>(V);
1802     if (!SI)
1803       return false;
1804     auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1805     if (!Cmp)
1806       return false;
1807     // At this point we have a select conditioned on a comparison.  Check that
1808     // it is the values returned by the select that are being compared.
1809     auto *TrueVal = SI->getTrueValue();
1810     auto *FalseVal = SI->getFalseValue();
1811     auto *LHS = Cmp->getOperand(0);
1812     auto *RHS = Cmp->getOperand(1);
1813     if ((TrueVal != LHS || FalseVal != RHS) &&
1814         (TrueVal != RHS || FalseVal != LHS))
1815       return false;
1816     typename CmpInst_t::Predicate Pred =
1817         LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate();
1818     // Does "(x pred y) ? x : y" represent the desired max/min operation?
1819     if (!Pred_t::match(Pred))
1820       return false;
1821     // It does!  Bind the operands.
1822     return (L.match(LHS) && R.match(RHS)) ||
1823            (Commutable && L.match(RHS) && R.match(LHS));
1824   }
1825 };
1826 
1827 /// Helper class for identifying signed max predicates.
1828 struct smax_pred_ty {
1829   static bool match(ICmpInst::Predicate Pred) {
1830     return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
1831   }
1832 };
1833 
1834 /// Helper class for identifying signed min predicates.
1835 struct smin_pred_ty {
1836   static bool match(ICmpInst::Predicate Pred) {
1837     return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
1838   }
1839 };
1840 
1841 /// Helper class for identifying unsigned max predicates.
1842 struct umax_pred_ty {
1843   static bool match(ICmpInst::Predicate Pred) {
1844     return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
1845   }
1846 };
1847 
1848 /// Helper class for identifying unsigned min predicates.
1849 struct umin_pred_ty {
1850   static bool match(ICmpInst::Predicate Pred) {
1851     return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
1852   }
1853 };
1854 
1855 /// Helper class for identifying ordered max predicates.
1856 struct ofmax_pred_ty {
1857   static bool match(FCmpInst::Predicate Pred) {
1858     return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
1859   }
1860 };
1861 
1862 /// Helper class for identifying ordered min predicates.
1863 struct ofmin_pred_ty {
1864   static bool match(FCmpInst::Predicate Pred) {
1865     return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
1866   }
1867 };
1868 
1869 /// Helper class for identifying unordered max predicates.
1870 struct ufmax_pred_ty {
1871   static bool match(FCmpInst::Predicate Pred) {
1872     return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
1873   }
1874 };
1875 
1876 /// Helper class for identifying unordered min predicates.
1877 struct ufmin_pred_ty {
1878   static bool match(FCmpInst::Predicate Pred) {
1879     return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
1880   }
1881 };
1882 
1883 template <typename LHS, typename RHS>
1884 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
1885                                                              const RHS &R) {
1886   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
1887 }
1888 
1889 template <typename LHS, typename RHS>
1890 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
1891                                                              const RHS &R) {
1892   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
1893 }
1894 
1895 template <typename LHS, typename RHS>
1896 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
1897                                                              const RHS &R) {
1898   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
1899 }
1900 
1901 template <typename LHS, typename RHS>
1902 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
1903                                                              const RHS &R) {
1904   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
1905 }
1906 
1907 template <typename LHS, typename RHS>
1908 inline match_combine_or<
1909     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>,
1910                      MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>>,
1911     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>,
1912                      MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>>>
1913 m_MaxOrMin(const LHS &L, const RHS &R) {
1914   return m_CombineOr(m_CombineOr(m_SMax(L, R), m_SMin(L, R)),
1915                      m_CombineOr(m_UMax(L, R), m_UMin(L, R)));
1916 }
1917 
1918 /// Match an 'ordered' floating point maximum function.
1919 /// Floating point has one special value 'NaN'. Therefore, there is no total
1920 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1921 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1922 /// semantics. In the presence of 'NaN' we have to preserve the original
1923 /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
1924 ///
1925 ///                         max(L, R)  iff L and R are not NaN
1926 ///  m_OrdFMax(L, R) =      R          iff L or R are NaN
1927 template <typename LHS, typename RHS>
1928 inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
1929                                                                  const RHS &R) {
1930   return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
1931 }
1932 
1933 /// Match an 'ordered' floating point minimum function.
1934 /// Floating point has one special value 'NaN'. Therefore, there is no total
1935 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1936 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1937 /// semantics. In the presence of 'NaN' we have to preserve the original
1938 /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
1939 ///
1940 ///                         min(L, R)  iff L and R are not NaN
1941 ///  m_OrdFMin(L, R) =      R          iff L or R are NaN
1942 template <typename LHS, typename RHS>
1943 inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
1944                                                                  const RHS &R) {
1945   return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
1946 }
1947 
1948 /// Match an 'unordered' floating point maximum function.
1949 /// Floating point has one special value 'NaN'. Therefore, there is no total
1950 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1951 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1952 /// semantics. In the presence of 'NaN' we have to preserve the original
1953 /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
1954 ///
1955 ///                         max(L, R)  iff L and R are not NaN
1956 ///  m_UnordFMax(L, R) =    L          iff L or R are NaN
1957 template <typename LHS, typename RHS>
1958 inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
1959 m_UnordFMax(const LHS &L, const RHS &R) {
1960   return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
1961 }
1962 
1963 /// Match an 'unordered' floating point minimum function.
1964 /// Floating point has one special value 'NaN'. Therefore, there is no total
1965 /// order. However, if we can ignore the 'NaN' value (for example, because of a
1966 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1967 /// semantics. In the presence of 'NaN' we have to preserve the original
1968 /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
1969 ///
1970 ///                          min(L, R)  iff L and R are not NaN
1971 ///  m_UnordFMin(L, R) =     L          iff L or R are NaN
1972 template <typename LHS, typename RHS>
1973 inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
1974 m_UnordFMin(const LHS &L, const RHS &R) {
1975   return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
1976 }
1977 
1978 //===----------------------------------------------------------------------===//
1979 // Matchers for overflow check patterns: e.g. (a + b) u< a, (a ^ -1) <u b
1980 // Note that S might be matched to other instructions than AddInst.
1981 //
1982 
1983 template <typename LHS_t, typename RHS_t, typename Sum_t>
1984 struct UAddWithOverflow_match {
1985   LHS_t L;
1986   RHS_t R;
1987   Sum_t S;
1988 
1989   UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
1990       : L(L), R(R), S(S) {}
1991 
1992   template <typename OpTy> bool match(OpTy *V) {
1993     Value *ICmpLHS, *ICmpRHS;
1994     ICmpInst::Predicate Pred;
1995     if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
1996       return false;
1997 
1998     Value *AddLHS, *AddRHS;
1999     auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
2000 
2001     // (a + b) u< a, (a + b) u< b
2002     if (Pred == ICmpInst::ICMP_ULT)
2003       if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
2004         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
2005 
2006     // a >u (a + b), b >u (a + b)
2007     if (Pred == ICmpInst::ICMP_UGT)
2008       if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
2009         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
2010 
2011     Value *Op1;
2012     auto XorExpr = m_OneUse(m_Xor(m_Value(Op1), m_AllOnes()));
2013     // (a ^ -1) <u b
2014     if (Pred == ICmpInst::ICMP_ULT) {
2015       if (XorExpr.match(ICmpLHS))
2016         return L.match(Op1) && R.match(ICmpRHS) && S.match(ICmpLHS);
2017     }
2018     //  b > u (a ^ -1)
2019     if (Pred == ICmpInst::ICMP_UGT) {
2020       if (XorExpr.match(ICmpRHS))
2021         return L.match(Op1) && R.match(ICmpLHS) && S.match(ICmpRHS);
2022     }
2023 
2024     // Match special-case for increment-by-1.
2025     if (Pred == ICmpInst::ICMP_EQ) {
2026       // (a + 1) == 0
2027       // (1 + a) == 0
2028       if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) &&
2029           (m_One().match(AddLHS) || m_One().match(AddRHS)))
2030         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
2031       // 0 == (a + 1)
2032       // 0 == (1 + a)
2033       if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) &&
2034           (m_One().match(AddLHS) || m_One().match(AddRHS)))
2035         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
2036     }
2037 
2038     return false;
2039   }
2040 };
2041 
2042 /// Match an icmp instruction checking for unsigned overflow on addition.
2043 ///
2044 /// S is matched to the addition whose result is being checked for overflow, and
2045 /// L and R are matched to the LHS and RHS of S.
2046 template <typename LHS_t, typename RHS_t, typename Sum_t>
2047 UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
2048 m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
2049   return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
2050 }
2051 
2052 template <typename Opnd_t> struct Argument_match {
2053   unsigned OpI;
2054   Opnd_t Val;
2055 
2056   Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
2057 
2058   template <typename OpTy> bool match(OpTy *V) {
2059     // FIXME: Should likely be switched to use `CallBase`.
2060     if (const auto *CI = dyn_cast<CallInst>(V))
2061       return Val.match(CI->getArgOperand(OpI));
2062     return false;
2063   }
2064 };
2065 
2066 /// Match an argument.
2067 template <unsigned OpI, typename Opnd_t>
2068 inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
2069   return Argument_match<Opnd_t>(OpI, Op);
2070 }
2071 
2072 /// Intrinsic matchers.
2073 struct IntrinsicID_match {
2074   unsigned ID;
2075 
2076   IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
2077 
2078   template <typename OpTy> bool match(OpTy *V) {
2079     if (const auto *CI = dyn_cast<CallInst>(V))
2080       if (const auto *F = CI->getCalledFunction())
2081         return F->getIntrinsicID() == ID;
2082     return false;
2083   }
2084 };
2085 
2086 /// Intrinsic matches are combinations of ID matchers, and argument
2087 /// matchers. Higher arity matcher are defined recursively in terms of and-ing
2088 /// them with lower arity matchers. Here's some convenient typedefs for up to
2089 /// several arguments, and more can be added as needed
2090 template <typename T0 = void, typename T1 = void, typename T2 = void,
2091           typename T3 = void, typename T4 = void, typename T5 = void,
2092           typename T6 = void, typename T7 = void, typename T8 = void,
2093           typename T9 = void, typename T10 = void>
2094 struct m_Intrinsic_Ty;
2095 template <typename T0> struct m_Intrinsic_Ty<T0> {
2096   using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
2097 };
2098 template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
2099   using Ty =
2100       match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
2101 };
2102 template <typename T0, typename T1, typename T2>
2103 struct m_Intrinsic_Ty<T0, T1, T2> {
2104   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
2105                                Argument_match<T2>>;
2106 };
2107 template <typename T0, typename T1, typename T2, typename T3>
2108 struct m_Intrinsic_Ty<T0, T1, T2, T3> {
2109   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
2110                                Argument_match<T3>>;
2111 };
2112 
2113 template <typename T0, typename T1, typename T2, typename T3, typename T4>
2114 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4> {
2115   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty,
2116                                Argument_match<T4>>;
2117 };
2118 
2119 template <typename T0, typename T1, typename T2, typename T3, typename T4,
2120           typename T5>
2121 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5> {
2122   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty,
2123                                Argument_match<T5>>;
2124 };
2125 
2126 /// Match intrinsic calls like this:
2127 /// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
2128 template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
2129   return IntrinsicID_match(IntrID);
2130 }
2131 
2132 /// Matches MaskedLoad Intrinsic.
2133 template <typename Opnd0, typename Opnd1, typename Opnd2, typename Opnd3>
2134 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2, Opnd3>::Ty
2135 m_MaskedLoad(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2,
2136              const Opnd3 &Op3) {
2137   return m_Intrinsic<Intrinsic::masked_load>(Op0, Op1, Op2, Op3);
2138 }
2139 
2140 /// Matches MaskedGather Intrinsic.
2141 template <typename Opnd0, typename Opnd1, typename Opnd2, typename Opnd3>
2142 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2, Opnd3>::Ty
2143 m_MaskedGather(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2,
2144                const Opnd3 &Op3) {
2145   return m_Intrinsic<Intrinsic::masked_gather>(Op0, Op1, Op2, Op3);
2146 }
2147 
2148 template <Intrinsic::ID IntrID, typename T0>
2149 inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
2150   return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
2151 }
2152 
2153 template <Intrinsic::ID IntrID, typename T0, typename T1>
2154 inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
2155                                                        const T1 &Op1) {
2156   return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
2157 }
2158 
2159 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
2160 inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
2161 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
2162   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
2163 }
2164 
2165 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2166           typename T3>
2167 inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
2168 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
2169   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
2170 }
2171 
2172 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2173           typename T3, typename T4>
2174 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty
2175 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2176             const T4 &Op4) {
2177   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3),
2178                       m_Argument<4>(Op4));
2179 }
2180 
2181 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2182           typename T3, typename T4, typename T5>
2183 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5>::Ty
2184 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2185             const T4 &Op4, const T5 &Op5) {
2186   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3, Op4),
2187                       m_Argument<5>(Op5));
2188 }
2189 
2190 // Helper intrinsic matching specializations.
2191 template <typename Opnd0>
2192 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) {
2193   return m_Intrinsic<Intrinsic::bitreverse>(Op0);
2194 }
2195 
2196 template <typename Opnd0>
2197 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
2198   return m_Intrinsic<Intrinsic::bswap>(Op0);
2199 }
2200 
2201 template <typename Opnd0>
2202 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) {
2203   return m_Intrinsic<Intrinsic::fabs>(Op0);
2204 }
2205 
2206 template <typename Opnd0>
2207 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) {
2208   return m_Intrinsic<Intrinsic::canonicalize>(Op0);
2209 }
2210 
2211 template <typename Opnd0, typename Opnd1>
2212 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
2213                                                         const Opnd1 &Op1) {
2214   return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
2215 }
2216 
2217 template <typename Opnd0, typename Opnd1>
2218 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
2219                                                         const Opnd1 &Op1) {
2220   return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
2221 }
2222 
2223 template <typename Opnd0, typename Opnd1, typename Opnd2>
2224 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2225 m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2226   return m_Intrinsic<Intrinsic::fshl>(Op0, Op1, Op2);
2227 }
2228 
2229 template <typename Opnd0, typename Opnd1, typename Opnd2>
2230 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2231 m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2232   return m_Intrinsic<Intrinsic::fshr>(Op0, Op1, Op2);
2233 }
2234 
2235 template <typename Opnd0>
2236 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_Sqrt(const Opnd0 &Op0) {
2237   return m_Intrinsic<Intrinsic::sqrt>(Op0);
2238 }
2239 
2240 template <typename Opnd0, typename Opnd1>
2241 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_CopySign(const Opnd0 &Op0,
2242                                                             const Opnd1 &Op1) {
2243   return m_Intrinsic<Intrinsic::copysign>(Op0, Op1);
2244 }
2245 
2246 template <typename Opnd0>
2247 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_VecReverse(const Opnd0 &Op0) {
2248   return m_Intrinsic<Intrinsic::experimental_vector_reverse>(Op0);
2249 }
2250 
2251 //===----------------------------------------------------------------------===//
2252 // Matchers for two-operands operators with the operators in either order
2253 //
2254 
2255 /// Matches a BinaryOperator with LHS and RHS in either order.
2256 template <typename LHS, typename RHS>
2257 inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) {
2258   return AnyBinaryOp_match<LHS, RHS, true>(L, R);
2259 }
2260 
2261 /// Matches an ICmp with a predicate over LHS and RHS in either order.
2262 /// Swaps the predicate if operands are commuted.
2263 template <typename LHS, typename RHS>
2264 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
2265 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
2266   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L,
2267                                                                        R);
2268 }
2269 
2270 /// Matches a specific opcode with LHS and RHS in either order.
2271 template <typename LHS, typename RHS>
2272 inline SpecificBinaryOp_match<LHS, RHS, true>
2273 m_c_BinOp(unsigned Opcode, const LHS &L, const RHS &R) {
2274   return SpecificBinaryOp_match<LHS, RHS, true>(Opcode, L, R);
2275 }
2276 
2277 /// Matches a Add with LHS and RHS in either order.
2278 template <typename LHS, typename RHS>
2279 inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L,
2280                                                                 const RHS &R) {
2281   return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R);
2282 }
2283 
2284 /// Matches a Mul with LHS and RHS in either order.
2285 template <typename LHS, typename RHS>
2286 inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L,
2287                                                                 const RHS &R) {
2288   return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R);
2289 }
2290 
2291 /// Matches an And with LHS and RHS in either order.
2292 template <typename LHS, typename RHS>
2293 inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L,
2294                                                                 const RHS &R) {
2295   return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R);
2296 }
2297 
2298 /// Matches an Or with LHS and RHS in either order.
2299 template <typename LHS, typename RHS>
2300 inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L,
2301                                                               const RHS &R) {
2302   return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R);
2303 }
2304 
2305 /// Matches an Xor with LHS and RHS in either order.
2306 template <typename LHS, typename RHS>
2307 inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L,
2308                                                                 const RHS &R) {
2309   return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R);
2310 }
2311 
2312 /// Matches a 'Neg' as 'sub 0, V'.
2313 template <typename ValTy>
2314 inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub>
2315 m_Neg(const ValTy &V) {
2316   return m_Sub(m_ZeroInt(), V);
2317 }
2318 
2319 /// Matches a 'Neg' as 'sub nsw 0, V'.
2320 template <typename ValTy>
2321 inline OverflowingBinaryOp_match<cst_pred_ty<is_zero_int>, ValTy,
2322                                  Instruction::Sub,
2323                                  OverflowingBinaryOperator::NoSignedWrap>
2324 m_NSWNeg(const ValTy &V) {
2325   return m_NSWSub(m_ZeroInt(), V);
2326 }
2327 
2328 /// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
2329 /// NOTE: we first match the 'Not' (by matching '-1'),
2330 /// and only then match the inner matcher!
2331 template <typename ValTy>
2332 inline BinaryOp_match<cst_pred_ty<is_all_ones>, ValTy, Instruction::Xor, true>
2333 m_Not(const ValTy &V) {
2334   return m_c_Xor(m_AllOnes(), V);
2335 }
2336 
2337 template <typename ValTy> struct NotForbidUndef_match {
2338   ValTy Val;
2339   NotForbidUndef_match(const ValTy &V) : Val(V) {}
2340 
2341   template <typename OpTy> bool match(OpTy *V) {
2342     // We do not use m_c_Xor because that could match an arbitrary APInt that is
2343     // not -1 as C and then fail to match the other operand if it is -1.
2344     // This code should still work even when both operands are constants.
2345     Value *X;
2346     const APInt *C;
2347     if (m_Xor(m_Value(X), m_APIntForbidUndef(C)).match(V) && C->isAllOnes())
2348       return Val.match(X);
2349     if (m_Xor(m_APIntForbidUndef(C), m_Value(X)).match(V) && C->isAllOnes())
2350       return Val.match(X);
2351     return false;
2352   }
2353 };
2354 
2355 /// Matches a bitwise 'not' as 'xor V, -1' or 'xor -1, V'. For vectors, the
2356 /// constant value must be composed of only -1 scalar elements.
2357 template <typename ValTy>
2358 inline NotForbidUndef_match<ValTy> m_NotForbidUndef(const ValTy &V) {
2359   return NotForbidUndef_match<ValTy>(V);
2360 }
2361 
2362 /// Matches an SMin with LHS and RHS in either order.
2363 template <typename LHS, typename RHS>
2364 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>
2365 m_c_SMin(const LHS &L, const RHS &R) {
2366   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R);
2367 }
2368 /// Matches an SMax with LHS and RHS in either order.
2369 template <typename LHS, typename RHS>
2370 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>
2371 m_c_SMax(const LHS &L, const RHS &R) {
2372   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R);
2373 }
2374 /// Matches a UMin with LHS and RHS in either order.
2375 template <typename LHS, typename RHS>
2376 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>
2377 m_c_UMin(const LHS &L, const RHS &R) {
2378   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R);
2379 }
2380 /// Matches a UMax with LHS and RHS in either order.
2381 template <typename LHS, typename RHS>
2382 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>
2383 m_c_UMax(const LHS &L, const RHS &R) {
2384   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R);
2385 }
2386 
2387 template <typename LHS, typename RHS>
2388 inline match_combine_or<
2389     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>,
2390                      MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>>,
2391     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>,
2392                      MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>>>
2393 m_c_MaxOrMin(const LHS &L, const RHS &R) {
2394   return m_CombineOr(m_CombineOr(m_c_SMax(L, R), m_c_SMin(L, R)),
2395                      m_CombineOr(m_c_UMax(L, R), m_c_UMin(L, R)));
2396 }
2397 
2398 template <Intrinsic::ID IntrID, typename T0, typename T1>
2399 inline match_combine_or<typename m_Intrinsic_Ty<T0, T1>::Ty,
2400                         typename m_Intrinsic_Ty<T1, T0>::Ty>
2401 m_c_Intrinsic(const T0 &Op0, const T1 &Op1) {
2402   return m_CombineOr(m_Intrinsic<IntrID>(Op0, Op1),
2403                      m_Intrinsic<IntrID>(Op1, Op0));
2404 }
2405 
2406 /// Matches FAdd with LHS and RHS in either order.
2407 template <typename LHS, typename RHS>
2408 inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true>
2409 m_c_FAdd(const LHS &L, const RHS &R) {
2410   return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R);
2411 }
2412 
2413 /// Matches FMul with LHS and RHS in either order.
2414 template <typename LHS, typename RHS>
2415 inline BinaryOp_match<LHS, RHS, Instruction::FMul, true>
2416 m_c_FMul(const LHS &L, const RHS &R) {
2417   return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R);
2418 }
2419 
2420 template <typename Opnd_t> struct Signum_match {
2421   Opnd_t Val;
2422   Signum_match(const Opnd_t &V) : Val(V) {}
2423 
2424   template <typename OpTy> bool match(OpTy *V) {
2425     unsigned TypeSize = V->getType()->getScalarSizeInBits();
2426     if (TypeSize == 0)
2427       return false;
2428 
2429     unsigned ShiftWidth = TypeSize - 1;
2430     Value *OpL = nullptr, *OpR = nullptr;
2431 
2432     // This is the representation of signum we match:
2433     //
2434     //  signum(x) == (x >> 63) | (-x >>u 63)
2435     //
2436     // An i1 value is its own signum, so it's correct to match
2437     //
2438     //  signum(x) == (x >> 0)  | (-x >>u 0)
2439     //
2440     // for i1 values.
2441 
2442     auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
2443     auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
2444     auto Signum = m_Or(LHS, RHS);
2445 
2446     return Signum.match(V) && OpL == OpR && Val.match(OpL);
2447   }
2448 };
2449 
2450 /// Matches a signum pattern.
2451 ///
2452 /// signum(x) =
2453 ///      x >  0  ->  1
2454 ///      x == 0  ->  0
2455 ///      x <  0  -> -1
2456 template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
2457   return Signum_match<Val_t>(V);
2458 }
2459 
2460 template <int Ind, typename Opnd_t> struct ExtractValue_match {
2461   Opnd_t Val;
2462   ExtractValue_match(const Opnd_t &V) : Val(V) {}
2463 
2464   template <typename OpTy> bool match(OpTy *V) {
2465     if (auto *I = dyn_cast<ExtractValueInst>(V)) {
2466       // If Ind is -1, don't inspect indices
2467       if (Ind != -1 &&
2468           !(I->getNumIndices() == 1 && I->getIndices()[0] == (unsigned)Ind))
2469         return false;
2470       return Val.match(I->getAggregateOperand());
2471     }
2472     return false;
2473   }
2474 };
2475 
2476 /// Match a single index ExtractValue instruction.
2477 /// For example m_ExtractValue<1>(...)
2478 template <int Ind, typename Val_t>
2479 inline ExtractValue_match<Ind, Val_t> m_ExtractValue(const Val_t &V) {
2480   return ExtractValue_match<Ind, Val_t>(V);
2481 }
2482 
2483 /// Match an ExtractValue instruction with any index.
2484 /// For example m_ExtractValue(...)
2485 template <typename Val_t>
2486 inline ExtractValue_match<-1, Val_t> m_ExtractValue(const Val_t &V) {
2487   return ExtractValue_match<-1, Val_t>(V);
2488 }
2489 
2490 /// Matcher for a single index InsertValue instruction.
2491 template <int Ind, typename T0, typename T1> struct InsertValue_match {
2492   T0 Op0;
2493   T1 Op1;
2494 
2495   InsertValue_match(const T0 &Op0, const T1 &Op1) : Op0(Op0), Op1(Op1) {}
2496 
2497   template <typename OpTy> bool match(OpTy *V) {
2498     if (auto *I = dyn_cast<InsertValueInst>(V)) {
2499       return Op0.match(I->getOperand(0)) && Op1.match(I->getOperand(1)) &&
2500              I->getNumIndices() == 1 && Ind == I->getIndices()[0];
2501     }
2502     return false;
2503   }
2504 };
2505 
2506 /// Matches a single index InsertValue instruction.
2507 template <int Ind, typename Val_t, typename Elt_t>
2508 inline InsertValue_match<Ind, Val_t, Elt_t> m_InsertValue(const Val_t &Val,
2509                                                           const Elt_t &Elt) {
2510   return InsertValue_match<Ind, Val_t, Elt_t>(Val, Elt);
2511 }
2512 
2513 /// Matches patterns for `vscale`. This can either be a call to `llvm.vscale` or
2514 /// the constant expression
2515 ///  `ptrtoint(gep <vscale x 1 x i8>, <vscale x 1 x i8>* null, i32 1>`
2516 /// under the right conditions determined by DataLayout.
2517 struct VScaleVal_match {
2518   template <typename ITy> bool match(ITy *V) {
2519     if (m_Intrinsic<Intrinsic::vscale>().match(V))
2520       return true;
2521 
2522     Value *Ptr;
2523     if (m_PtrToInt(m_Value(Ptr)).match(V)) {
2524       if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
2525         auto *DerefTy =
2526             dyn_cast<ScalableVectorType>(GEP->getSourceElementType());
2527         if (GEP->getNumIndices() == 1 && DerefTy &&
2528             DerefTy->getElementType()->isIntegerTy(8) &&
2529             m_Zero().match(GEP->getPointerOperand()) &&
2530             m_SpecificInt(1).match(GEP->idx_begin()->get()))
2531           return true;
2532       }
2533     }
2534 
2535     return false;
2536   }
2537 };
2538 
2539 inline VScaleVal_match m_VScale() {
2540   return VScaleVal_match();
2541 }
2542 
2543 template <typename LHS, typename RHS, unsigned Opcode, bool Commutable = false>
2544 struct LogicalOp_match {
2545   LHS L;
2546   RHS R;
2547 
2548   LogicalOp_match(const LHS &L, const RHS &R) : L(L), R(R) {}
2549 
2550   template <typename T> bool match(T *V) {
2551     auto *I = dyn_cast<Instruction>(V);
2552     if (!I || !I->getType()->isIntOrIntVectorTy(1))
2553       return false;
2554 
2555     if (I->getOpcode() == Opcode) {
2556       auto *Op0 = I->getOperand(0);
2557       auto *Op1 = I->getOperand(1);
2558       return (L.match(Op0) && R.match(Op1)) ||
2559              (Commutable && L.match(Op1) && R.match(Op0));
2560     }
2561 
2562     if (auto *Select = dyn_cast<SelectInst>(I)) {
2563       auto *Cond = Select->getCondition();
2564       auto *TVal = Select->getTrueValue();
2565       auto *FVal = Select->getFalseValue();
2566 
2567       // Don't match a scalar select of bool vectors.
2568       // Transforms expect a single type for operands if this matches.
2569       if (Cond->getType() != Select->getType())
2570         return false;
2571 
2572       if (Opcode == Instruction::And) {
2573         auto *C = dyn_cast<Constant>(FVal);
2574         if (C && C->isNullValue())
2575           return (L.match(Cond) && R.match(TVal)) ||
2576                  (Commutable && L.match(TVal) && R.match(Cond));
2577       } else {
2578         assert(Opcode == Instruction::Or);
2579         auto *C = dyn_cast<Constant>(TVal);
2580         if (C && C->isOneValue())
2581           return (L.match(Cond) && R.match(FVal)) ||
2582                  (Commutable && L.match(FVal) && R.match(Cond));
2583       }
2584     }
2585 
2586     return false;
2587   }
2588 };
2589 
2590 /// Matches L && R either in the form of L & R or L ? R : false.
2591 /// Note that the latter form is poison-blocking.
2592 template <typename LHS, typename RHS>
2593 inline LogicalOp_match<LHS, RHS, Instruction::And> m_LogicalAnd(const LHS &L,
2594                                                                 const RHS &R) {
2595   return LogicalOp_match<LHS, RHS, Instruction::And>(L, R);
2596 }
2597 
2598 /// Matches L && R where L and R are arbitrary values.
2599 inline auto m_LogicalAnd() { return m_LogicalAnd(m_Value(), m_Value()); }
2600 
2601 /// Matches L && R with LHS and RHS in either order.
2602 template <typename LHS, typename RHS>
2603 inline LogicalOp_match<LHS, RHS, Instruction::And, true>
2604 m_c_LogicalAnd(const LHS &L, const RHS &R) {
2605   return LogicalOp_match<LHS, RHS, Instruction::And, true>(L, R);
2606 }
2607 
2608 /// Matches L || R either in the form of L | R or L ? true : R.
2609 /// Note that the latter form is poison-blocking.
2610 template <typename LHS, typename RHS>
2611 inline LogicalOp_match<LHS, RHS, Instruction::Or> m_LogicalOr(const LHS &L,
2612                                                               const RHS &R) {
2613   return LogicalOp_match<LHS, RHS, Instruction::Or>(L, R);
2614 }
2615 
2616 /// Matches L || R where L and R are arbitrary values.
2617 inline auto m_LogicalOr() { return m_LogicalOr(m_Value(), m_Value()); }
2618 
2619 /// Matches L || R with LHS and RHS in either order.
2620 template <typename LHS, typename RHS>
2621 inline LogicalOp_match<LHS, RHS, Instruction::Or, true>
2622 m_c_LogicalOr(const LHS &L, const RHS &R) {
2623   return LogicalOp_match<LHS, RHS, Instruction::Or, true>(L, R);
2624 }
2625 
2626 /// Matches either L && R or L || R,
2627 /// either one being in the either binary or logical form.
2628 /// Note that the latter form is poison-blocking.
2629 template <typename LHS, typename RHS, bool Commutable = false>
2630 inline auto m_LogicalOp(const LHS &L, const RHS &R) {
2631   return m_CombineOr(
2632       LogicalOp_match<LHS, RHS, Instruction::And, Commutable>(L, R),
2633       LogicalOp_match<LHS, RHS, Instruction::Or, Commutable>(L, R));
2634 }
2635 
2636 /// Matches either L && R or L || R where L and R are arbitrary values.
2637 inline auto m_LogicalOp() { return m_LogicalOp(m_Value(), m_Value()); }
2638 
2639 /// Matches either L && R or L || R with LHS and RHS in either order.
2640 template <typename LHS, typename RHS>
2641 inline auto m_c_LogicalOp(const LHS &L, const RHS &R) {
2642   return m_LogicalOp<LHS, RHS, /*Commutable=*/true>(L, R);
2643 }
2644 
2645 } // end namespace PatternMatch
2646 } // end namespace llvm
2647 
2648 #endif // LLVM_IR_PATTERNMATCH_H
2649