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 
match(Val * V,const Pattern & P)49 template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) {
50   return const_cast<Pattern &>(P).match(V);
51 }
52 
match(ArrayRef<int> Mask,const Pattern & P)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 
OneUse_matchOneUse_match60   OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
61 
matchOneUse_match62   template <typename OpTy> bool match(OpTy *V) {
63     return V->hasOneUse() && SubPattern.match(V);
64   }
65 };
66 
m_OneUse(const T & SubPattern)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 {
matchclass_match72   template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
73 };
74 
75 /// Match an arbitrary value and ignore it.
m_Value()76 inline class_match<Value> m_Value() { return class_match<Value>(); }
77 
78 /// Match an arbitrary unary operation and ignore it.
m_UnOp()79 inline class_match<UnaryOperator> m_UnOp() {
80   return class_match<UnaryOperator>();
81 }
82 
83 /// Match an arbitrary binary operation and ignore it.
m_BinOp()84 inline class_match<BinaryOperator> m_BinOp() {
85   return class_match<BinaryOperator>();
86 }
87 
88 /// Matches any compare instruction and ignore it.
m_Cmp()89 inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
90 
91 struct undef_match {
checkundef_match92   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   }
matchundef_match130   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.
m_Undef()136 inline auto m_Undef() { return undef_match(); }
137 
138 /// Match an arbitrary poison constant.
m_Poison()139 inline class_match<PoisonValue> m_Poison() {
140   return class_match<PoisonValue>();
141 }
142 
143 /// Match an arbitrary Constant and ignore it.
m_Constant()144 inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
145 
146 /// Match an arbitrary ConstantInt and ignore it.
m_ConstantInt()147 inline class_match<ConstantInt> m_ConstantInt() {
148   return class_match<ConstantInt>();
149 }
150 
151 /// Match an arbitrary ConstantFP and ignore it.
m_ConstantFP()152 inline class_match<ConstantFP> m_ConstantFP() {
153   return class_match<ConstantFP>();
154 }
155 
156 struct constantexpr_match {
matchconstantexpr_match157   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.
m_ConstantExpr()165 inline constantexpr_match m_ConstantExpr() { return constantexpr_match(); }
166 
167 /// Match an arbitrary basic block value and ignore it.
m_BasicBlock()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 
match_unlessmatch_unless176   match_unless(const Ty &Matcher) : M(Matcher) {}
177 
matchmatch_unless178   template <typename ITy> bool match(ITy *V) { return !M.match(V); }
179 };
180 
181 /// Match if the inner matcher does *NOT* match.
m_Unless(const Ty & M)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 
match_combine_ormatch_combine_or191   match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
192 
matchmatch_combine_or193   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 
match_combine_andmatch_combine_and206   match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
207 
matchmatch_combine_and208   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>
m_CombineOr(const LTy & L,const RTy & R)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>
m_CombineAnd(const LTy & L,const RTy & R)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 
apint_matchapint_match232   apint_match(const APInt *&Res, bool AllowUndef)
233       : Res(Res), AllowUndef(AllowUndef) {}
234 
matchapint_match235   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 
apfloat_matchapfloat_match257   apfloat_match(const APFloat *&Res, bool AllowUndef)
258       : Res(Res), AllowUndef(AllowUndef) {}
259 
matchapfloat_match260   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.
m_APInt(const APInt * & Res)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.
m_APIntAllowUndef(const APInt * & Res)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.
m_APIntForbidUndef(const APInt * & Res)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.
m_APFloat(const APFloat * & Res)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.
m_APFloatAllowUndef(const APFloat * & Res)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.
m_APFloatForbidUndef(const APFloat * & Res)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 {
matchconstantint_match311   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.
m_ConstantInt()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 {
matchcstval_pred_ty335   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 
api_pred_tyapi_pred_ty383   api_pred_ty(const APInt *&R) : Res(R) {}
384 
matchapi_pred_ty385   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 
apf_pred_tyapf_pred_ty409   apf_pred_ty(const APFloat *&R) : Res(R) {}
410 
matchapf_pred_ty411   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 {
isValueis_any_apint440   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.
m_AnyIntegralConstant()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 {
isValueis_shifted_mask449   bool isValue(const APInt &C) { return C.isShiftedMask(); }
450 };
451 
m_ShiftedMask()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 {
isValueis_all_ones457   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.
m_AllOnes()461 inline cst_pred_ty<is_all_ones> m_AllOnes() {
462   return cst_pred_ty<is_all_ones>();
463 }
464 
465 struct is_maxsignedvalue {
isValueis_maxsignedvalue466   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.
m_MaxSignedValue()471 inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
472   return cst_pred_ty<is_maxsignedvalue>();
473 }
m_MaxSignedValue(const APInt * & V)474 inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
475   return V;
476 }
477 
478 struct is_negative {
isValueis_negative479   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.
m_Negative()483 inline cst_pred_ty<is_negative> m_Negative() {
484   return cst_pred_ty<is_negative>();
485 }
m_Negative(const APInt * & V)486 inline api_pred_ty<is_negative> m_Negative(const APInt *&V) { return V; }
487 
488 struct is_nonnegative {
isValueis_nonnegative489   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.
m_NonNegative()493 inline cst_pred_ty<is_nonnegative> m_NonNegative() {
494   return cst_pred_ty<is_nonnegative>();
495 }
m_NonNegative(const APInt * & V)496 inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) { return V; }
497 
498 struct is_strictlypositive {
isValueis_strictlypositive499   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.
m_StrictlyPositive()503 inline cst_pred_ty<is_strictlypositive> m_StrictlyPositive() {
504   return cst_pred_ty<is_strictlypositive>();
505 }
m_StrictlyPositive(const APInt * & V)506 inline api_pred_ty<is_strictlypositive> m_StrictlyPositive(const APInt *&V) {
507   return V;
508 }
509 
510 struct is_nonpositive {
isValueis_nonpositive511   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.
m_NonPositive()515 inline cst_pred_ty<is_nonpositive> m_NonPositive() {
516   return cst_pred_ty<is_nonpositive>();
517 }
m_NonPositive(const APInt * & V)518 inline api_pred_ty<is_nonpositive> m_NonPositive(const APInt *&V) { return V; }
519 
520 struct is_one {
isValueis_one521   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.
m_One()525 inline cst_pred_ty<is_one> m_One() { return cst_pred_ty<is_one>(); }
526 
527 struct is_zero_int {
isValueis_zero_int528   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.
m_ZeroInt()532 inline cst_pred_ty<is_zero_int> m_ZeroInt() {
533   return cst_pred_ty<is_zero_int>();
534 }
535 
536 struct is_zero {
matchis_zero537   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.
m_Zero()545 inline is_zero m_Zero() { return is_zero(); }
546 
547 struct is_power2 {
isValueis_power2548   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.
m_Power2()552 inline cst_pred_ty<is_power2> m_Power2() { return cst_pred_ty<is_power2>(); }
m_Power2(const APInt * & V)553 inline api_pred_ty<is_power2> m_Power2(const APInt *&V) { return V; }
554 
555 struct is_negated_power2 {
isValueis_negated_power2556   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.
m_NegatedPower2()560 inline cst_pred_ty<is_negated_power2> m_NegatedPower2() {
561   return cst_pred_ty<is_negated_power2>();
562 }
m_NegatedPower2(const APInt * & V)563 inline api_pred_ty<is_negated_power2> m_NegatedPower2(const APInt *&V) {
564   return V;
565 }
566 
567 struct is_negated_power2_or_zero {
isValueis_negated_power2_or_zero568   bool isValue(const APInt &C) { return !C || C.isNegatedPowerOf2(); }
569 };
570 /// Match a integer or vector negated power-of-2.
571 /// For vectors, this includes constants with undefined elements.
m_NegatedPower2OrZero()572 inline cst_pred_ty<is_negated_power2_or_zero> m_NegatedPower2OrZero() {
573   return cst_pred_ty<is_negated_power2_or_zero>();
574 }
575 inline api_pred_ty<is_negated_power2_or_zero>
m_NegatedPower2OrZero(const APInt * & V)576 m_NegatedPower2OrZero(const APInt *&V) {
577   return V;
578 }
579 
580 struct is_power2_or_zero {
isValueis_power2_or_zero581   bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
582 };
583 /// Match an integer or vector of 0 or power-of-2 values.
584 /// For vectors, this includes constants with undefined elements.
m_Power2OrZero()585 inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
586   return cst_pred_ty<is_power2_or_zero>();
587 }
m_Power2OrZero(const APInt * & V)588 inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
589   return V;
590 }
591 
592 struct is_sign_mask {
isValueis_sign_mask593   bool isValue(const APInt &C) { return C.isSignMask(); }
594 };
595 /// Match an integer or vector with only the sign bit(s) set.
596 /// For vectors, this includes constants with undefined elements.
m_SignMask()597 inline cst_pred_ty<is_sign_mask> m_SignMask() {
598   return cst_pred_ty<is_sign_mask>();
599 }
600 
601 struct is_lowbit_mask {
isValueis_lowbit_mask602   bool isValue(const APInt &C) { return C.isMask(); }
603 };
604 /// Match an integer or vector with only the low bit(s) set.
605 /// For vectors, this includes constants with undefined elements.
m_LowBitMask()606 inline cst_pred_ty<is_lowbit_mask> m_LowBitMask() {
607   return cst_pred_ty<is_lowbit_mask>();
608 }
m_LowBitMask(const APInt * & V)609 inline api_pred_ty<is_lowbit_mask> m_LowBitMask(const APInt *&V) { return V; }
610 
611 struct is_lowbit_mask_or_zero {
isValueis_lowbit_mask_or_zero612   bool isValue(const APInt &C) { return !C || C.isMask(); }
613 };
614 /// Match an integer or vector with only the low bit(s) set.
615 /// For vectors, this includes constants with undefined elements.
m_LowBitMaskOrZero()616 inline cst_pred_ty<is_lowbit_mask_or_zero> m_LowBitMaskOrZero() {
617   return cst_pred_ty<is_lowbit_mask_or_zero>();
618 }
m_LowBitMaskOrZero(const APInt * & V)619 inline api_pred_ty<is_lowbit_mask_or_zero> m_LowBitMaskOrZero(const APInt *&V) {
620   return V;
621 }
622 
623 struct icmp_pred_with_threshold {
624   ICmpInst::Predicate Pred;
625   const APInt *Thr;
isValueicmp_pred_with_threshold626   bool isValue(const APInt &C) { return ICmpInst::compare(C, *Thr, Pred); }
627 };
628 /// Match an integer or vector with every element comparing 'pred' (eg/ne/...)
629 /// to Threshold. For vectors, this includes constants with undefined elements.
630 inline cst_pred_ty<icmp_pred_with_threshold>
m_SpecificInt_ICMP(ICmpInst::Predicate Predicate,const APInt & Threshold)631 m_SpecificInt_ICMP(ICmpInst::Predicate Predicate, const APInt &Threshold) {
632   cst_pred_ty<icmp_pred_with_threshold> P;
633   P.Pred = Predicate;
634   P.Thr = &Threshold;
635   return P;
636 }
637 
638 struct is_nan {
isValueis_nan639   bool isValue(const APFloat &C) { return C.isNaN(); }
640 };
641 /// Match an arbitrary NaN constant. This includes quiet and signalling nans.
642 /// For vectors, this includes constants with undefined elements.
m_NaN()643 inline cstfp_pred_ty<is_nan> m_NaN() { return cstfp_pred_ty<is_nan>(); }
644 
645 struct is_nonnan {
isValueis_nonnan646   bool isValue(const APFloat &C) { return !C.isNaN(); }
647 };
648 /// Match a non-NaN FP constant.
649 /// For vectors, this includes constants with undefined elements.
m_NonNaN()650 inline cstfp_pred_ty<is_nonnan> m_NonNaN() {
651   return cstfp_pred_ty<is_nonnan>();
652 }
653 
654 struct is_inf {
isValueis_inf655   bool isValue(const APFloat &C) { return C.isInfinity(); }
656 };
657 /// Match a positive or negative infinity FP constant.
658 /// For vectors, this includes constants with undefined elements.
m_Inf()659 inline cstfp_pred_ty<is_inf> m_Inf() { return cstfp_pred_ty<is_inf>(); }
660 
661 struct is_noninf {
isValueis_noninf662   bool isValue(const APFloat &C) { return !C.isInfinity(); }
663 };
664 /// Match a non-infinity FP constant, i.e. finite or NaN.
665 /// For vectors, this includes constants with undefined elements.
m_NonInf()666 inline cstfp_pred_ty<is_noninf> m_NonInf() {
667   return cstfp_pred_ty<is_noninf>();
668 }
669 
670 struct is_finite {
isValueis_finite671   bool isValue(const APFloat &C) { return C.isFinite(); }
672 };
673 /// Match a finite FP constant, i.e. not infinity or NaN.
674 /// For vectors, this includes constants with undefined elements.
m_Finite()675 inline cstfp_pred_ty<is_finite> m_Finite() {
676   return cstfp_pred_ty<is_finite>();
677 }
m_Finite(const APFloat * & V)678 inline apf_pred_ty<is_finite> m_Finite(const APFloat *&V) { return V; }
679 
680 struct is_finitenonzero {
isValueis_finitenonzero681   bool isValue(const APFloat &C) { return C.isFiniteNonZero(); }
682 };
683 /// Match a finite non-zero FP constant.
684 /// For vectors, this includes constants with undefined elements.
m_FiniteNonZero()685 inline cstfp_pred_ty<is_finitenonzero> m_FiniteNonZero() {
686   return cstfp_pred_ty<is_finitenonzero>();
687 }
m_FiniteNonZero(const APFloat * & V)688 inline apf_pred_ty<is_finitenonzero> m_FiniteNonZero(const APFloat *&V) {
689   return V;
690 }
691 
692 struct is_any_zero_fp {
isValueis_any_zero_fp693   bool isValue(const APFloat &C) { return C.isZero(); }
694 };
695 /// Match a floating-point negative zero or positive zero.
696 /// For vectors, this includes constants with undefined elements.
m_AnyZeroFP()697 inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
698   return cstfp_pred_ty<is_any_zero_fp>();
699 }
700 
701 struct is_pos_zero_fp {
isValueis_pos_zero_fp702   bool isValue(const APFloat &C) { return C.isPosZero(); }
703 };
704 /// Match a floating-point positive zero.
705 /// For vectors, this includes constants with undefined elements.
m_PosZeroFP()706 inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
707   return cstfp_pred_ty<is_pos_zero_fp>();
708 }
709 
710 struct is_neg_zero_fp {
isValueis_neg_zero_fp711   bool isValue(const APFloat &C) { return C.isNegZero(); }
712 };
713 /// Match a floating-point negative zero.
714 /// For vectors, this includes constants with undefined elements.
m_NegZeroFP()715 inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
716   return cstfp_pred_ty<is_neg_zero_fp>();
717 }
718 
719 struct is_non_zero_fp {
isValueis_non_zero_fp720   bool isValue(const APFloat &C) { return C.isNonZero(); }
721 };
722 /// Match a floating-point non-zero.
723 /// For vectors, this includes constants with undefined elements.
m_NonZeroFP()724 inline cstfp_pred_ty<is_non_zero_fp> m_NonZeroFP() {
725   return cstfp_pred_ty<is_non_zero_fp>();
726 }
727 
728 ///////////////////////////////////////////////////////////////////////////////
729 
730 template <typename Class> struct bind_ty {
731   Class *&VR;
732 
bind_tybind_ty733   bind_ty(Class *&V) : VR(V) {}
734 
matchbind_ty735   template <typename ITy> bool match(ITy *V) {
736     if (auto *CV = dyn_cast<Class>(V)) {
737       VR = CV;
738       return true;
739     }
740     return false;
741   }
742 };
743 
744 /// Match a value, capturing it if we match.
m_Value(Value * & V)745 inline bind_ty<Value> m_Value(Value *&V) { return V; }
m_Value(const Value * & V)746 inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
747 
748 /// Match an instruction, capturing it if we match.
m_Instruction(Instruction * & I)749 inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
750 /// Match a unary operator, capturing it if we match.
m_UnOp(UnaryOperator * & I)751 inline bind_ty<UnaryOperator> m_UnOp(UnaryOperator *&I) { return I; }
752 /// Match a binary operator, capturing it if we match.
m_BinOp(BinaryOperator * & I)753 inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
754 /// Match a with overflow intrinsic, capturing it if we match.
m_WithOverflowInst(WithOverflowInst * & I)755 inline bind_ty<WithOverflowInst> m_WithOverflowInst(WithOverflowInst *&I) {
756   return I;
757 }
758 inline bind_ty<const WithOverflowInst>
m_WithOverflowInst(const WithOverflowInst * & I)759 m_WithOverflowInst(const WithOverflowInst *&I) {
760   return I;
761 }
762 
763 /// Match a Constant, capturing the value if we match.
m_Constant(Constant * & C)764 inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
765 
766 /// Match a ConstantInt, capturing the value if we match.
m_ConstantInt(ConstantInt * & CI)767 inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
768 
769 /// Match a ConstantFP, capturing the value if we match.
m_ConstantFP(ConstantFP * & C)770 inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
771 
772 /// Match a ConstantExpr, capturing the value if we match.
m_ConstantExpr(ConstantExpr * & C)773 inline bind_ty<ConstantExpr> m_ConstantExpr(ConstantExpr *&C) { return C; }
774 
775 /// Match a basic block value, capturing it if we match.
m_BasicBlock(BasicBlock * & V)776 inline bind_ty<BasicBlock> m_BasicBlock(BasicBlock *&V) { return V; }
m_BasicBlock(const BasicBlock * & V)777 inline bind_ty<const BasicBlock> m_BasicBlock(const BasicBlock *&V) {
778   return V;
779 }
780 
781 /// Match an arbitrary immediate Constant and ignore it.
782 inline match_combine_and<class_match<Constant>,
783                          match_unless<constantexpr_match>>
m_ImmConstant()784 m_ImmConstant() {
785   return m_CombineAnd(m_Constant(), m_Unless(m_ConstantExpr()));
786 }
787 
788 /// Match an immediate Constant, capturing the value if we match.
789 inline match_combine_and<bind_ty<Constant>,
790                          match_unless<constantexpr_match>>
m_ImmConstant(Constant * & C)791 m_ImmConstant(Constant *&C) {
792   return m_CombineAnd(m_Constant(C), m_Unless(m_ConstantExpr()));
793 }
794 
795 /// Match a specified Value*.
796 struct specificval_ty {
797   const Value *Val;
798 
specificval_tyspecificval_ty799   specificval_ty(const Value *V) : Val(V) {}
800 
matchspecificval_ty801   template <typename ITy> bool match(ITy *V) { return V == Val; }
802 };
803 
804 /// Match if we have a specific specified value.
m_Specific(const Value * V)805 inline specificval_ty m_Specific(const Value *V) { return V; }
806 
807 /// Stores a reference to the Value *, not the Value * itself,
808 /// thus can be used in commutative matchers.
809 template <typename Class> struct deferredval_ty {
810   Class *const &Val;
811 
deferredval_tydeferredval_ty812   deferredval_ty(Class *const &V) : Val(V) {}
813 
matchdeferredval_ty814   template <typename ITy> bool match(ITy *const V) { return V == Val; }
815 };
816 
817 /// Like m_Specific(), but works if the specific value to match is determined
818 /// as part of the same match() expression. For example:
819 /// m_Add(m_Value(X), m_Specific(X)) is incorrect, because m_Specific() will
820 /// bind X before the pattern match starts.
821 /// m_Add(m_Value(X), m_Deferred(X)) is correct, and will check against
822 /// whichever value m_Value(X) populated.
m_Deferred(Value * const & V)823 inline deferredval_ty<Value> m_Deferred(Value *const &V) { return V; }
m_Deferred(const Value * const & V)824 inline deferredval_ty<const Value> m_Deferred(const Value *const &V) {
825   return V;
826 }
827 
828 /// Match a specified floating point value or vector of all elements of
829 /// that value.
830 struct specific_fpval {
831   double Val;
832 
specific_fpvalspecific_fpval833   specific_fpval(double V) : Val(V) {}
834 
matchspecific_fpval835   template <typename ITy> bool match(ITy *V) {
836     if (const auto *CFP = dyn_cast<ConstantFP>(V))
837       return CFP->isExactlyValue(Val);
838     if (V->getType()->isVectorTy())
839       if (const auto *C = dyn_cast<Constant>(V))
840         if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
841           return CFP->isExactlyValue(Val);
842     return false;
843   }
844 };
845 
846 /// Match a specific floating point value or vector with all elements
847 /// equal to the value.
m_SpecificFP(double V)848 inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
849 
850 /// Match a float 1.0 or vector with all elements equal to 1.0.
m_FPOne()851 inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
852 
853 struct bind_const_intval_ty {
854   uint64_t &VR;
855 
bind_const_intval_tybind_const_intval_ty856   bind_const_intval_ty(uint64_t &V) : VR(V) {}
857 
matchbind_const_intval_ty858   template <typename ITy> bool match(ITy *V) {
859     if (const auto *CV = dyn_cast<ConstantInt>(V))
860       if (CV->getValue().ule(UINT64_MAX)) {
861         VR = CV->getZExtValue();
862         return true;
863       }
864     return false;
865   }
866 };
867 
868 /// Match a specified integer value or vector of all elements of that
869 /// value.
870 template <bool AllowUndefs> struct specific_intval {
871   APInt Val;
872 
specific_intvalspecific_intval873   specific_intval(APInt V) : Val(std::move(V)) {}
874 
matchspecific_intval875   template <typename ITy> bool match(ITy *V) {
876     const auto *CI = dyn_cast<ConstantInt>(V);
877     if (!CI && V->getType()->isVectorTy())
878       if (const auto *C = dyn_cast<Constant>(V))
879         CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue(AllowUndefs));
880 
881     return CI && APInt::isSameValue(CI->getValue(), Val);
882   }
883 };
884 
885 /// Match a specific integer value or vector with all elements equal to
886 /// the value.
m_SpecificInt(APInt V)887 inline specific_intval<false> m_SpecificInt(APInt V) {
888   return specific_intval<false>(std::move(V));
889 }
890 
m_SpecificInt(uint64_t V)891 inline specific_intval<false> m_SpecificInt(uint64_t V) {
892   return m_SpecificInt(APInt(64, V));
893 }
894 
m_SpecificIntAllowUndef(APInt V)895 inline specific_intval<true> m_SpecificIntAllowUndef(APInt V) {
896   return specific_intval<true>(std::move(V));
897 }
898 
m_SpecificIntAllowUndef(uint64_t V)899 inline specific_intval<true> m_SpecificIntAllowUndef(uint64_t V) {
900   return m_SpecificIntAllowUndef(APInt(64, V));
901 }
902 
903 /// Match a ConstantInt and bind to its value.  This does not match
904 /// ConstantInts wider than 64-bits.
m_ConstantInt(uint64_t & V)905 inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
906 
907 /// Match a specified basic block value.
908 struct specific_bbval {
909   BasicBlock *Val;
910 
specific_bbvalspecific_bbval911   specific_bbval(BasicBlock *Val) : Val(Val) {}
912 
matchspecific_bbval913   template <typename ITy> bool match(ITy *V) {
914     const auto *BB = dyn_cast<BasicBlock>(V);
915     return BB && BB == Val;
916   }
917 };
918 
919 /// Match a specific basic block value.
m_SpecificBB(BasicBlock * BB)920 inline specific_bbval m_SpecificBB(BasicBlock *BB) {
921   return specific_bbval(BB);
922 }
923 
924 /// A commutative-friendly version of m_Specific().
m_Deferred(BasicBlock * const & BB)925 inline deferredval_ty<BasicBlock> m_Deferred(BasicBlock *const &BB) {
926   return BB;
927 }
928 inline deferredval_ty<const BasicBlock>
m_Deferred(const BasicBlock * const & BB)929 m_Deferred(const BasicBlock *const &BB) {
930   return BB;
931 }
932 
933 //===----------------------------------------------------------------------===//
934 // Matcher for any binary operator.
935 //
936 template <typename LHS_t, typename RHS_t, bool Commutable = false>
937 struct AnyBinaryOp_match {
938   LHS_t L;
939   RHS_t R;
940 
941   // The evaluation order is always stable, regardless of Commutability.
942   // The LHS is always matched first.
AnyBinaryOp_matchAnyBinaryOp_match943   AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
944 
matchAnyBinaryOp_match945   template <typename OpTy> bool match(OpTy *V) {
946     if (auto *I = dyn_cast<BinaryOperator>(V))
947       return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
948              (Commutable && L.match(I->getOperand(1)) &&
949               R.match(I->getOperand(0)));
950     return false;
951   }
952 };
953 
954 template <typename LHS, typename RHS>
m_BinOp(const LHS & L,const RHS & R)955 inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
956   return AnyBinaryOp_match<LHS, RHS>(L, R);
957 }
958 
959 //===----------------------------------------------------------------------===//
960 // Matcher for any unary operator.
961 // TODO fuse unary, binary matcher into n-ary matcher
962 //
963 template <typename OP_t> struct AnyUnaryOp_match {
964   OP_t X;
965 
AnyUnaryOp_matchAnyUnaryOp_match966   AnyUnaryOp_match(const OP_t &X) : X(X) {}
967 
matchAnyUnaryOp_match968   template <typename OpTy> bool match(OpTy *V) {
969     if (auto *I = dyn_cast<UnaryOperator>(V))
970       return X.match(I->getOperand(0));
971     return false;
972   }
973 };
974 
m_UnOp(const OP_t & X)975 template <typename OP_t> inline AnyUnaryOp_match<OP_t> m_UnOp(const OP_t &X) {
976   return AnyUnaryOp_match<OP_t>(X);
977 }
978 
979 //===----------------------------------------------------------------------===//
980 // Matchers for specific binary operators.
981 //
982 
983 template <typename LHS_t, typename RHS_t, unsigned Opcode,
984           bool Commutable = false>
985 struct BinaryOp_match {
986   LHS_t L;
987   RHS_t R;
988 
989   // The evaluation order is always stable, regardless of Commutability.
990   // The LHS is always matched first.
BinaryOp_matchBinaryOp_match991   BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
992 
matchBinaryOp_match993   template <typename OpTy> inline bool match(unsigned Opc, OpTy *V) {
994     if (V->getValueID() == Value::InstructionVal + Opc) {
995       auto *I = cast<BinaryOperator>(V);
996       return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
997              (Commutable && L.match(I->getOperand(1)) &&
998               R.match(I->getOperand(0)));
999     }
1000     return false;
1001   }
1002 
matchBinaryOp_match1003   template <typename OpTy> bool match(OpTy *V) { return match(Opcode, V); }
1004 };
1005 
1006 template <typename LHS, typename RHS>
m_Add(const LHS & L,const RHS & R)1007 inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
1008                                                         const RHS &R) {
1009   return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
1010 }
1011 
1012 template <typename LHS, typename RHS>
m_FAdd(const LHS & L,const RHS & R)1013 inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
1014                                                           const RHS &R) {
1015   return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
1016 }
1017 
1018 template <typename LHS, typename RHS>
m_Sub(const LHS & L,const RHS & R)1019 inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
1020                                                         const RHS &R) {
1021   return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
1022 }
1023 
1024 template <typename LHS, typename RHS>
m_FSub(const LHS & L,const RHS & R)1025 inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
1026                                                           const RHS &R) {
1027   return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
1028 }
1029 
1030 template <typename Op_t> struct FNeg_match {
1031   Op_t X;
1032 
FNeg_matchFNeg_match1033   FNeg_match(const Op_t &Op) : X(Op) {}
matchFNeg_match1034   template <typename OpTy> bool match(OpTy *V) {
1035     auto *FPMO = dyn_cast<FPMathOperator>(V);
1036     if (!FPMO)
1037       return false;
1038 
1039     if (FPMO->getOpcode() == Instruction::FNeg)
1040       return X.match(FPMO->getOperand(0));
1041 
1042     if (FPMO->getOpcode() == Instruction::FSub) {
1043       if (FPMO->hasNoSignedZeros()) {
1044         // With 'nsz', any zero goes.
1045         if (!cstfp_pred_ty<is_any_zero_fp>().match(FPMO->getOperand(0)))
1046           return false;
1047       } else {
1048         // Without 'nsz', we need fsub -0.0, X exactly.
1049         if (!cstfp_pred_ty<is_neg_zero_fp>().match(FPMO->getOperand(0)))
1050           return false;
1051       }
1052 
1053       return X.match(FPMO->getOperand(1));
1054     }
1055 
1056     return false;
1057   }
1058 };
1059 
1060 /// Match 'fneg X' as 'fsub -0.0, X'.
m_FNeg(const OpTy & X)1061 template <typename OpTy> inline FNeg_match<OpTy> m_FNeg(const OpTy &X) {
1062   return FNeg_match<OpTy>(X);
1063 }
1064 
1065 /// Match 'fneg X' as 'fsub +-0.0, X'.
1066 template <typename RHS>
1067 inline BinaryOp_match<cstfp_pred_ty<is_any_zero_fp>, RHS, Instruction::FSub>
m_FNegNSZ(const RHS & X)1068 m_FNegNSZ(const RHS &X) {
1069   return m_FSub(m_AnyZeroFP(), X);
1070 }
1071 
1072 template <typename LHS, typename RHS>
m_Mul(const LHS & L,const RHS & R)1073 inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
1074                                                         const RHS &R) {
1075   return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
1076 }
1077 
1078 template <typename LHS, typename RHS>
m_FMul(const LHS & L,const RHS & R)1079 inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
1080                                                           const RHS &R) {
1081   return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
1082 }
1083 
1084 template <typename LHS, typename RHS>
m_UDiv(const LHS & L,const RHS & R)1085 inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
1086                                                           const RHS &R) {
1087   return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
1088 }
1089 
1090 template <typename LHS, typename RHS>
m_SDiv(const LHS & L,const RHS & R)1091 inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
1092                                                           const RHS &R) {
1093   return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
1094 }
1095 
1096 template <typename LHS, typename RHS>
m_FDiv(const LHS & L,const RHS & R)1097 inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
1098                                                           const RHS &R) {
1099   return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
1100 }
1101 
1102 template <typename LHS, typename RHS>
m_URem(const LHS & L,const RHS & R)1103 inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
1104                                                           const RHS &R) {
1105   return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
1106 }
1107 
1108 template <typename LHS, typename RHS>
m_SRem(const LHS & L,const RHS & R)1109 inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
1110                                                           const RHS &R) {
1111   return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
1112 }
1113 
1114 template <typename LHS, typename RHS>
m_FRem(const LHS & L,const RHS & R)1115 inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
1116                                                           const RHS &R) {
1117   return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
1118 }
1119 
1120 template <typename LHS, typename RHS>
m_And(const LHS & L,const RHS & R)1121 inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
1122                                                         const RHS &R) {
1123   return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
1124 }
1125 
1126 template <typename LHS, typename RHS>
m_Or(const LHS & L,const RHS & R)1127 inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
1128                                                       const RHS &R) {
1129   return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
1130 }
1131 
1132 template <typename LHS, typename RHS>
m_Xor(const LHS & L,const RHS & R)1133 inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
1134                                                         const RHS &R) {
1135   return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
1136 }
1137 
1138 template <typename LHS, typename RHS>
m_Shl(const LHS & L,const RHS & R)1139 inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
1140                                                         const RHS &R) {
1141   return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
1142 }
1143 
1144 template <typename LHS, typename RHS>
m_LShr(const LHS & L,const RHS & R)1145 inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
1146                                                           const RHS &R) {
1147   return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
1148 }
1149 
1150 template <typename LHS, typename RHS>
m_AShr(const LHS & L,const RHS & R)1151 inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
1152                                                           const RHS &R) {
1153   return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
1154 }
1155 
1156 template <typename LHS_t, typename RHS_t, unsigned Opcode,
1157           unsigned WrapFlags = 0>
1158 struct OverflowingBinaryOp_match {
1159   LHS_t L;
1160   RHS_t R;
1161 
OverflowingBinaryOp_matchOverflowingBinaryOp_match1162   OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
1163       : L(LHS), R(RHS) {}
1164 
matchOverflowingBinaryOp_match1165   template <typename OpTy> bool match(OpTy *V) {
1166     if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
1167       if (Op->getOpcode() != Opcode)
1168         return false;
1169       if ((WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap) &&
1170           !Op->hasNoUnsignedWrap())
1171         return false;
1172       if ((WrapFlags & OverflowingBinaryOperator::NoSignedWrap) &&
1173           !Op->hasNoSignedWrap())
1174         return false;
1175       return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
1176     }
1177     return false;
1178   }
1179 };
1180 
1181 template <typename LHS, typename RHS>
1182 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1183                                  OverflowingBinaryOperator::NoSignedWrap>
m_NSWAdd(const LHS & L,const RHS & R)1184 m_NSWAdd(const LHS &L, const RHS &R) {
1185   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1186                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1187                                                                             R);
1188 }
1189 template <typename LHS, typename RHS>
1190 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1191                                  OverflowingBinaryOperator::NoSignedWrap>
m_NSWSub(const LHS & L,const RHS & R)1192 m_NSWSub(const LHS &L, const RHS &R) {
1193   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1194                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1195                                                                             R);
1196 }
1197 template <typename LHS, typename RHS>
1198 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1199                                  OverflowingBinaryOperator::NoSignedWrap>
m_NSWMul(const LHS & L,const RHS & R)1200 m_NSWMul(const LHS &L, const RHS &R) {
1201   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1202                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1203                                                                             R);
1204 }
1205 template <typename LHS, typename RHS>
1206 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1207                                  OverflowingBinaryOperator::NoSignedWrap>
m_NSWShl(const LHS & L,const RHS & R)1208 m_NSWShl(const LHS &L, const RHS &R) {
1209   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1210                                    OverflowingBinaryOperator::NoSignedWrap>(L,
1211                                                                             R);
1212 }
1213 
1214 template <typename LHS, typename RHS>
1215 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1216                                  OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWAdd(const LHS & L,const RHS & R)1217 m_NUWAdd(const LHS &L, const RHS &R) {
1218   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
1219                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1220       L, R);
1221 }
1222 template <typename LHS, typename RHS>
1223 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1224                                  OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWSub(const LHS & L,const RHS & R)1225 m_NUWSub(const LHS &L, const RHS &R) {
1226   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
1227                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1228       L, R);
1229 }
1230 template <typename LHS, typename RHS>
1231 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1232                                  OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWMul(const LHS & L,const RHS & R)1233 m_NUWMul(const LHS &L, const RHS &R) {
1234   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
1235                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1236       L, R);
1237 }
1238 template <typename LHS, typename RHS>
1239 inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1240                                  OverflowingBinaryOperator::NoUnsignedWrap>
m_NUWShl(const LHS & L,const RHS & R)1241 m_NUWShl(const LHS &L, const RHS &R) {
1242   return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
1243                                    OverflowingBinaryOperator::NoUnsignedWrap>(
1244       L, R);
1245 }
1246 
1247 template <typename LHS_t, typename RHS_t, bool Commutable = false>
1248 struct SpecificBinaryOp_match
1249     : public BinaryOp_match<LHS_t, RHS_t, 0, Commutable> {
1250   unsigned Opcode;
1251 
SpecificBinaryOp_matchSpecificBinaryOp_match1252   SpecificBinaryOp_match(unsigned Opcode, const LHS_t &LHS, const RHS_t &RHS)
1253       : BinaryOp_match<LHS_t, RHS_t, 0, Commutable>(LHS, RHS), Opcode(Opcode) {}
1254 
matchSpecificBinaryOp_match1255   template <typename OpTy> bool match(OpTy *V) {
1256     return BinaryOp_match<LHS_t, RHS_t, 0, Commutable>::match(Opcode, V);
1257   }
1258 };
1259 
1260 /// Matches a specific opcode.
1261 template <typename LHS, typename RHS>
m_BinOp(unsigned Opcode,const LHS & L,const RHS & R)1262 inline SpecificBinaryOp_match<LHS, RHS> m_BinOp(unsigned Opcode, const LHS &L,
1263                                                 const RHS &R) {
1264   return SpecificBinaryOp_match<LHS, RHS>(Opcode, L, R);
1265 }
1266 
1267 template <typename LHS, typename RHS, bool Commutable = false>
1268 struct DisjointOr_match {
1269   LHS L;
1270   RHS R;
1271 
DisjointOr_matchDisjointOr_match1272   DisjointOr_match(const LHS &L, const RHS &R) : L(L), R(R) {}
1273 
matchDisjointOr_match1274   template <typename OpTy> bool match(OpTy *V) {
1275     if (auto *PDI = dyn_cast<PossiblyDisjointInst>(V)) {
1276       assert(PDI->getOpcode() == Instruction::Or && "Only or can be disjoint");
1277       if (!PDI->isDisjoint())
1278         return false;
1279       return (L.match(PDI->getOperand(0)) && R.match(PDI->getOperand(1))) ||
1280              (Commutable && L.match(PDI->getOperand(1)) &&
1281               R.match(PDI->getOperand(0)));
1282     }
1283     return false;
1284   }
1285 };
1286 
1287 template <typename LHS, typename RHS>
m_DisjointOr(const LHS & L,const RHS & R)1288 inline DisjointOr_match<LHS, RHS> m_DisjointOr(const LHS &L, const RHS &R) {
1289   return DisjointOr_match<LHS, RHS>(L, R);
1290 }
1291 
1292 template <typename LHS, typename RHS>
m_c_DisjointOr(const LHS & L,const RHS & R)1293 inline DisjointOr_match<LHS, RHS, true> m_c_DisjointOr(const LHS &L,
1294                                                        const RHS &R) {
1295   return DisjointOr_match<LHS, RHS, true>(L, R);
1296 }
1297 
1298 /// Match either "add" or "or disjoint".
1299 template <typename LHS, typename RHS>
1300 inline match_combine_or<BinaryOp_match<LHS, RHS, Instruction::Add>,
1301                         DisjointOr_match<LHS, RHS>>
m_AddLike(const LHS & L,const RHS & R)1302 m_AddLike(const LHS &L, const RHS &R) {
1303   return m_CombineOr(m_Add(L, R), m_DisjointOr(L, R));
1304 }
1305 
1306 //===----------------------------------------------------------------------===//
1307 // Class that matches a group of binary opcodes.
1308 //
1309 template <typename LHS_t, typename RHS_t, typename Predicate>
1310 struct BinOpPred_match : Predicate {
1311   LHS_t L;
1312   RHS_t R;
1313 
BinOpPred_matchBinOpPred_match1314   BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1315 
matchBinOpPred_match1316   template <typename OpTy> bool match(OpTy *V) {
1317     if (auto *I = dyn_cast<Instruction>(V))
1318       return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) &&
1319              R.match(I->getOperand(1));
1320     return false;
1321   }
1322 };
1323 
1324 struct is_shift_op {
isOpTypeis_shift_op1325   bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); }
1326 };
1327 
1328 struct is_right_shift_op {
isOpTypeis_right_shift_op1329   bool isOpType(unsigned Opcode) {
1330     return Opcode == Instruction::LShr || Opcode == Instruction::AShr;
1331   }
1332 };
1333 
1334 struct is_logical_shift_op {
isOpTypeis_logical_shift_op1335   bool isOpType(unsigned Opcode) {
1336     return Opcode == Instruction::LShr || Opcode == Instruction::Shl;
1337   }
1338 };
1339 
1340 struct is_bitwiselogic_op {
isOpTypeis_bitwiselogic_op1341   bool isOpType(unsigned Opcode) {
1342     return Instruction::isBitwiseLogicOp(Opcode);
1343   }
1344 };
1345 
1346 struct is_idiv_op {
isOpTypeis_idiv_op1347   bool isOpType(unsigned Opcode) {
1348     return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
1349   }
1350 };
1351 
1352 struct is_irem_op {
isOpTypeis_irem_op1353   bool isOpType(unsigned Opcode) {
1354     return Opcode == Instruction::SRem || Opcode == Instruction::URem;
1355   }
1356 };
1357 
1358 /// Matches shift operations.
1359 template <typename LHS, typename RHS>
m_Shift(const LHS & L,const RHS & R)1360 inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L,
1361                                                       const RHS &R) {
1362   return BinOpPred_match<LHS, RHS, is_shift_op>(L, R);
1363 }
1364 
1365 /// Matches logical shift operations.
1366 template <typename LHS, typename RHS>
m_Shr(const LHS & L,const RHS & R)1367 inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L,
1368                                                           const RHS &R) {
1369   return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R);
1370 }
1371 
1372 /// Matches logical shift operations.
1373 template <typename LHS, typename RHS>
1374 inline BinOpPred_match<LHS, RHS, is_logical_shift_op>
m_LogicalShift(const LHS & L,const RHS & R)1375 m_LogicalShift(const LHS &L, const RHS &R) {
1376   return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R);
1377 }
1378 
1379 /// Matches bitwise logic operations.
1380 template <typename LHS, typename RHS>
1381 inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op>
m_BitwiseLogic(const LHS & L,const RHS & R)1382 m_BitwiseLogic(const LHS &L, const RHS &R) {
1383   return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R);
1384 }
1385 
1386 /// Matches integer division operations.
1387 template <typename LHS, typename RHS>
m_IDiv(const LHS & L,const RHS & R)1388 inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L,
1389                                                     const RHS &R) {
1390   return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R);
1391 }
1392 
1393 /// Matches integer remainder operations.
1394 template <typename LHS, typename RHS>
m_IRem(const LHS & L,const RHS & R)1395 inline BinOpPred_match<LHS, RHS, is_irem_op> m_IRem(const LHS &L,
1396                                                     const RHS &R) {
1397   return BinOpPred_match<LHS, RHS, is_irem_op>(L, R);
1398 }
1399 
1400 //===----------------------------------------------------------------------===//
1401 // Class that matches exact binary ops.
1402 //
1403 template <typename SubPattern_t> struct Exact_match {
1404   SubPattern_t SubPattern;
1405 
Exact_matchExact_match1406   Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
1407 
matchExact_match1408   template <typename OpTy> bool match(OpTy *V) {
1409     if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
1410       return PEO->isExact() && SubPattern.match(V);
1411     return false;
1412   }
1413 };
1414 
m_Exact(const T & SubPattern)1415 template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
1416   return SubPattern;
1417 }
1418 
1419 //===----------------------------------------------------------------------===//
1420 // Matchers for CmpInst classes
1421 //
1422 
1423 template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy,
1424           bool Commutable = false>
1425 struct CmpClass_match {
1426   PredicateTy &Predicate;
1427   LHS_t L;
1428   RHS_t R;
1429 
1430   // The evaluation order is always stable, regardless of Commutability.
1431   // The LHS is always matched first.
CmpClass_matchCmpClass_match1432   CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
1433       : Predicate(Pred), L(LHS), R(RHS) {}
1434 
matchCmpClass_match1435   template <typename OpTy> bool match(OpTy *V) {
1436     if (auto *I = dyn_cast<Class>(V)) {
1437       if (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) {
1438         Predicate = I->getPredicate();
1439         return true;
1440       } else if (Commutable && L.match(I->getOperand(1)) &&
1441                  R.match(I->getOperand(0))) {
1442         Predicate = I->getSwappedPredicate();
1443         return true;
1444       }
1445     }
1446     return false;
1447   }
1448 };
1449 
1450 template <typename LHS, typename RHS>
1451 inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
m_Cmp(CmpInst::Predicate & Pred,const LHS & L,const RHS & R)1452 m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1453   return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
1454 }
1455 
1456 template <typename LHS, typename RHS>
1457 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
m_ICmp(ICmpInst::Predicate & Pred,const LHS & L,const RHS & R)1458 m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1459   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
1460 }
1461 
1462 template <typename LHS, typename RHS>
1463 inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
m_FCmp(FCmpInst::Predicate & Pred,const LHS & L,const RHS & R)1464 m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1465   return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
1466 }
1467 
1468 //===----------------------------------------------------------------------===//
1469 // Matchers for instructions with a given opcode and number of operands.
1470 //
1471 
1472 /// Matches instructions with Opcode and three operands.
1473 template <typename T0, unsigned Opcode> struct OneOps_match {
1474   T0 Op1;
1475 
OneOps_matchOneOps_match1476   OneOps_match(const T0 &Op1) : Op1(Op1) {}
1477 
matchOneOps_match1478   template <typename OpTy> bool match(OpTy *V) {
1479     if (V->getValueID() == Value::InstructionVal + Opcode) {
1480       auto *I = cast<Instruction>(V);
1481       return Op1.match(I->getOperand(0));
1482     }
1483     return false;
1484   }
1485 };
1486 
1487 /// Matches instructions with Opcode and three operands.
1488 template <typename T0, typename T1, unsigned Opcode> struct TwoOps_match {
1489   T0 Op1;
1490   T1 Op2;
1491 
TwoOps_matchTwoOps_match1492   TwoOps_match(const T0 &Op1, const T1 &Op2) : Op1(Op1), Op2(Op2) {}
1493 
matchTwoOps_match1494   template <typename OpTy> bool match(OpTy *V) {
1495     if (V->getValueID() == Value::InstructionVal + Opcode) {
1496       auto *I = cast<Instruction>(V);
1497       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1));
1498     }
1499     return false;
1500   }
1501 };
1502 
1503 /// Matches instructions with Opcode and three operands.
1504 template <typename T0, typename T1, typename T2, unsigned Opcode>
1505 struct ThreeOps_match {
1506   T0 Op1;
1507   T1 Op2;
1508   T2 Op3;
1509 
ThreeOps_matchThreeOps_match1510   ThreeOps_match(const T0 &Op1, const T1 &Op2, const T2 &Op3)
1511       : Op1(Op1), Op2(Op2), Op3(Op3) {}
1512 
matchThreeOps_match1513   template <typename OpTy> bool match(OpTy *V) {
1514     if (V->getValueID() == Value::InstructionVal + Opcode) {
1515       auto *I = cast<Instruction>(V);
1516       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1517              Op3.match(I->getOperand(2));
1518     }
1519     return false;
1520   }
1521 };
1522 
1523 /// Matches instructions with Opcode and any number of operands
1524 template <unsigned Opcode, typename... OperandTypes> struct AnyOps_match {
1525   std::tuple<OperandTypes...> Operands;
1526 
AnyOps_matchAnyOps_match1527   AnyOps_match(const OperandTypes &...Ops) : Operands(Ops...) {}
1528 
1529   // Operand matching works by recursively calling match_operands, matching the
1530   // operands left to right. The first version is called for each operand but
1531   // the last, for which the second version is called. The second version of
1532   // match_operands is also used to match each individual operand.
1533   template <int Idx, int Last>
match_operandsAnyOps_match1534   std::enable_if_t<Idx != Last, bool> match_operands(const Instruction *I) {
1535     return match_operands<Idx, Idx>(I) && match_operands<Idx + 1, Last>(I);
1536   }
1537 
1538   template <int Idx, int Last>
match_operandsAnyOps_match1539   std::enable_if_t<Idx == Last, bool> match_operands(const Instruction *I) {
1540     return std::get<Idx>(Operands).match(I->getOperand(Idx));
1541   }
1542 
matchAnyOps_match1543   template <typename OpTy> bool match(OpTy *V) {
1544     if (V->getValueID() == Value::InstructionVal + Opcode) {
1545       auto *I = cast<Instruction>(V);
1546       return I->getNumOperands() == sizeof...(OperandTypes) &&
1547              match_operands<0, sizeof...(OperandTypes) - 1>(I);
1548     }
1549     return false;
1550   }
1551 };
1552 
1553 /// Matches SelectInst.
1554 template <typename Cond, typename LHS, typename RHS>
1555 inline ThreeOps_match<Cond, LHS, RHS, Instruction::Select>
m_Select(const Cond & C,const LHS & L,const RHS & R)1556 m_Select(const Cond &C, const LHS &L, const RHS &R) {
1557   return ThreeOps_match<Cond, LHS, RHS, Instruction::Select>(C, L, R);
1558 }
1559 
1560 /// This matches a select of two constants, e.g.:
1561 /// m_SelectCst<-1, 0>(m_Value(V))
1562 template <int64_t L, int64_t R, typename Cond>
1563 inline ThreeOps_match<Cond, constantint_match<L>, constantint_match<R>,
1564                       Instruction::Select>
m_SelectCst(const Cond & C)1565 m_SelectCst(const Cond &C) {
1566   return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
1567 }
1568 
1569 /// Matches FreezeInst.
1570 template <typename OpTy>
m_Freeze(const OpTy & Op)1571 inline OneOps_match<OpTy, Instruction::Freeze> m_Freeze(const OpTy &Op) {
1572   return OneOps_match<OpTy, Instruction::Freeze>(Op);
1573 }
1574 
1575 /// Matches InsertElementInst.
1576 template <typename Val_t, typename Elt_t, typename Idx_t>
1577 inline ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>
m_InsertElt(const Val_t & Val,const Elt_t & Elt,const Idx_t & Idx)1578 m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) {
1579   return ThreeOps_match<Val_t, Elt_t, Idx_t, Instruction::InsertElement>(
1580       Val, Elt, Idx);
1581 }
1582 
1583 /// Matches ExtractElementInst.
1584 template <typename Val_t, typename Idx_t>
1585 inline TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>
m_ExtractElt(const Val_t & Val,const Idx_t & Idx)1586 m_ExtractElt(const Val_t &Val, const Idx_t &Idx) {
1587   return TwoOps_match<Val_t, Idx_t, Instruction::ExtractElement>(Val, Idx);
1588 }
1589 
1590 /// Matches shuffle.
1591 template <typename T0, typename T1, typename T2> struct Shuffle_match {
1592   T0 Op1;
1593   T1 Op2;
1594   T2 Mask;
1595 
Shuffle_matchShuffle_match1596   Shuffle_match(const T0 &Op1, const T1 &Op2, const T2 &Mask)
1597       : Op1(Op1), Op2(Op2), Mask(Mask) {}
1598 
matchShuffle_match1599   template <typename OpTy> bool match(OpTy *V) {
1600     if (auto *I = dyn_cast<ShuffleVectorInst>(V)) {
1601       return Op1.match(I->getOperand(0)) && Op2.match(I->getOperand(1)) &&
1602              Mask.match(I->getShuffleMask());
1603     }
1604     return false;
1605   }
1606 };
1607 
1608 struct m_Mask {
1609   ArrayRef<int> &MaskRef;
m_Maskm_Mask1610   m_Mask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
matchm_Mask1611   bool match(ArrayRef<int> Mask) {
1612     MaskRef = Mask;
1613     return true;
1614   }
1615 };
1616 
1617 struct m_ZeroMask {
matchm_ZeroMask1618   bool match(ArrayRef<int> Mask) {
1619     return all_of(Mask, [](int Elem) { return Elem == 0 || Elem == -1; });
1620   }
1621 };
1622 
1623 struct m_SpecificMask {
1624   ArrayRef<int> &MaskRef;
m_SpecificMaskm_SpecificMask1625   m_SpecificMask(ArrayRef<int> &MaskRef) : MaskRef(MaskRef) {}
matchm_SpecificMask1626   bool match(ArrayRef<int> Mask) { return MaskRef == Mask; }
1627 };
1628 
1629 struct m_SplatOrUndefMask {
1630   int &SplatIndex;
m_SplatOrUndefMaskm_SplatOrUndefMask1631   m_SplatOrUndefMask(int &SplatIndex) : SplatIndex(SplatIndex) {}
matchm_SplatOrUndefMask1632   bool match(ArrayRef<int> Mask) {
1633     const auto *First = find_if(Mask, [](int Elem) { return Elem != -1; });
1634     if (First == Mask.end())
1635       return false;
1636     SplatIndex = *First;
1637     return all_of(Mask,
1638                   [First](int Elem) { return Elem == *First || Elem == -1; });
1639   }
1640 };
1641 
1642 template <typename PointerOpTy, typename OffsetOpTy> struct PtrAdd_match {
1643   PointerOpTy PointerOp;
1644   OffsetOpTy OffsetOp;
1645 
PtrAdd_matchPtrAdd_match1646   PtrAdd_match(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp)
1647       : PointerOp(PointerOp), OffsetOp(OffsetOp) {}
1648 
matchPtrAdd_match1649   template <typename OpTy> bool match(OpTy *V) {
1650     auto *GEP = dyn_cast<GEPOperator>(V);
1651     return GEP && GEP->getSourceElementType()->isIntegerTy(8) &&
1652            PointerOp.match(GEP->getPointerOperand()) &&
1653            OffsetOp.match(GEP->idx_begin()->get());
1654   }
1655 };
1656 
1657 /// Matches ShuffleVectorInst independently of mask value.
1658 template <typename V1_t, typename V2_t>
1659 inline TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>
m_Shuffle(const V1_t & v1,const V2_t & v2)1660 m_Shuffle(const V1_t &v1, const V2_t &v2) {
1661   return TwoOps_match<V1_t, V2_t, Instruction::ShuffleVector>(v1, v2);
1662 }
1663 
1664 template <typename V1_t, typename V2_t, typename Mask_t>
1665 inline Shuffle_match<V1_t, V2_t, Mask_t>
m_Shuffle(const V1_t & v1,const V2_t & v2,const Mask_t & mask)1666 m_Shuffle(const V1_t &v1, const V2_t &v2, const Mask_t &mask) {
1667   return Shuffle_match<V1_t, V2_t, Mask_t>(v1, v2, mask);
1668 }
1669 
1670 /// Matches LoadInst.
1671 template <typename OpTy>
m_Load(const OpTy & Op)1672 inline OneOps_match<OpTy, Instruction::Load> m_Load(const OpTy &Op) {
1673   return OneOps_match<OpTy, Instruction::Load>(Op);
1674 }
1675 
1676 /// Matches StoreInst.
1677 template <typename ValueOpTy, typename PointerOpTy>
1678 inline TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>
m_Store(const ValueOpTy & ValueOp,const PointerOpTy & PointerOp)1679 m_Store(const ValueOpTy &ValueOp, const PointerOpTy &PointerOp) {
1680   return TwoOps_match<ValueOpTy, PointerOpTy, Instruction::Store>(ValueOp,
1681                                                                   PointerOp);
1682 }
1683 
1684 /// Matches GetElementPtrInst.
1685 template <typename... OperandTypes>
m_GEP(const OperandTypes &...Ops)1686 inline auto m_GEP(const OperandTypes &...Ops) {
1687   return AnyOps_match<Instruction::GetElementPtr, OperandTypes...>(Ops...);
1688 }
1689 
1690 /// Matches GEP with i8 source element type
1691 template <typename PointerOpTy, typename OffsetOpTy>
1692 inline PtrAdd_match<PointerOpTy, OffsetOpTy>
m_PtrAdd(const PointerOpTy & PointerOp,const OffsetOpTy & OffsetOp)1693 m_PtrAdd(const PointerOpTy &PointerOp, const OffsetOpTy &OffsetOp) {
1694   return PtrAdd_match<PointerOpTy, OffsetOpTy>(PointerOp, OffsetOp);
1695 }
1696 
1697 //===----------------------------------------------------------------------===//
1698 // Matchers for CastInst classes
1699 //
1700 
1701 template <typename Op_t, unsigned Opcode> struct CastOperator_match {
1702   Op_t Op;
1703 
CastOperator_matchCastOperator_match1704   CastOperator_match(const Op_t &OpMatch) : Op(OpMatch) {}
1705 
matchCastOperator_match1706   template <typename OpTy> bool match(OpTy *V) {
1707     if (auto *O = dyn_cast<Operator>(V))
1708       return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
1709     return false;
1710   }
1711 };
1712 
1713 template <typename Op_t, typename Class> struct CastInst_match {
1714   Op_t Op;
1715 
CastInst_matchCastInst_match1716   CastInst_match(const Op_t &OpMatch) : Op(OpMatch) {}
1717 
matchCastInst_match1718   template <typename OpTy> bool match(OpTy *V) {
1719     if (auto *I = dyn_cast<Class>(V))
1720       return Op.match(I->getOperand(0));
1721     return false;
1722   }
1723 };
1724 
1725 template <typename Op_t> struct PtrToIntSameSize_match {
1726   const DataLayout &DL;
1727   Op_t Op;
1728 
PtrToIntSameSize_matchPtrToIntSameSize_match1729   PtrToIntSameSize_match(const DataLayout &DL, const Op_t &OpMatch)
1730       : DL(DL), Op(OpMatch) {}
1731 
matchPtrToIntSameSize_match1732   template <typename OpTy> bool match(OpTy *V) {
1733     if (auto *O = dyn_cast<Operator>(V))
1734       return O->getOpcode() == Instruction::PtrToInt &&
1735              DL.getTypeSizeInBits(O->getType()) ==
1736                  DL.getTypeSizeInBits(O->getOperand(0)->getType()) &&
1737              Op.match(O->getOperand(0));
1738     return false;
1739   }
1740 };
1741 
1742 template <typename Op_t> struct NNegZExt_match {
1743   Op_t Op;
1744 
NNegZExt_matchNNegZExt_match1745   NNegZExt_match(const Op_t &OpMatch) : Op(OpMatch) {}
1746 
matchNNegZExt_match1747   template <typename OpTy> bool match(OpTy *V) {
1748     if (auto *I = dyn_cast<ZExtInst>(V))
1749       return I->hasNonNeg() && Op.match(I->getOperand(0));
1750     return false;
1751   }
1752 };
1753 
1754 /// Matches BitCast.
1755 template <typename OpTy>
1756 inline CastOperator_match<OpTy, Instruction::BitCast>
m_BitCast(const OpTy & Op)1757 m_BitCast(const OpTy &Op) {
1758   return CastOperator_match<OpTy, Instruction::BitCast>(Op);
1759 }
1760 
1761 template <typename Op_t> struct ElementWiseBitCast_match {
1762   Op_t Op;
1763 
ElementWiseBitCast_matchElementWiseBitCast_match1764   ElementWiseBitCast_match(const Op_t &OpMatch) : Op(OpMatch) {}
1765 
matchElementWiseBitCast_match1766   template <typename OpTy> bool match(OpTy *V) {
1767     BitCastInst *I = dyn_cast<BitCastInst>(V);
1768     if (!I)
1769       return false;
1770     Type *SrcType = I->getSrcTy();
1771     Type *DstType = I->getType();
1772     // Make sure the bitcast doesn't change between scalar and vector and
1773     // doesn't change the number of vector elements.
1774     if (SrcType->isVectorTy() != DstType->isVectorTy())
1775       return false;
1776     if (VectorType *SrcVecTy = dyn_cast<VectorType>(SrcType);
1777         SrcVecTy && SrcVecTy->getElementCount() !=
1778                         cast<VectorType>(DstType)->getElementCount())
1779       return false;
1780     return Op.match(I->getOperand(0));
1781   }
1782 };
1783 
1784 template <typename OpTy>
m_ElementWiseBitCast(const OpTy & Op)1785 inline ElementWiseBitCast_match<OpTy> m_ElementWiseBitCast(const OpTy &Op) {
1786   return ElementWiseBitCast_match<OpTy>(Op);
1787 }
1788 
1789 /// Matches PtrToInt.
1790 template <typename OpTy>
1791 inline CastOperator_match<OpTy, Instruction::PtrToInt>
m_PtrToInt(const OpTy & Op)1792 m_PtrToInt(const OpTy &Op) {
1793   return CastOperator_match<OpTy, Instruction::PtrToInt>(Op);
1794 }
1795 
1796 template <typename OpTy>
m_PtrToIntSameSize(const DataLayout & DL,const OpTy & Op)1797 inline PtrToIntSameSize_match<OpTy> m_PtrToIntSameSize(const DataLayout &DL,
1798                                                        const OpTy &Op) {
1799   return PtrToIntSameSize_match<OpTy>(DL, Op);
1800 }
1801 
1802 /// Matches IntToPtr.
1803 template <typename OpTy>
1804 inline CastOperator_match<OpTy, Instruction::IntToPtr>
m_IntToPtr(const OpTy & Op)1805 m_IntToPtr(const OpTy &Op) {
1806   return CastOperator_match<OpTy, Instruction::IntToPtr>(Op);
1807 }
1808 
1809 /// Matches Trunc.
1810 template <typename OpTy>
m_Trunc(const OpTy & Op)1811 inline CastOperator_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) {
1812   return CastOperator_match<OpTy, Instruction::Trunc>(Op);
1813 }
1814 
1815 template <typename OpTy>
1816 inline match_combine_or<CastOperator_match<OpTy, Instruction::Trunc>, OpTy>
m_TruncOrSelf(const OpTy & Op)1817 m_TruncOrSelf(const OpTy &Op) {
1818   return m_CombineOr(m_Trunc(Op), Op);
1819 }
1820 
1821 /// Matches SExt.
1822 template <typename OpTy>
m_SExt(const OpTy & Op)1823 inline CastInst_match<OpTy, SExtInst> m_SExt(const OpTy &Op) {
1824   return CastInst_match<OpTy, SExtInst>(Op);
1825 }
1826 
1827 /// Matches ZExt.
1828 template <typename OpTy>
m_ZExt(const OpTy & Op)1829 inline CastInst_match<OpTy, ZExtInst> m_ZExt(const OpTy &Op) {
1830   return CastInst_match<OpTy, ZExtInst>(Op);
1831 }
1832 
1833 template <typename OpTy>
m_NNegZExt(const OpTy & Op)1834 inline NNegZExt_match<OpTy> m_NNegZExt(const OpTy &Op) {
1835   return NNegZExt_match<OpTy>(Op);
1836 }
1837 
1838 template <typename OpTy>
1839 inline match_combine_or<CastInst_match<OpTy, ZExtInst>, OpTy>
m_ZExtOrSelf(const OpTy & Op)1840 m_ZExtOrSelf(const OpTy &Op) {
1841   return m_CombineOr(m_ZExt(Op), Op);
1842 }
1843 
1844 template <typename OpTy>
1845 inline match_combine_or<CastInst_match<OpTy, SExtInst>, OpTy>
m_SExtOrSelf(const OpTy & Op)1846 m_SExtOrSelf(const OpTy &Op) {
1847   return m_CombineOr(m_SExt(Op), Op);
1848 }
1849 
1850 /// Match either "sext" or "zext nneg".
1851 template <typename OpTy>
1852 inline match_combine_or<CastInst_match<OpTy, SExtInst>, NNegZExt_match<OpTy>>
m_SExtLike(const OpTy & Op)1853 m_SExtLike(const OpTy &Op) {
1854   return m_CombineOr(m_SExt(Op), m_NNegZExt(Op));
1855 }
1856 
1857 template <typename OpTy>
1858 inline match_combine_or<CastInst_match<OpTy, ZExtInst>,
1859                         CastInst_match<OpTy, SExtInst>>
m_ZExtOrSExt(const OpTy & Op)1860 m_ZExtOrSExt(const OpTy &Op) {
1861   return m_CombineOr(m_ZExt(Op), m_SExt(Op));
1862 }
1863 
1864 template <typename OpTy>
1865 inline match_combine_or<match_combine_or<CastInst_match<OpTy, ZExtInst>,
1866                                          CastInst_match<OpTy, SExtInst>>,
1867                         OpTy>
m_ZExtOrSExtOrSelf(const OpTy & Op)1868 m_ZExtOrSExtOrSelf(const OpTy &Op) {
1869   return m_CombineOr(m_ZExtOrSExt(Op), Op);
1870 }
1871 
1872 template <typename OpTy>
m_UIToFP(const OpTy & Op)1873 inline CastInst_match<OpTy, UIToFPInst> m_UIToFP(const OpTy &Op) {
1874   return CastInst_match<OpTy, UIToFPInst>(Op);
1875 }
1876 
1877 template <typename OpTy>
m_SIToFP(const OpTy & Op)1878 inline CastInst_match<OpTy, SIToFPInst> m_SIToFP(const OpTy &Op) {
1879   return CastInst_match<OpTy, SIToFPInst>(Op);
1880 }
1881 
1882 template <typename OpTy>
m_FPToUI(const OpTy & Op)1883 inline CastInst_match<OpTy, FPToUIInst> m_FPToUI(const OpTy &Op) {
1884   return CastInst_match<OpTy, FPToUIInst>(Op);
1885 }
1886 
1887 template <typename OpTy>
m_FPToSI(const OpTy & Op)1888 inline CastInst_match<OpTy, FPToSIInst> m_FPToSI(const OpTy &Op) {
1889   return CastInst_match<OpTy, FPToSIInst>(Op);
1890 }
1891 
1892 template <typename OpTy>
m_FPTrunc(const OpTy & Op)1893 inline CastInst_match<OpTy, FPTruncInst> m_FPTrunc(const OpTy &Op) {
1894   return CastInst_match<OpTy, FPTruncInst>(Op);
1895 }
1896 
1897 template <typename OpTy>
m_FPExt(const OpTy & Op)1898 inline CastInst_match<OpTy, FPExtInst> m_FPExt(const OpTy &Op) {
1899   return CastInst_match<OpTy, FPExtInst>(Op);
1900 }
1901 
1902 //===----------------------------------------------------------------------===//
1903 // Matchers for control flow.
1904 //
1905 
1906 struct br_match {
1907   BasicBlock *&Succ;
1908 
br_matchbr_match1909   br_match(BasicBlock *&Succ) : Succ(Succ) {}
1910 
matchbr_match1911   template <typename OpTy> bool match(OpTy *V) {
1912     if (auto *BI = dyn_cast<BranchInst>(V))
1913       if (BI->isUnconditional()) {
1914         Succ = BI->getSuccessor(0);
1915         return true;
1916       }
1917     return false;
1918   }
1919 };
1920 
m_UnconditionalBr(BasicBlock * & Succ)1921 inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
1922 
1923 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1924 struct brc_match {
1925   Cond_t Cond;
1926   TrueBlock_t T;
1927   FalseBlock_t F;
1928 
brc_matchbrc_match1929   brc_match(const Cond_t &C, const TrueBlock_t &t, const FalseBlock_t &f)
1930       : Cond(C), T(t), F(f) {}
1931 
matchbrc_match1932   template <typename OpTy> bool match(OpTy *V) {
1933     if (auto *BI = dyn_cast<BranchInst>(V))
1934       if (BI->isConditional() && Cond.match(BI->getCondition()))
1935         return T.match(BI->getSuccessor(0)) && F.match(BI->getSuccessor(1));
1936     return false;
1937   }
1938 };
1939 
1940 template <typename Cond_t>
1941 inline brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>
m_Br(const Cond_t & C,BasicBlock * & T,BasicBlock * & F)1942 m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
1943   return brc_match<Cond_t, bind_ty<BasicBlock>, bind_ty<BasicBlock>>(
1944       C, m_BasicBlock(T), m_BasicBlock(F));
1945 }
1946 
1947 template <typename Cond_t, typename TrueBlock_t, typename FalseBlock_t>
1948 inline brc_match<Cond_t, TrueBlock_t, FalseBlock_t>
m_Br(const Cond_t & C,const TrueBlock_t & T,const FalseBlock_t & F)1949 m_Br(const Cond_t &C, const TrueBlock_t &T, const FalseBlock_t &F) {
1950   return brc_match<Cond_t, TrueBlock_t, FalseBlock_t>(C, T, F);
1951 }
1952 
1953 //===----------------------------------------------------------------------===//
1954 // Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
1955 //
1956 
1957 template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t,
1958           bool Commutable = false>
1959 struct MaxMin_match {
1960   using PredType = Pred_t;
1961   LHS_t L;
1962   RHS_t R;
1963 
1964   // The evaluation order is always stable, regardless of Commutability.
1965   // The LHS is always matched first.
MaxMin_matchMaxMin_match1966   MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1967 
matchMaxMin_match1968   template <typename OpTy> bool match(OpTy *V) {
1969     if (auto *II = dyn_cast<IntrinsicInst>(V)) {
1970       Intrinsic::ID IID = II->getIntrinsicID();
1971       if ((IID == Intrinsic::smax && Pred_t::match(ICmpInst::ICMP_SGT)) ||
1972           (IID == Intrinsic::smin && Pred_t::match(ICmpInst::ICMP_SLT)) ||
1973           (IID == Intrinsic::umax && Pred_t::match(ICmpInst::ICMP_UGT)) ||
1974           (IID == Intrinsic::umin && Pred_t::match(ICmpInst::ICMP_ULT))) {
1975         Value *LHS = II->getOperand(0), *RHS = II->getOperand(1);
1976         return (L.match(LHS) && R.match(RHS)) ||
1977                (Commutable && L.match(RHS) && R.match(LHS));
1978       }
1979     }
1980     // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1981     auto *SI = dyn_cast<SelectInst>(V);
1982     if (!SI)
1983       return false;
1984     auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1985     if (!Cmp)
1986       return false;
1987     // At this point we have a select conditioned on a comparison.  Check that
1988     // it is the values returned by the select that are being compared.
1989     auto *TrueVal = SI->getTrueValue();
1990     auto *FalseVal = SI->getFalseValue();
1991     auto *LHS = Cmp->getOperand(0);
1992     auto *RHS = Cmp->getOperand(1);
1993     if ((TrueVal != LHS || FalseVal != RHS) &&
1994         (TrueVal != RHS || FalseVal != LHS))
1995       return false;
1996     typename CmpInst_t::Predicate Pred =
1997         LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate();
1998     // Does "(x pred y) ? x : y" represent the desired max/min operation?
1999     if (!Pred_t::match(Pred))
2000       return false;
2001     // It does!  Bind the operands.
2002     return (L.match(LHS) && R.match(RHS)) ||
2003            (Commutable && L.match(RHS) && R.match(LHS));
2004   }
2005 };
2006 
2007 /// Helper class for identifying signed max predicates.
2008 struct smax_pred_ty {
matchsmax_pred_ty2009   static bool match(ICmpInst::Predicate Pred) {
2010     return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
2011   }
2012 };
2013 
2014 /// Helper class for identifying signed min predicates.
2015 struct smin_pred_ty {
matchsmin_pred_ty2016   static bool match(ICmpInst::Predicate Pred) {
2017     return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
2018   }
2019 };
2020 
2021 /// Helper class for identifying unsigned max predicates.
2022 struct umax_pred_ty {
matchumax_pred_ty2023   static bool match(ICmpInst::Predicate Pred) {
2024     return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
2025   }
2026 };
2027 
2028 /// Helper class for identifying unsigned min predicates.
2029 struct umin_pred_ty {
matchumin_pred_ty2030   static bool match(ICmpInst::Predicate Pred) {
2031     return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
2032   }
2033 };
2034 
2035 /// Helper class for identifying ordered max predicates.
2036 struct ofmax_pred_ty {
matchofmax_pred_ty2037   static bool match(FCmpInst::Predicate Pred) {
2038     return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
2039   }
2040 };
2041 
2042 /// Helper class for identifying ordered min predicates.
2043 struct ofmin_pred_ty {
matchofmin_pred_ty2044   static bool match(FCmpInst::Predicate Pred) {
2045     return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
2046   }
2047 };
2048 
2049 /// Helper class for identifying unordered max predicates.
2050 struct ufmax_pred_ty {
matchufmax_pred_ty2051   static bool match(FCmpInst::Predicate Pred) {
2052     return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
2053   }
2054 };
2055 
2056 /// Helper class for identifying unordered min predicates.
2057 struct ufmin_pred_ty {
matchufmin_pred_ty2058   static bool match(FCmpInst::Predicate Pred) {
2059     return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
2060   }
2061 };
2062 
2063 template <typename LHS, typename RHS>
m_SMax(const LHS & L,const RHS & R)2064 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
2065                                                              const RHS &R) {
2066   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
2067 }
2068 
2069 template <typename LHS, typename RHS>
m_SMin(const LHS & L,const RHS & R)2070 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
2071                                                              const RHS &R) {
2072   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
2073 }
2074 
2075 template <typename LHS, typename RHS>
m_UMax(const LHS & L,const RHS & R)2076 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
2077                                                              const RHS &R) {
2078   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
2079 }
2080 
2081 template <typename LHS, typename RHS>
m_UMin(const LHS & L,const RHS & R)2082 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
2083                                                              const RHS &R) {
2084   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
2085 }
2086 
2087 template <typename LHS, typename RHS>
2088 inline match_combine_or<
2089     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>,
2090                      MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>>,
2091     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>,
2092                      MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>>>
m_MaxOrMin(const LHS & L,const RHS & R)2093 m_MaxOrMin(const LHS &L, const RHS &R) {
2094   return m_CombineOr(m_CombineOr(m_SMax(L, R), m_SMin(L, R)),
2095                      m_CombineOr(m_UMax(L, R), m_UMin(L, R)));
2096 }
2097 
2098 /// Match an 'ordered' floating point maximum function.
2099 /// Floating point has one special value 'NaN'. Therefore, there is no total
2100 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2101 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
2102 /// semantics. In the presence of 'NaN' we have to preserve the original
2103 /// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
2104 ///
2105 ///                         max(L, R)  iff L and R are not NaN
2106 ///  m_OrdFMax(L, R) =      R          iff L or R are NaN
2107 template <typename LHS, typename RHS>
m_OrdFMax(const LHS & L,const RHS & R)2108 inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
2109                                                                  const RHS &R) {
2110   return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
2111 }
2112 
2113 /// Match an 'ordered' floating point minimum function.
2114 /// Floating point has one special value 'NaN'. Therefore, there is no total
2115 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2116 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
2117 /// semantics. In the presence of 'NaN' we have to preserve the original
2118 /// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
2119 ///
2120 ///                         min(L, R)  iff L and R are not NaN
2121 ///  m_OrdFMin(L, R) =      R          iff L or R are NaN
2122 template <typename LHS, typename RHS>
m_OrdFMin(const LHS & L,const RHS & R)2123 inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
2124                                                                  const RHS &R) {
2125   return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
2126 }
2127 
2128 /// Match an 'unordered' floating point maximum function.
2129 /// Floating point has one special value 'NaN'. Therefore, there is no total
2130 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2131 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
2132 /// semantics. In the presence of 'NaN' we have to preserve the original
2133 /// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
2134 ///
2135 ///                         max(L, R)  iff L and R are not NaN
2136 ///  m_UnordFMax(L, R) =    L          iff L or R are NaN
2137 template <typename LHS, typename RHS>
2138 inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
m_UnordFMax(const LHS & L,const RHS & R)2139 m_UnordFMax(const LHS &L, const RHS &R) {
2140   return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
2141 }
2142 
2143 /// Match an 'unordered' floating point minimum function.
2144 /// Floating point has one special value 'NaN'. Therefore, there is no total
2145 /// order. However, if we can ignore the 'NaN' value (for example, because of a
2146 /// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
2147 /// semantics. In the presence of 'NaN' we have to preserve the original
2148 /// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
2149 ///
2150 ///                          min(L, R)  iff L and R are not NaN
2151 ///  m_UnordFMin(L, R) =     L          iff L or R are NaN
2152 template <typename LHS, typename RHS>
2153 inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
m_UnordFMin(const LHS & L,const RHS & R)2154 m_UnordFMin(const LHS &L, const RHS &R) {
2155   return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
2156 }
2157 
2158 //===----------------------------------------------------------------------===//
2159 // Matchers for overflow check patterns: e.g. (a + b) u< a, (a ^ -1) <u b
2160 // Note that S might be matched to other instructions than AddInst.
2161 //
2162 
2163 template <typename LHS_t, typename RHS_t, typename Sum_t>
2164 struct UAddWithOverflow_match {
2165   LHS_t L;
2166   RHS_t R;
2167   Sum_t S;
2168 
UAddWithOverflow_matchUAddWithOverflow_match2169   UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
2170       : L(L), R(R), S(S) {}
2171 
matchUAddWithOverflow_match2172   template <typename OpTy> bool match(OpTy *V) {
2173     Value *ICmpLHS, *ICmpRHS;
2174     ICmpInst::Predicate Pred;
2175     if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
2176       return false;
2177 
2178     Value *AddLHS, *AddRHS;
2179     auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
2180 
2181     // (a + b) u< a, (a + b) u< b
2182     if (Pred == ICmpInst::ICMP_ULT)
2183       if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
2184         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
2185 
2186     // a >u (a + b), b >u (a + b)
2187     if (Pred == ICmpInst::ICMP_UGT)
2188       if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
2189         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
2190 
2191     Value *Op1;
2192     auto XorExpr = m_OneUse(m_Xor(m_Value(Op1), m_AllOnes()));
2193     // (a ^ -1) <u b
2194     if (Pred == ICmpInst::ICMP_ULT) {
2195       if (XorExpr.match(ICmpLHS))
2196         return L.match(Op1) && R.match(ICmpRHS) && S.match(ICmpLHS);
2197     }
2198     //  b > u (a ^ -1)
2199     if (Pred == ICmpInst::ICMP_UGT) {
2200       if (XorExpr.match(ICmpRHS))
2201         return L.match(Op1) && R.match(ICmpLHS) && S.match(ICmpRHS);
2202     }
2203 
2204     // Match special-case for increment-by-1.
2205     if (Pred == ICmpInst::ICMP_EQ) {
2206       // (a + 1) == 0
2207       // (1 + a) == 0
2208       if (AddExpr.match(ICmpLHS) && m_ZeroInt().match(ICmpRHS) &&
2209           (m_One().match(AddLHS) || m_One().match(AddRHS)))
2210         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
2211       // 0 == (a + 1)
2212       // 0 == (1 + a)
2213       if (m_ZeroInt().match(ICmpLHS) && AddExpr.match(ICmpRHS) &&
2214           (m_One().match(AddLHS) || m_One().match(AddRHS)))
2215         return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
2216     }
2217 
2218     return false;
2219   }
2220 };
2221 
2222 /// Match an icmp instruction checking for unsigned overflow on addition.
2223 ///
2224 /// S is matched to the addition whose result is being checked for overflow, and
2225 /// L and R are matched to the LHS and RHS of S.
2226 template <typename LHS_t, typename RHS_t, typename Sum_t>
2227 UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
m_UAddWithOverflow(const LHS_t & L,const RHS_t & R,const Sum_t & S)2228 m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
2229   return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
2230 }
2231 
2232 template <typename Opnd_t> struct Argument_match {
2233   unsigned OpI;
2234   Opnd_t Val;
2235 
Argument_matchArgument_match2236   Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
2237 
matchArgument_match2238   template <typename OpTy> bool match(OpTy *V) {
2239     // FIXME: Should likely be switched to use `CallBase`.
2240     if (const auto *CI = dyn_cast<CallInst>(V))
2241       return Val.match(CI->getArgOperand(OpI));
2242     return false;
2243   }
2244 };
2245 
2246 /// Match an argument.
2247 template <unsigned OpI, typename Opnd_t>
m_Argument(const Opnd_t & Op)2248 inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
2249   return Argument_match<Opnd_t>(OpI, Op);
2250 }
2251 
2252 /// Intrinsic matchers.
2253 struct IntrinsicID_match {
2254   unsigned ID;
2255 
IntrinsicID_matchIntrinsicID_match2256   IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
2257 
matchIntrinsicID_match2258   template <typename OpTy> bool match(OpTy *V) {
2259     if (const auto *CI = dyn_cast<CallInst>(V))
2260       if (const auto *F = CI->getCalledFunction())
2261         return F->getIntrinsicID() == ID;
2262     return false;
2263   }
2264 };
2265 
2266 /// Intrinsic matches are combinations of ID matchers, and argument
2267 /// matchers. Higher arity matcher are defined recursively in terms of and-ing
2268 /// them with lower arity matchers. Here's some convenient typedefs for up to
2269 /// several arguments, and more can be added as needed
2270 template <typename T0 = void, typename T1 = void, typename T2 = void,
2271           typename T3 = void, typename T4 = void, typename T5 = void,
2272           typename T6 = void, typename T7 = void, typename T8 = void,
2273           typename T9 = void, typename T10 = void>
2274 struct m_Intrinsic_Ty;
2275 template <typename T0> struct m_Intrinsic_Ty<T0> {
2276   using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
2277 };
2278 template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
2279   using Ty =
2280       match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
2281 };
2282 template <typename T0, typename T1, typename T2>
2283 struct m_Intrinsic_Ty<T0, T1, T2> {
2284   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
2285                                Argument_match<T2>>;
2286 };
2287 template <typename T0, typename T1, typename T2, typename T3>
2288 struct m_Intrinsic_Ty<T0, T1, T2, T3> {
2289   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
2290                                Argument_match<T3>>;
2291 };
2292 
2293 template <typename T0, typename T1, typename T2, typename T3, typename T4>
2294 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4> {
2295   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty,
2296                                Argument_match<T4>>;
2297 };
2298 
2299 template <typename T0, typename T1, typename T2, typename T3, typename T4,
2300           typename T5>
2301 struct m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5> {
2302   using Ty = match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty,
2303                                Argument_match<T5>>;
2304 };
2305 
2306 /// Match intrinsic calls like this:
2307 /// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
2308 template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
2309   return IntrinsicID_match(IntrID);
2310 }
2311 
2312 /// Matches MaskedLoad Intrinsic.
2313 template <typename Opnd0, typename Opnd1, typename Opnd2, typename Opnd3>
2314 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2, Opnd3>::Ty
2315 m_MaskedLoad(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2,
2316              const Opnd3 &Op3) {
2317   return m_Intrinsic<Intrinsic::masked_load>(Op0, Op1, Op2, Op3);
2318 }
2319 
2320 /// Matches MaskedGather Intrinsic.
2321 template <typename Opnd0, typename Opnd1, typename Opnd2, typename Opnd3>
2322 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2, Opnd3>::Ty
2323 m_MaskedGather(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2,
2324                const Opnd3 &Op3) {
2325   return m_Intrinsic<Intrinsic::masked_gather>(Op0, Op1, Op2, Op3);
2326 }
2327 
2328 template <Intrinsic::ID IntrID, typename T0>
2329 inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
2330   return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
2331 }
2332 
2333 template <Intrinsic::ID IntrID, typename T0, typename T1>
2334 inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
2335                                                        const T1 &Op1) {
2336   return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
2337 }
2338 
2339 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
2340 inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
2341 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
2342   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
2343 }
2344 
2345 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2346           typename T3>
2347 inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
2348 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
2349   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
2350 }
2351 
2352 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2353           typename T3, typename T4>
2354 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4>::Ty
2355 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2356             const T4 &Op4) {
2357   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3),
2358                       m_Argument<4>(Op4));
2359 }
2360 
2361 template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
2362           typename T3, typename T4, typename T5>
2363 inline typename m_Intrinsic_Ty<T0, T1, T2, T3, T4, T5>::Ty
2364 m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3,
2365             const T4 &Op4, const T5 &Op5) {
2366   return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2, Op3, Op4),
2367                       m_Argument<5>(Op5));
2368 }
2369 
2370 // Helper intrinsic matching specializations.
2371 template <typename Opnd0>
2372 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) {
2373   return m_Intrinsic<Intrinsic::bitreverse>(Op0);
2374 }
2375 
2376 template <typename Opnd0>
2377 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
2378   return m_Intrinsic<Intrinsic::bswap>(Op0);
2379 }
2380 
2381 template <typename Opnd0>
2382 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FAbs(const Opnd0 &Op0) {
2383   return m_Intrinsic<Intrinsic::fabs>(Op0);
2384 }
2385 
2386 template <typename Opnd0>
2387 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_FCanonicalize(const Opnd0 &Op0) {
2388   return m_Intrinsic<Intrinsic::canonicalize>(Op0);
2389 }
2390 
2391 template <typename Opnd0, typename Opnd1>
2392 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
2393                                                         const Opnd1 &Op1) {
2394   return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
2395 }
2396 
2397 template <typename Opnd0, typename Opnd1>
2398 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
2399                                                         const Opnd1 &Op1) {
2400   return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
2401 }
2402 
2403 template <typename Opnd0, typename Opnd1, typename Opnd2>
2404 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2405 m_FShl(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2406   return m_Intrinsic<Intrinsic::fshl>(Op0, Op1, Op2);
2407 }
2408 
2409 template <typename Opnd0, typename Opnd1, typename Opnd2>
2410 inline typename m_Intrinsic_Ty<Opnd0, Opnd1, Opnd2>::Ty
2411 m_FShr(const Opnd0 &Op0, const Opnd1 &Op1, const Opnd2 &Op2) {
2412   return m_Intrinsic<Intrinsic::fshr>(Op0, Op1, Op2);
2413 }
2414 
2415 template <typename Opnd0>
2416 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_Sqrt(const Opnd0 &Op0) {
2417   return m_Intrinsic<Intrinsic::sqrt>(Op0);
2418 }
2419 
2420 template <typename Opnd0, typename Opnd1>
2421 inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_CopySign(const Opnd0 &Op0,
2422                                                             const Opnd1 &Op1) {
2423   return m_Intrinsic<Intrinsic::copysign>(Op0, Op1);
2424 }
2425 
2426 template <typename Opnd0>
2427 inline typename m_Intrinsic_Ty<Opnd0>::Ty m_VecReverse(const Opnd0 &Op0) {
2428   return m_Intrinsic<Intrinsic::experimental_vector_reverse>(Op0);
2429 }
2430 
2431 //===----------------------------------------------------------------------===//
2432 // Matchers for two-operands operators with the operators in either order
2433 //
2434 
2435 /// Matches a BinaryOperator with LHS and RHS in either order.
2436 template <typename LHS, typename RHS>
2437 inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) {
2438   return AnyBinaryOp_match<LHS, RHS, true>(L, R);
2439 }
2440 
2441 /// Matches an ICmp with a predicate over LHS and RHS in either order.
2442 /// Swaps the predicate if operands are commuted.
2443 template <typename LHS, typename RHS>
2444 inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
2445 m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
2446   return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L,
2447                                                                        R);
2448 }
2449 
2450 /// Matches a specific opcode with LHS and RHS in either order.
2451 template <typename LHS, typename RHS>
2452 inline SpecificBinaryOp_match<LHS, RHS, true>
2453 m_c_BinOp(unsigned Opcode, const LHS &L, const RHS &R) {
2454   return SpecificBinaryOp_match<LHS, RHS, true>(Opcode, L, R);
2455 }
2456 
2457 /// Matches a Add with LHS and RHS in either order.
2458 template <typename LHS, typename RHS>
2459 inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L,
2460                                                                 const RHS &R) {
2461   return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R);
2462 }
2463 
2464 /// Matches a Mul with LHS and RHS in either order.
2465 template <typename LHS, typename RHS>
2466 inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L,
2467                                                                 const RHS &R) {
2468   return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R);
2469 }
2470 
2471 /// Matches an And with LHS and RHS in either order.
2472 template <typename LHS, typename RHS>
2473 inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L,
2474                                                                 const RHS &R) {
2475   return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R);
2476 }
2477 
2478 /// Matches an Or with LHS and RHS in either order.
2479 template <typename LHS, typename RHS>
2480 inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L,
2481                                                               const RHS &R) {
2482   return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R);
2483 }
2484 
2485 /// Matches an Xor with LHS and RHS in either order.
2486 template <typename LHS, typename RHS>
2487 inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L,
2488                                                                 const RHS &R) {
2489   return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R);
2490 }
2491 
2492 /// Matches a 'Neg' as 'sub 0, V'.
2493 template <typename ValTy>
2494 inline BinaryOp_match<cst_pred_ty<is_zero_int>, ValTy, Instruction::Sub>
2495 m_Neg(const ValTy &V) {
2496   return m_Sub(m_ZeroInt(), V);
2497 }
2498 
2499 /// Matches a 'Neg' as 'sub nsw 0, V'.
2500 template <typename ValTy>
2501 inline OverflowingBinaryOp_match<cst_pred_ty<is_zero_int>, ValTy,
2502                                  Instruction::Sub,
2503                                  OverflowingBinaryOperator::NoSignedWrap>
2504 m_NSWNeg(const ValTy &V) {
2505   return m_NSWSub(m_ZeroInt(), V);
2506 }
2507 
2508 /// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
2509 /// NOTE: we first match the 'Not' (by matching '-1'),
2510 /// and only then match the inner matcher!
2511 template <typename ValTy>
2512 inline BinaryOp_match<cst_pred_ty<is_all_ones>, ValTy, Instruction::Xor, true>
2513 m_Not(const ValTy &V) {
2514   return m_c_Xor(m_AllOnes(), V);
2515 }
2516 
2517 template <typename ValTy> struct NotForbidUndef_match {
2518   ValTy Val;
2519   NotForbidUndef_match(const ValTy &V) : Val(V) {}
2520 
2521   template <typename OpTy> bool match(OpTy *V) {
2522     // We do not use m_c_Xor because that could match an arbitrary APInt that is
2523     // not -1 as C and then fail to match the other operand if it is -1.
2524     // This code should still work even when both operands are constants.
2525     Value *X;
2526     const APInt *C;
2527     if (m_Xor(m_Value(X), m_APIntForbidUndef(C)).match(V) && C->isAllOnes())
2528       return Val.match(X);
2529     if (m_Xor(m_APIntForbidUndef(C), m_Value(X)).match(V) && C->isAllOnes())
2530       return Val.match(X);
2531     return false;
2532   }
2533 };
2534 
2535 /// Matches a bitwise 'not' as 'xor V, -1' or 'xor -1, V'. For vectors, the
2536 /// constant value must be composed of only -1 scalar elements.
2537 template <typename ValTy>
2538 inline NotForbidUndef_match<ValTy> m_NotForbidUndef(const ValTy &V) {
2539   return NotForbidUndef_match<ValTy>(V);
2540 }
2541 
2542 /// Matches an SMin with LHS and RHS in either order.
2543 template <typename LHS, typename RHS>
2544 inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>
2545 m_c_SMin(const LHS &L, const RHS &R) {
2546   return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R);
2547 }
2548 /// Matches an SMax with LHS and RHS in either order.
2549 template <typename LHS, typename RHS>
2550 inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>
2551 m_c_SMax(const LHS &L, const RHS &R) {
2552   return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R);
2553 }
2554 /// Matches a UMin with LHS and RHS in either order.
2555 template <typename LHS, typename RHS>
2556 inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>
2557 m_c_UMin(const LHS &L, const RHS &R) {
2558   return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R);
2559 }
2560 /// Matches a UMax with LHS and RHS in either order.
2561 template <typename LHS, typename RHS>
2562 inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>
2563 m_c_UMax(const LHS &L, const RHS &R) {
2564   return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R);
2565 }
2566 
2567 template <typename LHS, typename RHS>
2568 inline match_combine_or<
2569     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>,
2570                      MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>>,
2571     match_combine_or<MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>,
2572                      MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>>>
2573 m_c_MaxOrMin(const LHS &L, const RHS &R) {
2574   return m_CombineOr(m_CombineOr(m_c_SMax(L, R), m_c_SMin(L, R)),
2575                      m_CombineOr(m_c_UMax(L, R), m_c_UMin(L, R)));
2576 }
2577 
2578 template <Intrinsic::ID IntrID, typename T0, typename T1>
2579 inline match_combine_or<typename m_Intrinsic_Ty<T0, T1>::Ty,
2580                         typename m_Intrinsic_Ty<T1, T0>::Ty>
2581 m_c_Intrinsic(const T0 &Op0, const T1 &Op1) {
2582   return m_CombineOr(m_Intrinsic<IntrID>(Op0, Op1),
2583                      m_Intrinsic<IntrID>(Op1, Op0));
2584 }
2585 
2586 /// Matches FAdd with LHS and RHS in either order.
2587 template <typename LHS, typename RHS>
2588 inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true>
2589 m_c_FAdd(const LHS &L, const RHS &R) {
2590   return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R);
2591 }
2592 
2593 /// Matches FMul with LHS and RHS in either order.
2594 template <typename LHS, typename RHS>
2595 inline BinaryOp_match<LHS, RHS, Instruction::FMul, true>
2596 m_c_FMul(const LHS &L, const RHS &R) {
2597   return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R);
2598 }
2599 
2600 template <typename Opnd_t> struct Signum_match {
2601   Opnd_t Val;
2602   Signum_match(const Opnd_t &V) : Val(V) {}
2603 
2604   template <typename OpTy> bool match(OpTy *V) {
2605     unsigned TypeSize = V->getType()->getScalarSizeInBits();
2606     if (TypeSize == 0)
2607       return false;
2608 
2609     unsigned ShiftWidth = TypeSize - 1;
2610     Value *OpL = nullptr, *OpR = nullptr;
2611 
2612     // This is the representation of signum we match:
2613     //
2614     //  signum(x) == (x >> 63) | (-x >>u 63)
2615     //
2616     // An i1 value is its own signum, so it's correct to match
2617     //
2618     //  signum(x) == (x >> 0)  | (-x >>u 0)
2619     //
2620     // for i1 values.
2621 
2622     auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
2623     auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
2624     auto Signum = m_Or(LHS, RHS);
2625 
2626     return Signum.match(V) && OpL == OpR && Val.match(OpL);
2627   }
2628 };
2629 
2630 /// Matches a signum pattern.
2631 ///
2632 /// signum(x) =
2633 ///      x >  0  ->  1
2634 ///      x == 0  ->  0
2635 ///      x <  0  -> -1
2636 template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
2637   return Signum_match<Val_t>(V);
2638 }
2639 
2640 template <int Ind, typename Opnd_t> struct ExtractValue_match {
2641   Opnd_t Val;
2642   ExtractValue_match(const Opnd_t &V) : Val(V) {}
2643 
2644   template <typename OpTy> bool match(OpTy *V) {
2645     if (auto *I = dyn_cast<ExtractValueInst>(V)) {
2646       // If Ind is -1, don't inspect indices
2647       if (Ind != -1 &&
2648           !(I->getNumIndices() == 1 && I->getIndices()[0] == (unsigned)Ind))
2649         return false;
2650       return Val.match(I->getAggregateOperand());
2651     }
2652     return false;
2653   }
2654 };
2655 
2656 /// Match a single index ExtractValue instruction.
2657 /// For example m_ExtractValue<1>(...)
2658 template <int Ind, typename Val_t>
2659 inline ExtractValue_match<Ind, Val_t> m_ExtractValue(const Val_t &V) {
2660   return ExtractValue_match<Ind, Val_t>(V);
2661 }
2662 
2663 /// Match an ExtractValue instruction with any index.
2664 /// For example m_ExtractValue(...)
2665 template <typename Val_t>
2666 inline ExtractValue_match<-1, Val_t> m_ExtractValue(const Val_t &V) {
2667   return ExtractValue_match<-1, Val_t>(V);
2668 }
2669 
2670 /// Matcher for a single index InsertValue instruction.
2671 template <int Ind, typename T0, typename T1> struct InsertValue_match {
2672   T0 Op0;
2673   T1 Op1;
2674 
2675   InsertValue_match(const T0 &Op0, const T1 &Op1) : Op0(Op0), Op1(Op1) {}
2676 
2677   template <typename OpTy> bool match(OpTy *V) {
2678     if (auto *I = dyn_cast<InsertValueInst>(V)) {
2679       return Op0.match(I->getOperand(0)) && Op1.match(I->getOperand(1)) &&
2680              I->getNumIndices() == 1 && Ind == I->getIndices()[0];
2681     }
2682     return false;
2683   }
2684 };
2685 
2686 /// Matches a single index InsertValue instruction.
2687 template <int Ind, typename Val_t, typename Elt_t>
2688 inline InsertValue_match<Ind, Val_t, Elt_t> m_InsertValue(const Val_t &Val,
2689                                                           const Elt_t &Elt) {
2690   return InsertValue_match<Ind, Val_t, Elt_t>(Val, Elt);
2691 }
2692 
2693 /// Matches patterns for `vscale`. This can either be a call to `llvm.vscale` or
2694 /// the constant expression
2695 ///  `ptrtoint(gep <vscale x 1 x i8>, <vscale x 1 x i8>* null, i32 1>`
2696 /// under the right conditions determined by DataLayout.
2697 struct VScaleVal_match {
2698   template <typename ITy> bool match(ITy *V) {
2699     if (m_Intrinsic<Intrinsic::vscale>().match(V))
2700       return true;
2701 
2702     Value *Ptr;
2703     if (m_PtrToInt(m_Value(Ptr)).match(V)) {
2704       if (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
2705         auto *DerefTy =
2706             dyn_cast<ScalableVectorType>(GEP->getSourceElementType());
2707         if (GEP->getNumIndices() == 1 && DerefTy &&
2708             DerefTy->getElementType()->isIntegerTy(8) &&
2709             m_Zero().match(GEP->getPointerOperand()) &&
2710             m_SpecificInt(1).match(GEP->idx_begin()->get()))
2711           return true;
2712       }
2713     }
2714 
2715     return false;
2716   }
2717 };
2718 
2719 inline VScaleVal_match m_VScale() {
2720   return VScaleVal_match();
2721 }
2722 
2723 template <typename LHS, typename RHS, unsigned Opcode, bool Commutable = false>
2724 struct LogicalOp_match {
2725   LHS L;
2726   RHS R;
2727 
2728   LogicalOp_match(const LHS &L, const RHS &R) : L(L), R(R) {}
2729 
2730   template <typename T> bool match(T *V) {
2731     auto *I = dyn_cast<Instruction>(V);
2732     if (!I || !I->getType()->isIntOrIntVectorTy(1))
2733       return false;
2734 
2735     if (I->getOpcode() == Opcode) {
2736       auto *Op0 = I->getOperand(0);
2737       auto *Op1 = I->getOperand(1);
2738       return (L.match(Op0) && R.match(Op1)) ||
2739              (Commutable && L.match(Op1) && R.match(Op0));
2740     }
2741 
2742     if (auto *Select = dyn_cast<SelectInst>(I)) {
2743       auto *Cond = Select->getCondition();
2744       auto *TVal = Select->getTrueValue();
2745       auto *FVal = Select->getFalseValue();
2746 
2747       // Don't match a scalar select of bool vectors.
2748       // Transforms expect a single type for operands if this matches.
2749       if (Cond->getType() != Select->getType())
2750         return false;
2751 
2752       if (Opcode == Instruction::And) {
2753         auto *C = dyn_cast<Constant>(FVal);
2754         if (C && C->isNullValue())
2755           return (L.match(Cond) && R.match(TVal)) ||
2756                  (Commutable && L.match(TVal) && R.match(Cond));
2757       } else {
2758         assert(Opcode == Instruction::Or);
2759         auto *C = dyn_cast<Constant>(TVal);
2760         if (C && C->isOneValue())
2761           return (L.match(Cond) && R.match(FVal)) ||
2762                  (Commutable && L.match(FVal) && R.match(Cond));
2763       }
2764     }
2765 
2766     return false;
2767   }
2768 };
2769 
2770 /// Matches L && R either in the form of L & R or L ? R : false.
2771 /// Note that the latter form is poison-blocking.
2772 template <typename LHS, typename RHS>
2773 inline LogicalOp_match<LHS, RHS, Instruction::And> m_LogicalAnd(const LHS &L,
2774                                                                 const RHS &R) {
2775   return LogicalOp_match<LHS, RHS, Instruction::And>(L, R);
2776 }
2777 
2778 /// Matches L && R where L and R are arbitrary values.
2779 inline auto m_LogicalAnd() { return m_LogicalAnd(m_Value(), m_Value()); }
2780 
2781 /// Matches L && R with LHS and RHS in either order.
2782 template <typename LHS, typename RHS>
2783 inline LogicalOp_match<LHS, RHS, Instruction::And, true>
2784 m_c_LogicalAnd(const LHS &L, const RHS &R) {
2785   return LogicalOp_match<LHS, RHS, Instruction::And, true>(L, R);
2786 }
2787 
2788 /// Matches L || R either in the form of L | R or L ? true : R.
2789 /// Note that the latter form is poison-blocking.
2790 template <typename LHS, typename RHS>
2791 inline LogicalOp_match<LHS, RHS, Instruction::Or> m_LogicalOr(const LHS &L,
2792                                                               const RHS &R) {
2793   return LogicalOp_match<LHS, RHS, Instruction::Or>(L, R);
2794 }
2795 
2796 /// Matches L || R where L and R are arbitrary values.
2797 inline auto m_LogicalOr() { return m_LogicalOr(m_Value(), m_Value()); }
2798 
2799 /// Matches L || R with LHS and RHS in either order.
2800 template <typename LHS, typename RHS>
2801 inline LogicalOp_match<LHS, RHS, Instruction::Or, true>
2802 m_c_LogicalOr(const LHS &L, const RHS &R) {
2803   return LogicalOp_match<LHS, RHS, Instruction::Or, true>(L, R);
2804 }
2805 
2806 /// Matches either L && R or L || R,
2807 /// either one being in the either binary or logical form.
2808 /// Note that the latter form is poison-blocking.
2809 template <typename LHS, typename RHS, bool Commutable = false>
2810 inline auto m_LogicalOp(const LHS &L, const RHS &R) {
2811   return m_CombineOr(
2812       LogicalOp_match<LHS, RHS, Instruction::And, Commutable>(L, R),
2813       LogicalOp_match<LHS, RHS, Instruction::Or, Commutable>(L, R));
2814 }
2815 
2816 /// Matches either L && R or L || R where L and R are arbitrary values.
2817 inline auto m_LogicalOp() { return m_LogicalOp(m_Value(), m_Value()); }
2818 
2819 /// Matches either L && R or L || R with LHS and RHS in either order.
2820 template <typename LHS, typename RHS>
2821 inline auto m_c_LogicalOp(const LHS &L, const RHS &R) {
2822   return m_LogicalOp<LHS, RHS, /*Commutable=*/true>(L, R);
2823 }
2824 
2825 } // end namespace PatternMatch
2826 } // end namespace llvm
2827 
2828 #endif // LLVM_IR_PATTERNMATCH_H
2829