blob: 304b84bc85d2a0da96279f1f3ff73a9164295d7d [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- PatternMatch.h - Match on the LLVM IR --------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides a simple and efficient mechanism for performing general
11// tree-based pattern matches on the LLVM IR. The power of these routines is
12// that it allows you to write concise patterns that are expressive and easy to
13// understand. The other major advantage of this is that it allows you to
14// trivially capture/bind elements in the pattern to variables. For example,
15// you can do something like this:
16//
17// Value *Exp = ...
18// Value *X, *Y; ConstantInt *C1, *C2; // (X & C1) | (Y & C2)
19// if (match(Exp, m_Or(m_And(m_Value(X), m_ConstantInt(C1)),
20// m_And(m_Value(Y), m_ConstantInt(C2))))) {
21// ... Pattern is matched and variables are bound ...
22// }
23//
24// This is primarily useful to things like the instruction combiner, but can
25// also be useful for static analysis tools or code generators.
26//
27//===----------------------------------------------------------------------===//
28
29#ifndef LLVM_IR_PATTERNMATCH_H
30#define LLVM_IR_PATTERNMATCH_H
31
32#include "llvm/ADT/APFloat.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/IR/CallSite.h"
35#include "llvm/IR/Constant.h"
36#include "llvm/IR/Constants.h"
37#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
39#include "llvm/IR/Instructions.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
46namespace llvm {
47namespace PatternMatch {
48
49template <typename Val, typename Pattern> bool match(Val *V, const Pattern &P) {
50 return const_cast<Pattern &>(P).match(V);
51}
52
53template <typename SubPattern_t> struct OneUse_match {
54 SubPattern_t SubPattern;
55
56 OneUse_match(const SubPattern_t &SP) : SubPattern(SP) {}
57
58 template <typename OpTy> bool match(OpTy *V) {
59 return V->hasOneUse() && SubPattern.match(V);
60 }
61};
62
63template <typename T> inline OneUse_match<T> m_OneUse(const T &SubPattern) {
64 return SubPattern;
65}
66
67template <typename Class> struct class_match {
68 template <typename ITy> bool match(ITy *V) { return isa<Class>(V); }
69};
70
71/// Match an arbitrary value and ignore it.
72inline class_match<Value> m_Value() { return class_match<Value>(); }
73
74/// Match an arbitrary binary operation and ignore it.
75inline class_match<BinaryOperator> m_BinOp() {
76 return class_match<BinaryOperator>();
77}
78
79/// Matches any compare instruction and ignore it.
80inline class_match<CmpInst> m_Cmp() { return class_match<CmpInst>(); }
81
82/// Match an arbitrary ConstantInt and ignore it.
83inline class_match<ConstantInt> m_ConstantInt() {
84 return class_match<ConstantInt>();
85}
86
87/// Match an arbitrary undef constant.
88inline class_match<UndefValue> m_Undef() { return class_match<UndefValue>(); }
89
90/// Match an arbitrary Constant and ignore it.
91inline class_match<Constant> m_Constant() { return class_match<Constant>(); }
92
93/// Matching combinators
94template <typename LTy, typename RTy> struct match_combine_or {
95 LTy L;
96 RTy R;
97
98 match_combine_or(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
99
100 template <typename ITy> bool match(ITy *V) {
101 if (L.match(V))
102 return true;
103 if (R.match(V))
104 return true;
105 return false;
106 }
107};
108
109template <typename LTy, typename RTy> struct match_combine_and {
110 LTy L;
111 RTy R;
112
113 match_combine_and(const LTy &Left, const RTy &Right) : L(Left), R(Right) {}
114
115 template <typename ITy> bool match(ITy *V) {
116 if (L.match(V))
117 if (R.match(V))
118 return true;
119 return false;
120 }
121};
122
123/// Combine two pattern matchers matching L || R
124template <typename LTy, typename RTy>
125inline match_combine_or<LTy, RTy> m_CombineOr(const LTy &L, const RTy &R) {
126 return match_combine_or<LTy, RTy>(L, R);
127}
128
129/// Combine two pattern matchers matching L && R
130template <typename LTy, typename RTy>
131inline match_combine_and<LTy, RTy> m_CombineAnd(const LTy &L, const RTy &R) {
132 return match_combine_and<LTy, RTy>(L, R);
133}
134
135struct match_zero {
136 template <typename ITy> bool match(ITy *V) {
137 if (const auto *C = dyn_cast<Constant>(V))
138 return C->isNullValue();
139 return false;
140 }
141};
142
143/// Match an arbitrary zero/null constant. This includes
144/// zero_initializer for vectors and ConstantPointerNull for pointers.
145inline match_zero m_Zero() { return match_zero(); }
146
147struct apint_match {
148 const APInt *&Res;
149
150 apint_match(const APInt *&R) : Res(R) {}
151
152 template <typename ITy> bool match(ITy *V) {
153 if (auto *CI = dyn_cast<ConstantInt>(V)) {
154 Res = &CI->getValue();
155 return true;
156 }
157 if (V->getType()->isVectorTy())
158 if (const auto *C = dyn_cast<Constant>(V))
159 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue())) {
160 Res = &CI->getValue();
161 return true;
162 }
163 return false;
164 }
165};
166// Either constexpr if or renaming ConstantFP::getValueAPF to
167// ConstantFP::getValue is needed to do it via single template
168// function for both apint/apfloat.
169struct apfloat_match {
170 const APFloat *&Res;
171 apfloat_match(const APFloat *&R) : Res(R) {}
172 template <typename ITy> bool match(ITy *V) {
173 if (auto *CI = dyn_cast<ConstantFP>(V)) {
174 Res = &CI->getValueAPF();
175 return true;
176 }
177 if (V->getType()->isVectorTy())
178 if (const auto *C = dyn_cast<Constant>(V))
179 if (auto *CI = dyn_cast_or_null<ConstantFP>(C->getSplatValue())) {
180 Res = &CI->getValueAPF();
181 return true;
182 }
183 return false;
184 }
185};
186
187/// Match a ConstantInt or splatted ConstantVector, binding the
188/// specified pointer to the contained APInt.
189inline apint_match m_APInt(const APInt *&Res) { return Res; }
190
191/// Match a ConstantFP or splatted ConstantVector, binding the
192/// specified pointer to the contained APFloat.
193inline apfloat_match m_APFloat(const APFloat *&Res) { return Res; }
194
195template <int64_t Val> struct constantint_match {
196 template <typename ITy> bool match(ITy *V) {
197 if (const auto *CI = dyn_cast<ConstantInt>(V)) {
198 const APInt &CIV = CI->getValue();
199 if (Val >= 0)
200 return CIV == static_cast<uint64_t>(Val);
201 // If Val is negative, and CI is shorter than it, truncate to the right
202 // number of bits. If it is larger, then we have to sign extend. Just
203 // compare their negated values.
204 return -CIV == -Val;
205 }
206 return false;
207 }
208};
209
210/// Match a ConstantInt with a specific value.
211template <int64_t Val> inline constantint_match<Val> m_ConstantInt() {
212 return constantint_match<Val>();
213}
214
215/// This helper class is used to match scalar and vector integer constants that
216/// satisfy a specified predicate.
217/// For vector constants, undefined elements are ignored.
218template <typename Predicate> struct cst_pred_ty : public Predicate {
219 template <typename ITy> bool match(ITy *V) {
220 if (const auto *CI = dyn_cast<ConstantInt>(V))
221 return this->isValue(CI->getValue());
222 if (V->getType()->isVectorTy()) {
223 if (const auto *C = dyn_cast<Constant>(V)) {
224 if (const auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
225 return this->isValue(CI->getValue());
226
227 // Non-splat vector constant: check each element for a match.
228 unsigned NumElts = V->getType()->getVectorNumElements();
229 assert(NumElts != 0 && "Constant vector with no elements?");
230 for (unsigned i = 0; i != NumElts; ++i) {
231 Constant *Elt = C->getAggregateElement(i);
232 if (!Elt)
233 return false;
234 if (isa<UndefValue>(Elt))
235 continue;
236 auto *CI = dyn_cast<ConstantInt>(Elt);
237 if (!CI || !this->isValue(CI->getValue()))
238 return false;
239 }
240 return true;
241 }
242 }
243 return false;
244 }
245};
246
247/// This helper class is used to match scalar and vector constants that
248/// satisfy a specified predicate, and bind them to an APInt.
249template <typename Predicate> struct api_pred_ty : public Predicate {
250 const APInt *&Res;
251
252 api_pred_ty(const APInt *&R) : Res(R) {}
253
254 template <typename ITy> bool match(ITy *V) {
255 if (const auto *CI = dyn_cast<ConstantInt>(V))
256 if (this->isValue(CI->getValue())) {
257 Res = &CI->getValue();
258 return true;
259 }
260 if (V->getType()->isVectorTy())
261 if (const auto *C = dyn_cast<Constant>(V))
262 if (auto *CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue()))
263 if (this->isValue(CI->getValue())) {
264 Res = &CI->getValue();
265 return true;
266 }
267
268 return false;
269 }
270};
271
272/// This helper class is used to match scalar and vector floating-point
273/// constants that satisfy a specified predicate.
274/// For vector constants, undefined elements are ignored.
275template <typename Predicate> struct cstfp_pred_ty : public Predicate {
276 template <typename ITy> bool match(ITy *V) {
277 if (const auto *CF = dyn_cast<ConstantFP>(V))
278 return this->isValue(CF->getValueAPF());
279 if (V->getType()->isVectorTy()) {
280 if (const auto *C = dyn_cast<Constant>(V)) {
281 if (const auto *CF = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
282 return this->isValue(CF->getValueAPF());
283
284 // Non-splat vector constant: check each element for a match.
285 unsigned NumElts = V->getType()->getVectorNumElements();
286 assert(NumElts != 0 && "Constant vector with no elements?");
287 for (unsigned i = 0; i != NumElts; ++i) {
288 Constant *Elt = C->getAggregateElement(i);
289 if (!Elt)
290 return false;
291 if (isa<UndefValue>(Elt))
292 continue;
293 auto *CF = dyn_cast<ConstantFP>(Elt);
294 if (!CF || !this->isValue(CF->getValueAPF()))
295 return false;
296 }
297 return true;
298 }
299 }
300 return false;
301 }
302};
303
304///////////////////////////////////////////////////////////////////////////////
305//
306// Encapsulate constant value queries for use in templated predicate matchers.
307// This allows checking if constants match using compound predicates and works
308// with vector constants, possibly with relaxed constraints. For example, ignore
309// undef values.
310//
311///////////////////////////////////////////////////////////////////////////////
312
313struct is_all_ones {
314 bool isValue(const APInt &C) { return C.isAllOnesValue(); }
315};
316/// Match an integer or vector with all bits set.
317/// For vectors, this includes constants with undefined elements.
318inline cst_pred_ty<is_all_ones> m_AllOnes() {
319 return cst_pred_ty<is_all_ones>();
320}
321
322struct is_maxsignedvalue {
323 bool isValue(const APInt &C) { return C.isMaxSignedValue(); }
324};
325/// Match an integer or vector with values having all bits except for the high
326/// bit set (0x7f...).
327/// For vectors, this includes constants with undefined elements.
328inline cst_pred_ty<is_maxsignedvalue> m_MaxSignedValue() {
329 return cst_pred_ty<is_maxsignedvalue>();
330}
331inline api_pred_ty<is_maxsignedvalue> m_MaxSignedValue(const APInt *&V) {
332 return V;
333}
334
335struct is_negative {
336 bool isValue(const APInt &C) { return C.isNegative(); }
337};
338/// Match an integer or vector of negative values.
339/// For vectors, this includes constants with undefined elements.
340inline cst_pred_ty<is_negative> m_Negative() {
341 return cst_pred_ty<is_negative>();
342}
343inline api_pred_ty<is_negative> m_Negative(const APInt *&V) {
344 return V;
345}
346
347struct is_nonnegative {
348 bool isValue(const APInt &C) { return C.isNonNegative(); }
349};
350/// Match an integer or vector of nonnegative values.
351/// For vectors, this includes constants with undefined elements.
352inline cst_pred_ty<is_nonnegative> m_NonNegative() {
353 return cst_pred_ty<is_nonnegative>();
354}
355inline api_pred_ty<is_nonnegative> m_NonNegative(const APInt *&V) {
356 return V;
357}
358
359struct is_one {
360 bool isValue(const APInt &C) { return C.isOneValue(); }
361};
362/// Match an integer 1 or a vector with all elements equal to 1.
363/// For vectors, this includes constants with undefined elements.
364inline cst_pred_ty<is_one> m_One() {
365 return cst_pred_ty<is_one>();
366}
367
368struct is_power2 {
369 bool isValue(const APInt &C) { return C.isPowerOf2(); }
370};
371/// Match an integer or vector power-of-2.
372/// For vectors, this includes constants with undefined elements.
373inline cst_pred_ty<is_power2> m_Power2() {
374 return cst_pred_ty<is_power2>();
375}
376inline api_pred_ty<is_power2> m_Power2(const APInt *&V) {
377 return V;
378}
379
380struct is_power2_or_zero {
381 bool isValue(const APInt &C) { return !C || C.isPowerOf2(); }
382};
383/// Match an integer or vector of 0 or power-of-2 values.
384/// For vectors, this includes constants with undefined elements.
385inline cst_pred_ty<is_power2_or_zero> m_Power2OrZero() {
386 return cst_pred_ty<is_power2_or_zero>();
387}
388inline api_pred_ty<is_power2_or_zero> m_Power2OrZero(const APInt *&V) {
389 return V;
390}
391
392struct is_sign_mask {
393 bool isValue(const APInt &C) { return C.isSignMask(); }
394};
395/// Match an integer or vector with only the sign bit(s) set.
396/// For vectors, this includes constants with undefined elements.
397inline cst_pred_ty<is_sign_mask> m_SignMask() {
398 return cst_pred_ty<is_sign_mask>();
399}
400
401struct is_nan {
402 bool isValue(const APFloat &C) { return C.isNaN(); }
403};
404/// Match an arbitrary NaN constant. This includes quiet and signalling nans.
405/// For vectors, this includes constants with undefined elements.
406inline cstfp_pred_ty<is_nan> m_NaN() {
407 return cstfp_pred_ty<is_nan>();
408}
409
410struct is_any_zero_fp {
411 bool isValue(const APFloat &C) { return C.isZero(); }
412};
413/// Match a floating-point negative zero or positive zero.
414/// For vectors, this includes constants with undefined elements.
415inline cstfp_pred_ty<is_any_zero_fp> m_AnyZeroFP() {
416 return cstfp_pred_ty<is_any_zero_fp>();
417}
418
419struct is_pos_zero_fp {
420 bool isValue(const APFloat &C) { return C.isPosZero(); }
421};
422/// Match a floating-point positive zero.
423/// For vectors, this includes constants with undefined elements.
424inline cstfp_pred_ty<is_pos_zero_fp> m_PosZeroFP() {
425 return cstfp_pred_ty<is_pos_zero_fp>();
426}
427
428struct is_neg_zero_fp {
429 bool isValue(const APFloat &C) { return C.isNegZero(); }
430};
431/// Match a floating-point negative zero.
432/// For vectors, this includes constants with undefined elements.
433inline cstfp_pred_ty<is_neg_zero_fp> m_NegZeroFP() {
434 return cstfp_pred_ty<is_neg_zero_fp>();
435}
436
437///////////////////////////////////////////////////////////////////////////////
438
439template <typename Class> struct bind_ty {
440 Class *&VR;
441
442 bind_ty(Class *&V) : VR(V) {}
443
444 template <typename ITy> bool match(ITy *V) {
445 if (auto *CV = dyn_cast<Class>(V)) {
446 VR = CV;
447 return true;
448 }
449 return false;
450 }
451};
452
453/// Match a value, capturing it if we match.
454inline bind_ty<Value> m_Value(Value *&V) { return V; }
455inline bind_ty<const Value> m_Value(const Value *&V) { return V; }
456
457/// Match an instruction, capturing it if we match.
458inline bind_ty<Instruction> m_Instruction(Instruction *&I) { return I; }
459/// Match a binary operator, capturing it if we match.
460inline bind_ty<BinaryOperator> m_BinOp(BinaryOperator *&I) { return I; }
461
462/// Match a ConstantInt, capturing the value if we match.
463inline bind_ty<ConstantInt> m_ConstantInt(ConstantInt *&CI) { return CI; }
464
465/// Match a Constant, capturing the value if we match.
466inline bind_ty<Constant> m_Constant(Constant *&C) { return C; }
467
468/// Match a ConstantFP, capturing the value if we match.
469inline bind_ty<ConstantFP> m_ConstantFP(ConstantFP *&C) { return C; }
470
471/// Match a specified Value*.
472struct specificval_ty {
473 const Value *Val;
474
475 specificval_ty(const Value *V) : Val(V) {}
476
477 template <typename ITy> bool match(ITy *V) { return V == Val; }
478};
479
480/// Match if we have a specific specified value.
481inline specificval_ty m_Specific(const Value *V) { return V; }
482
483/// Match a specified floating point value or vector of all elements of
484/// that value.
485struct specific_fpval {
486 double Val;
487
488 specific_fpval(double V) : Val(V) {}
489
490 template <typename ITy> bool match(ITy *V) {
491 if (const auto *CFP = dyn_cast<ConstantFP>(V))
492 return CFP->isExactlyValue(Val);
493 if (V->getType()->isVectorTy())
494 if (const auto *C = dyn_cast<Constant>(V))
495 if (auto *CFP = dyn_cast_or_null<ConstantFP>(C->getSplatValue()))
496 return CFP->isExactlyValue(Val);
497 return false;
498 }
499};
500
501/// Match a specific floating point value or vector with all elements
502/// equal to the value.
503inline specific_fpval m_SpecificFP(double V) { return specific_fpval(V); }
504
505/// Match a float 1.0 or vector with all elements equal to 1.0.
506inline specific_fpval m_FPOne() { return m_SpecificFP(1.0); }
507
508struct bind_const_intval_ty {
509 uint64_t &VR;
510
511 bind_const_intval_ty(uint64_t &V) : VR(V) {}
512
513 template <typename ITy> bool match(ITy *V) {
514 if (const auto *CV = dyn_cast<ConstantInt>(V))
515 if (CV->getValue().ule(UINT64_MAX)) {
516 VR = CV->getZExtValue();
517 return true;
518 }
519 return false;
520 }
521};
522
523/// Match a specified integer value or vector of all elements of that
524// value.
525struct specific_intval {
526 uint64_t Val;
527
528 specific_intval(uint64_t V) : Val(V) {}
529
530 template <typename ITy> bool match(ITy *V) {
531 const auto *CI = dyn_cast<ConstantInt>(V);
532 if (!CI && V->getType()->isVectorTy())
533 if (const auto *C = dyn_cast<Constant>(V))
534 CI = dyn_cast_or_null<ConstantInt>(C->getSplatValue());
535
536 return CI && CI->getValue() == Val;
537 }
538};
539
540/// Match a specific integer value or vector with all elements equal to
541/// the value.
542inline specific_intval m_SpecificInt(uint64_t V) { return specific_intval(V); }
543
544/// Match a ConstantInt and bind to its value. This does not match
545/// ConstantInts wider than 64-bits.
546inline bind_const_intval_ty m_ConstantInt(uint64_t &V) { return V; }
547
548//===----------------------------------------------------------------------===//
549// Matcher for any binary operator.
550//
551template <typename LHS_t, typename RHS_t, bool Commutable = false>
552struct AnyBinaryOp_match {
553 LHS_t L;
554 RHS_t R;
555
556 AnyBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
557
558 template <typename OpTy> bool match(OpTy *V) {
559 if (auto *I = dyn_cast<BinaryOperator>(V))
560 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
561 (Commutable && R.match(I->getOperand(0)) &&
562 L.match(I->getOperand(1)));
563 return false;
564 }
565};
566
567template <typename LHS, typename RHS>
568inline AnyBinaryOp_match<LHS, RHS> m_BinOp(const LHS &L, const RHS &R) {
569 return AnyBinaryOp_match<LHS, RHS>(L, R);
570}
571
572//===----------------------------------------------------------------------===//
573// Matchers for specific binary operators.
574//
575
576template <typename LHS_t, typename RHS_t, unsigned Opcode,
577 bool Commutable = false>
578struct BinaryOp_match {
579 LHS_t L;
580 RHS_t R;
581
582 BinaryOp_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
583
584 template <typename OpTy> bool match(OpTy *V) {
585 if (V->getValueID() == Value::InstructionVal + Opcode) {
586 auto *I = cast<BinaryOperator>(V);
587 return (L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
588 (Commutable && R.match(I->getOperand(0)) &&
589 L.match(I->getOperand(1)));
590 }
591 if (auto *CE = dyn_cast<ConstantExpr>(V))
592 return CE->getOpcode() == Opcode &&
593 ((L.match(CE->getOperand(0)) && R.match(CE->getOperand(1))) ||
594 (Commutable && R.match(CE->getOperand(0)) &&
595 L.match(CE->getOperand(1))));
596 return false;
597 }
598};
599
600template <typename LHS, typename RHS>
601inline BinaryOp_match<LHS, RHS, Instruction::Add> m_Add(const LHS &L,
602 const RHS &R) {
603 return BinaryOp_match<LHS, RHS, Instruction::Add>(L, R);
604}
605
606template <typename LHS, typename RHS>
607inline BinaryOp_match<LHS, RHS, Instruction::FAdd> m_FAdd(const LHS &L,
608 const RHS &R) {
609 return BinaryOp_match<LHS, RHS, Instruction::FAdd>(L, R);
610}
611
612template <typename LHS, typename RHS>
613inline BinaryOp_match<LHS, RHS, Instruction::Sub> m_Sub(const LHS &L,
614 const RHS &R) {
615 return BinaryOp_match<LHS, RHS, Instruction::Sub>(L, R);
616}
617
618template <typename LHS, typename RHS>
619inline BinaryOp_match<LHS, RHS, Instruction::FSub> m_FSub(const LHS &L,
620 const RHS &R) {
621 return BinaryOp_match<LHS, RHS, Instruction::FSub>(L, R);
622}
623
624template <typename LHS, typename RHS>
625inline BinaryOp_match<LHS, RHS, Instruction::Mul> m_Mul(const LHS &L,
626 const RHS &R) {
627 return BinaryOp_match<LHS, RHS, Instruction::Mul>(L, R);
628}
629
630template <typename LHS, typename RHS>
631inline BinaryOp_match<LHS, RHS, Instruction::FMul> m_FMul(const LHS &L,
632 const RHS &R) {
633 return BinaryOp_match<LHS, RHS, Instruction::FMul>(L, R);
634}
635
636template <typename LHS, typename RHS>
637inline BinaryOp_match<LHS, RHS, Instruction::UDiv> m_UDiv(const LHS &L,
638 const RHS &R) {
639 return BinaryOp_match<LHS, RHS, Instruction::UDiv>(L, R);
640}
641
642template <typename LHS, typename RHS>
643inline BinaryOp_match<LHS, RHS, Instruction::SDiv> m_SDiv(const LHS &L,
644 const RHS &R) {
645 return BinaryOp_match<LHS, RHS, Instruction::SDiv>(L, R);
646}
647
648template <typename LHS, typename RHS>
649inline BinaryOp_match<LHS, RHS, Instruction::FDiv> m_FDiv(const LHS &L,
650 const RHS &R) {
651 return BinaryOp_match<LHS, RHS, Instruction::FDiv>(L, R);
652}
653
654template <typename LHS, typename RHS>
655inline BinaryOp_match<LHS, RHS, Instruction::URem> m_URem(const LHS &L,
656 const RHS &R) {
657 return BinaryOp_match<LHS, RHS, Instruction::URem>(L, R);
658}
659
660template <typename LHS, typename RHS>
661inline BinaryOp_match<LHS, RHS, Instruction::SRem> m_SRem(const LHS &L,
662 const RHS &R) {
663 return BinaryOp_match<LHS, RHS, Instruction::SRem>(L, R);
664}
665
666template <typename LHS, typename RHS>
667inline BinaryOp_match<LHS, RHS, Instruction::FRem> m_FRem(const LHS &L,
668 const RHS &R) {
669 return BinaryOp_match<LHS, RHS, Instruction::FRem>(L, R);
670}
671
672template <typename LHS, typename RHS>
673inline BinaryOp_match<LHS, RHS, Instruction::And> m_And(const LHS &L,
674 const RHS &R) {
675 return BinaryOp_match<LHS, RHS, Instruction::And>(L, R);
676}
677
678template <typename LHS, typename RHS>
679inline BinaryOp_match<LHS, RHS, Instruction::Or> m_Or(const LHS &L,
680 const RHS &R) {
681 return BinaryOp_match<LHS, RHS, Instruction::Or>(L, R);
682}
683
684template <typename LHS, typename RHS>
685inline BinaryOp_match<LHS, RHS, Instruction::Xor> m_Xor(const LHS &L,
686 const RHS &R) {
687 return BinaryOp_match<LHS, RHS, Instruction::Xor>(L, R);
688}
689
690template <typename LHS, typename RHS>
691inline BinaryOp_match<LHS, RHS, Instruction::Shl> m_Shl(const LHS &L,
692 const RHS &R) {
693 return BinaryOp_match<LHS, RHS, Instruction::Shl>(L, R);
694}
695
696template <typename LHS, typename RHS>
697inline BinaryOp_match<LHS, RHS, Instruction::LShr> m_LShr(const LHS &L,
698 const RHS &R) {
699 return BinaryOp_match<LHS, RHS, Instruction::LShr>(L, R);
700}
701
702template <typename LHS, typename RHS>
703inline BinaryOp_match<LHS, RHS, Instruction::AShr> m_AShr(const LHS &L,
704 const RHS &R) {
705 return BinaryOp_match<LHS, RHS, Instruction::AShr>(L, R);
706}
707
708template <typename LHS_t, typename RHS_t, unsigned Opcode,
709 unsigned WrapFlags = 0>
710struct OverflowingBinaryOp_match {
711 LHS_t L;
712 RHS_t R;
713
714 OverflowingBinaryOp_match(const LHS_t &LHS, const RHS_t &RHS)
715 : L(LHS), R(RHS) {}
716
717 template <typename OpTy> bool match(OpTy *V) {
718 if (auto *Op = dyn_cast<OverflowingBinaryOperator>(V)) {
719 if (Op->getOpcode() != Opcode)
720 return false;
721 if (WrapFlags & OverflowingBinaryOperator::NoUnsignedWrap &&
722 !Op->hasNoUnsignedWrap())
723 return false;
724 if (WrapFlags & OverflowingBinaryOperator::NoSignedWrap &&
725 !Op->hasNoSignedWrap())
726 return false;
727 return L.match(Op->getOperand(0)) && R.match(Op->getOperand(1));
728 }
729 return false;
730 }
731};
732
733template <typename LHS, typename RHS>
734inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
735 OverflowingBinaryOperator::NoSignedWrap>
736m_NSWAdd(const LHS &L, const RHS &R) {
737 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
738 OverflowingBinaryOperator::NoSignedWrap>(
739 L, R);
740}
741template <typename LHS, typename RHS>
742inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
743 OverflowingBinaryOperator::NoSignedWrap>
744m_NSWSub(const LHS &L, const RHS &R) {
745 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
746 OverflowingBinaryOperator::NoSignedWrap>(
747 L, R);
748}
749template <typename LHS, typename RHS>
750inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
751 OverflowingBinaryOperator::NoSignedWrap>
752m_NSWMul(const LHS &L, const RHS &R) {
753 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
754 OverflowingBinaryOperator::NoSignedWrap>(
755 L, R);
756}
757template <typename LHS, typename RHS>
758inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
759 OverflowingBinaryOperator::NoSignedWrap>
760m_NSWShl(const LHS &L, const RHS &R) {
761 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
762 OverflowingBinaryOperator::NoSignedWrap>(
763 L, R);
764}
765
766template <typename LHS, typename RHS>
767inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
768 OverflowingBinaryOperator::NoUnsignedWrap>
769m_NUWAdd(const LHS &L, const RHS &R) {
770 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Add,
771 OverflowingBinaryOperator::NoUnsignedWrap>(
772 L, R);
773}
774template <typename LHS, typename RHS>
775inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
776 OverflowingBinaryOperator::NoUnsignedWrap>
777m_NUWSub(const LHS &L, const RHS &R) {
778 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Sub,
779 OverflowingBinaryOperator::NoUnsignedWrap>(
780 L, R);
781}
782template <typename LHS, typename RHS>
783inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
784 OverflowingBinaryOperator::NoUnsignedWrap>
785m_NUWMul(const LHS &L, const RHS &R) {
786 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Mul,
787 OverflowingBinaryOperator::NoUnsignedWrap>(
788 L, R);
789}
790template <typename LHS, typename RHS>
791inline OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
792 OverflowingBinaryOperator::NoUnsignedWrap>
793m_NUWShl(const LHS &L, const RHS &R) {
794 return OverflowingBinaryOp_match<LHS, RHS, Instruction::Shl,
795 OverflowingBinaryOperator::NoUnsignedWrap>(
796 L, R);
797}
798
799//===----------------------------------------------------------------------===//
800// Class that matches a group of binary opcodes.
801//
802template <typename LHS_t, typename RHS_t, typename Predicate>
803struct BinOpPred_match : Predicate {
804 LHS_t L;
805 RHS_t R;
806
807 BinOpPred_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
808
809 template <typename OpTy> bool match(OpTy *V) {
810 if (auto *I = dyn_cast<Instruction>(V))
811 return this->isOpType(I->getOpcode()) && L.match(I->getOperand(0)) &&
812 R.match(I->getOperand(1));
813 if (auto *CE = dyn_cast<ConstantExpr>(V))
814 return this->isOpType(CE->getOpcode()) && L.match(CE->getOperand(0)) &&
815 R.match(CE->getOperand(1));
816 return false;
817 }
818};
819
820struct is_shift_op {
821 bool isOpType(unsigned Opcode) { return Instruction::isShift(Opcode); }
822};
823
824struct is_right_shift_op {
825 bool isOpType(unsigned Opcode) {
826 return Opcode == Instruction::LShr || Opcode == Instruction::AShr;
827 }
828};
829
830struct is_logical_shift_op {
831 bool isOpType(unsigned Opcode) {
832 return Opcode == Instruction::LShr || Opcode == Instruction::Shl;
833 }
834};
835
836struct is_bitwiselogic_op {
837 bool isOpType(unsigned Opcode) {
838 return Instruction::isBitwiseLogicOp(Opcode);
839 }
840};
841
842struct is_idiv_op {
843 bool isOpType(unsigned Opcode) {
844 return Opcode == Instruction::SDiv || Opcode == Instruction::UDiv;
845 }
846};
847
848/// Matches shift operations.
849template <typename LHS, typename RHS>
850inline BinOpPred_match<LHS, RHS, is_shift_op> m_Shift(const LHS &L,
851 const RHS &R) {
852 return BinOpPred_match<LHS, RHS, is_shift_op>(L, R);
853}
854
855/// Matches logical shift operations.
856template <typename LHS, typename RHS>
857inline BinOpPred_match<LHS, RHS, is_right_shift_op> m_Shr(const LHS &L,
858 const RHS &R) {
859 return BinOpPred_match<LHS, RHS, is_right_shift_op>(L, R);
860}
861
862/// Matches logical shift operations.
863template <typename LHS, typename RHS>
864inline BinOpPred_match<LHS, RHS, is_logical_shift_op>
865m_LogicalShift(const LHS &L, const RHS &R) {
866 return BinOpPred_match<LHS, RHS, is_logical_shift_op>(L, R);
867}
868
869/// Matches bitwise logic operations.
870template <typename LHS, typename RHS>
871inline BinOpPred_match<LHS, RHS, is_bitwiselogic_op>
872m_BitwiseLogic(const LHS &L, const RHS &R) {
873 return BinOpPred_match<LHS, RHS, is_bitwiselogic_op>(L, R);
874}
875
876/// Matches integer division operations.
877template <typename LHS, typename RHS>
878inline BinOpPred_match<LHS, RHS, is_idiv_op> m_IDiv(const LHS &L,
879 const RHS &R) {
880 return BinOpPred_match<LHS, RHS, is_idiv_op>(L, R);
881}
882
883//===----------------------------------------------------------------------===//
884// Class that matches exact binary ops.
885//
886template <typename SubPattern_t> struct Exact_match {
887 SubPattern_t SubPattern;
888
889 Exact_match(const SubPattern_t &SP) : SubPattern(SP) {}
890
891 template <typename OpTy> bool match(OpTy *V) {
892 if (auto *PEO = dyn_cast<PossiblyExactOperator>(V))
893 return PEO->isExact() && SubPattern.match(V);
894 return false;
895 }
896};
897
898template <typename T> inline Exact_match<T> m_Exact(const T &SubPattern) {
899 return SubPattern;
900}
901
902//===----------------------------------------------------------------------===//
903// Matchers for CmpInst classes
904//
905
906template <typename LHS_t, typename RHS_t, typename Class, typename PredicateTy,
907 bool Commutable = false>
908struct CmpClass_match {
909 PredicateTy &Predicate;
910 LHS_t L;
911 RHS_t R;
912
913 CmpClass_match(PredicateTy &Pred, const LHS_t &LHS, const RHS_t &RHS)
914 : Predicate(Pred), L(LHS), R(RHS) {}
915
916 template <typename OpTy> bool match(OpTy *V) {
917 if (auto *I = dyn_cast<Class>(V))
918 if ((L.match(I->getOperand(0)) && R.match(I->getOperand(1))) ||
919 (Commutable && R.match(I->getOperand(0)) &&
920 L.match(I->getOperand(1)))) {
921 Predicate = I->getPredicate();
922 return true;
923 }
924 return false;
925 }
926};
927
928template <typename LHS, typename RHS>
929inline CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>
930m_Cmp(CmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
931 return CmpClass_match<LHS, RHS, CmpInst, CmpInst::Predicate>(Pred, L, R);
932}
933
934template <typename LHS, typename RHS>
935inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>
936m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
937 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate>(Pred, L, R);
938}
939
940template <typename LHS, typename RHS>
941inline CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>
942m_FCmp(FCmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
943 return CmpClass_match<LHS, RHS, FCmpInst, FCmpInst::Predicate>(Pred, L, R);
944}
945
946//===----------------------------------------------------------------------===//
947// Matchers for SelectInst classes
948//
949
950template <typename Cond_t, typename LHS_t, typename RHS_t>
951struct SelectClass_match {
952 Cond_t C;
953 LHS_t L;
954 RHS_t R;
955
956 SelectClass_match(const Cond_t &Cond, const LHS_t &LHS, const RHS_t &RHS)
957 : C(Cond), L(LHS), R(RHS) {}
958
959 template <typename OpTy> bool match(OpTy *V) {
960 if (auto *I = dyn_cast<SelectInst>(V))
961 return C.match(I->getOperand(0)) && L.match(I->getOperand(1)) &&
962 R.match(I->getOperand(2));
963 return false;
964 }
965};
966
967template <typename Cond, typename LHS, typename RHS>
968inline SelectClass_match<Cond, LHS, RHS> m_Select(const Cond &C, const LHS &L,
969 const RHS &R) {
970 return SelectClass_match<Cond, LHS, RHS>(C, L, R);
971}
972
973/// This matches a select of two constants, e.g.:
974/// m_SelectCst<-1, 0>(m_Value(V))
975template <int64_t L, int64_t R, typename Cond>
976inline SelectClass_match<Cond, constantint_match<L>, constantint_match<R>>
977m_SelectCst(const Cond &C) {
978 return m_Select(C, m_ConstantInt<L>(), m_ConstantInt<R>());
979}
980
981//===----------------------------------------------------------------------===//
982// Matchers for InsertElementInst classes
983//
984
985template <typename Val_t, typename Elt_t, typename Idx_t>
986struct InsertElementClass_match {
987 Val_t V;
988 Elt_t E;
989 Idx_t I;
990
991 InsertElementClass_match(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
992 : V(Val), E(Elt), I(Idx) {}
993
994 template <typename OpTy> bool match(OpTy *VV) {
995 if (auto *II = dyn_cast<InsertElementInst>(VV))
996 return V.match(II->getOperand(0)) && E.match(II->getOperand(1)) &&
997 I.match(II->getOperand(2));
998 return false;
999 }
1000};
1001
1002template <typename Val_t, typename Elt_t, typename Idx_t>
1003inline InsertElementClass_match<Val_t, Elt_t, Idx_t>
1004m_InsertElement(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx) {
1005 return InsertElementClass_match<Val_t, Elt_t, Idx_t>(Val, Elt, Idx);
1006}
1007
1008//===----------------------------------------------------------------------===//
1009// Matchers for ExtractElementInst classes
1010//
1011
1012template <typename Val_t, typename Idx_t> struct ExtractElementClass_match {
1013 Val_t V;
1014 Idx_t I;
1015
1016 ExtractElementClass_match(const Val_t &Val, const Idx_t &Idx)
1017 : V(Val), I(Idx) {}
1018
1019 template <typename OpTy> bool match(OpTy *VV) {
1020 if (auto *II = dyn_cast<ExtractElementInst>(VV))
1021 return V.match(II->getOperand(0)) && I.match(II->getOperand(1));
1022 return false;
1023 }
1024};
1025
1026template <typename Val_t, typename Idx_t>
1027inline ExtractElementClass_match<Val_t, Idx_t>
1028m_ExtractElement(const Val_t &Val, const Idx_t &Idx) {
1029 return ExtractElementClass_match<Val_t, Idx_t>(Val, Idx);
1030}
1031
1032//===----------------------------------------------------------------------===//
1033// Matchers for ShuffleVectorInst classes
1034//
1035
1036template <typename V1_t, typename V2_t, typename Mask_t>
1037struct ShuffleVectorClass_match {
1038 V1_t V1;
1039 V2_t V2;
1040 Mask_t M;
1041
1042 ShuffleVectorClass_match(const V1_t &v1, const V2_t &v2, const Mask_t &m)
1043 : V1(v1), V2(v2), M(m) {}
1044
1045 template <typename OpTy> bool match(OpTy *V) {
1046 if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
1047 return V1.match(SI->getOperand(0)) && V2.match(SI->getOperand(1)) &&
1048 M.match(SI->getOperand(2));
1049 return false;
1050 }
1051};
1052
1053template <typename V1_t, typename V2_t, typename Mask_t>
1054inline ShuffleVectorClass_match<V1_t, V2_t, Mask_t>
1055m_ShuffleVector(const V1_t &v1, const V2_t &v2, const Mask_t &m) {
1056 return ShuffleVectorClass_match<V1_t, V2_t, Mask_t>(v1, v2, m);
1057}
1058
1059//===----------------------------------------------------------------------===//
1060// Matchers for CastInst classes
1061//
1062
1063template <typename Op_t, unsigned Opcode> struct CastClass_match {
1064 Op_t Op;
1065
1066 CastClass_match(const Op_t &OpMatch) : Op(OpMatch) {}
1067
1068 template <typename OpTy> bool match(OpTy *V) {
1069 if (auto *O = dyn_cast<Operator>(V))
1070 return O->getOpcode() == Opcode && Op.match(O->getOperand(0));
1071 return false;
1072 }
1073};
1074
1075/// Matches BitCast.
1076template <typename OpTy>
1077inline CastClass_match<OpTy, Instruction::BitCast> m_BitCast(const OpTy &Op) {
1078 return CastClass_match<OpTy, Instruction::BitCast>(Op);
1079}
1080
1081/// Matches PtrToInt.
1082template <typename OpTy>
1083inline CastClass_match<OpTy, Instruction::PtrToInt> m_PtrToInt(const OpTy &Op) {
1084 return CastClass_match<OpTy, Instruction::PtrToInt>(Op);
1085}
1086
1087/// Matches Trunc.
1088template <typename OpTy>
1089inline CastClass_match<OpTy, Instruction::Trunc> m_Trunc(const OpTy &Op) {
1090 return CastClass_match<OpTy, Instruction::Trunc>(Op);
1091}
1092
1093/// Matches SExt.
1094template <typename OpTy>
1095inline CastClass_match<OpTy, Instruction::SExt> m_SExt(const OpTy &Op) {
1096 return CastClass_match<OpTy, Instruction::SExt>(Op);
1097}
1098
1099/// Matches ZExt.
1100template <typename OpTy>
1101inline CastClass_match<OpTy, Instruction::ZExt> m_ZExt(const OpTy &Op) {
1102 return CastClass_match<OpTy, Instruction::ZExt>(Op);
1103}
1104
1105template <typename OpTy>
1106inline match_combine_or<CastClass_match<OpTy, Instruction::ZExt>,
1107 CastClass_match<OpTy, Instruction::SExt>>
1108m_ZExtOrSExt(const OpTy &Op) {
1109 return m_CombineOr(m_ZExt(Op), m_SExt(Op));
1110}
1111
1112/// Matches UIToFP.
1113template <typename OpTy>
1114inline CastClass_match<OpTy, Instruction::UIToFP> m_UIToFP(const OpTy &Op) {
1115 return CastClass_match<OpTy, Instruction::UIToFP>(Op);
1116}
1117
1118/// Matches SIToFP.
1119template <typename OpTy>
1120inline CastClass_match<OpTy, Instruction::SIToFP> m_SIToFP(const OpTy &Op) {
1121 return CastClass_match<OpTy, Instruction::SIToFP>(Op);
1122}
1123
1124/// Matches FPTrunc
1125template <typename OpTy>
1126inline CastClass_match<OpTy, Instruction::FPTrunc> m_FPTrunc(const OpTy &Op) {
1127 return CastClass_match<OpTy, Instruction::FPTrunc>(Op);
1128}
1129
1130/// Matches FPExt
1131template <typename OpTy>
1132inline CastClass_match<OpTy, Instruction::FPExt> m_FPExt(const OpTy &Op) {
1133 return CastClass_match<OpTy, Instruction::FPExt>(Op);
1134}
1135
1136//===----------------------------------------------------------------------===//
1137// Matcher for LoadInst classes
1138//
1139
1140template <typename Op_t> struct LoadClass_match {
1141 Op_t Op;
1142
1143 LoadClass_match(const Op_t &OpMatch) : Op(OpMatch) {}
1144
1145 template <typename OpTy> bool match(OpTy *V) {
1146 if (auto *LI = dyn_cast<LoadInst>(V))
1147 return Op.match(LI->getPointerOperand());
1148 return false;
1149 }
1150};
1151
1152/// Matches LoadInst.
1153template <typename OpTy> inline LoadClass_match<OpTy> m_Load(const OpTy &Op) {
1154 return LoadClass_match<OpTy>(Op);
1155}
1156
1157//===----------------------------------------------------------------------===//
1158// Matchers for unary operators
1159//
1160
1161template <typename LHS_t> struct neg_match {
1162 LHS_t L;
1163
1164 neg_match(const LHS_t &LHS) : L(LHS) {}
1165
1166 template <typename OpTy> bool match(OpTy *V) {
1167 if (auto *O = dyn_cast<Operator>(V))
1168 if (O->getOpcode() == Instruction::Sub)
1169 return matchIfNeg(O->getOperand(0), O->getOperand(1));
1170 return false;
1171 }
1172
1173private:
1174 bool matchIfNeg(Value *LHS, Value *RHS) {
1175 return ((isa<ConstantInt>(LHS) && cast<ConstantInt>(LHS)->isZero()) ||
1176 isa<ConstantAggregateZero>(LHS)) &&
1177 L.match(RHS);
1178 }
1179};
1180
1181/// Match an integer negate.
1182template <typename LHS> inline neg_match<LHS> m_Neg(const LHS &L) { return L; }
1183
1184template <typename LHS_t> struct fneg_match {
1185 LHS_t L;
1186
1187 fneg_match(const LHS_t &LHS) : L(LHS) {}
1188
1189 template <typename OpTy> bool match(OpTy *V) {
1190 if (auto *O = dyn_cast<Operator>(V))
1191 if (O->getOpcode() == Instruction::FSub)
1192 return matchIfFNeg(O->getOperand(0), O->getOperand(1));
1193 return false;
1194 }
1195
1196private:
1197 bool matchIfFNeg(Value *LHS, Value *RHS) {
1198 if (const auto *C = dyn_cast<Constant>(LHS))
1199 return C->isNegativeZeroValue() && L.match(RHS);
1200 return false;
1201 }
1202};
1203
1204/// Match a floating point negate.
1205template <typename LHS> inline fneg_match<LHS> m_FNeg(const LHS &L) {
1206 return L;
1207}
1208
1209//===----------------------------------------------------------------------===//
1210// Matchers for control flow.
1211//
1212
1213struct br_match {
1214 BasicBlock *&Succ;
1215
1216 br_match(BasicBlock *&Succ) : Succ(Succ) {}
1217
1218 template <typename OpTy> bool match(OpTy *V) {
1219 if (auto *BI = dyn_cast<BranchInst>(V))
1220 if (BI->isUnconditional()) {
1221 Succ = BI->getSuccessor(0);
1222 return true;
1223 }
1224 return false;
1225 }
1226};
1227
1228inline br_match m_UnconditionalBr(BasicBlock *&Succ) { return br_match(Succ); }
1229
1230template <typename Cond_t> struct brc_match {
1231 Cond_t Cond;
1232 BasicBlock *&T, *&F;
1233
1234 brc_match(const Cond_t &C, BasicBlock *&t, BasicBlock *&f)
1235 : Cond(C), T(t), F(f) {}
1236
1237 template <typename OpTy> bool match(OpTy *V) {
1238 if (auto *BI = dyn_cast<BranchInst>(V))
1239 if (BI->isConditional() && Cond.match(BI->getCondition())) {
1240 T = BI->getSuccessor(0);
1241 F = BI->getSuccessor(1);
1242 return true;
1243 }
1244 return false;
1245 }
1246};
1247
1248template <typename Cond_t>
1249inline brc_match<Cond_t> m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F) {
1250 return brc_match<Cond_t>(C, T, F);
1251}
1252
1253//===----------------------------------------------------------------------===//
1254// Matchers for max/min idioms, eg: "select (sgt x, y), x, y" -> smax(x,y).
1255//
1256
1257template <typename CmpInst_t, typename LHS_t, typename RHS_t, typename Pred_t,
1258 bool Commutable = false>
1259struct MaxMin_match {
1260 LHS_t L;
1261 RHS_t R;
1262
1263 MaxMin_match(const LHS_t &LHS, const RHS_t &RHS) : L(LHS), R(RHS) {}
1264
1265 template <typename OpTy> bool match(OpTy *V) {
1266 // Look for "(x pred y) ? x : y" or "(x pred y) ? y : x".
1267 auto *SI = dyn_cast<SelectInst>(V);
1268 if (!SI)
1269 return false;
1270 auto *Cmp = dyn_cast<CmpInst_t>(SI->getCondition());
1271 if (!Cmp)
1272 return false;
1273 // At this point we have a select conditioned on a comparison. Check that
1274 // it is the values returned by the select that are being compared.
1275 Value *TrueVal = SI->getTrueValue();
1276 Value *FalseVal = SI->getFalseValue();
1277 Value *LHS = Cmp->getOperand(0);
1278 Value *RHS = Cmp->getOperand(1);
1279 if ((TrueVal != LHS || FalseVal != RHS) &&
1280 (TrueVal != RHS || FalseVal != LHS))
1281 return false;
1282 typename CmpInst_t::Predicate Pred =
1283 LHS == TrueVal ? Cmp->getPredicate() : Cmp->getInversePredicate();
1284 // Does "(x pred y) ? x : y" represent the desired max/min operation?
1285 if (!Pred_t::match(Pred))
1286 return false;
1287 // It does! Bind the operands.
1288 return (L.match(LHS) && R.match(RHS)) ||
1289 (Commutable && R.match(LHS) && L.match(RHS));
1290 }
1291};
1292
1293/// Helper class for identifying signed max predicates.
1294struct smax_pred_ty {
1295 static bool match(ICmpInst::Predicate Pred) {
1296 return Pred == CmpInst::ICMP_SGT || Pred == CmpInst::ICMP_SGE;
1297 }
1298};
1299
1300/// Helper class for identifying signed min predicates.
1301struct smin_pred_ty {
1302 static bool match(ICmpInst::Predicate Pred) {
1303 return Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_SLE;
1304 }
1305};
1306
1307/// Helper class for identifying unsigned max predicates.
1308struct umax_pred_ty {
1309 static bool match(ICmpInst::Predicate Pred) {
1310 return Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_UGE;
1311 }
1312};
1313
1314/// Helper class for identifying unsigned min predicates.
1315struct umin_pred_ty {
1316 static bool match(ICmpInst::Predicate Pred) {
1317 return Pred == CmpInst::ICMP_ULT || Pred == CmpInst::ICMP_ULE;
1318 }
1319};
1320
1321/// Helper class for identifying ordered max predicates.
1322struct ofmax_pred_ty {
1323 static bool match(FCmpInst::Predicate Pred) {
1324 return Pred == CmpInst::FCMP_OGT || Pred == CmpInst::FCMP_OGE;
1325 }
1326};
1327
1328/// Helper class for identifying ordered min predicates.
1329struct ofmin_pred_ty {
1330 static bool match(FCmpInst::Predicate Pred) {
1331 return Pred == CmpInst::FCMP_OLT || Pred == CmpInst::FCMP_OLE;
1332 }
1333};
1334
1335/// Helper class for identifying unordered max predicates.
1336struct ufmax_pred_ty {
1337 static bool match(FCmpInst::Predicate Pred) {
1338 return Pred == CmpInst::FCMP_UGT || Pred == CmpInst::FCMP_UGE;
1339 }
1340};
1341
1342/// Helper class for identifying unordered min predicates.
1343struct ufmin_pred_ty {
1344 static bool match(FCmpInst::Predicate Pred) {
1345 return Pred == CmpInst::FCMP_ULT || Pred == CmpInst::FCMP_ULE;
1346 }
1347};
1348
1349template <typename LHS, typename RHS>
1350inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty> m_SMax(const LHS &L,
1351 const RHS &R) {
1352 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty>(L, R);
1353}
1354
1355template <typename LHS, typename RHS>
1356inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty> m_SMin(const LHS &L,
1357 const RHS &R) {
1358 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty>(L, R);
1359}
1360
1361template <typename LHS, typename RHS>
1362inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty> m_UMax(const LHS &L,
1363 const RHS &R) {
1364 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty>(L, R);
1365}
1366
1367template <typename LHS, typename RHS>
1368inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty> m_UMin(const LHS &L,
1369 const RHS &R) {
1370 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty>(L, R);
1371}
1372
1373/// Match an 'ordered' floating point maximum function.
1374/// Floating point has one special value 'NaN'. Therefore, there is no total
1375/// order. However, if we can ignore the 'NaN' value (for example, because of a
1376/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1377/// semantics. In the presence of 'NaN' we have to preserve the original
1378/// select(fcmp(ogt/ge, L, R), L, R) semantics matched by this predicate.
1379///
1380/// max(L, R) iff L and R are not NaN
1381/// m_OrdFMax(L, R) = R iff L or R are NaN
1382template <typename LHS, typename RHS>
1383inline MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty> m_OrdFMax(const LHS &L,
1384 const RHS &R) {
1385 return MaxMin_match<FCmpInst, LHS, RHS, ofmax_pred_ty>(L, R);
1386}
1387
1388/// Match an 'ordered' floating point minimum function.
1389/// Floating point has one special value 'NaN'. Therefore, there is no total
1390/// order. However, if we can ignore the 'NaN' value (for example, because of a
1391/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1392/// semantics. In the presence of 'NaN' we have to preserve the original
1393/// select(fcmp(olt/le, L, R), L, R) semantics matched by this predicate.
1394///
1395/// min(L, R) iff L and R are not NaN
1396/// m_OrdFMin(L, R) = R iff L or R are NaN
1397template <typename LHS, typename RHS>
1398inline MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty> m_OrdFMin(const LHS &L,
1399 const RHS &R) {
1400 return MaxMin_match<FCmpInst, LHS, RHS, ofmin_pred_ty>(L, R);
1401}
1402
1403/// Match an 'unordered' floating point maximum function.
1404/// Floating point has one special value 'NaN'. Therefore, there is no total
1405/// order. However, if we can ignore the 'NaN' value (for example, because of a
1406/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'maximum'
1407/// semantics. In the presence of 'NaN' we have to preserve the original
1408/// select(fcmp(ugt/ge, L, R), L, R) semantics matched by this predicate.
1409///
1410/// max(L, R) iff L and R are not NaN
1411/// m_UnordFMax(L, R) = L iff L or R are NaN
1412template <typename LHS, typename RHS>
1413inline MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>
1414m_UnordFMax(const LHS &L, const RHS &R) {
1415 return MaxMin_match<FCmpInst, LHS, RHS, ufmax_pred_ty>(L, R);
1416}
1417
1418/// Match an 'unordered' floating point minimum function.
1419/// Floating point has one special value 'NaN'. Therefore, there is no total
1420/// order. However, if we can ignore the 'NaN' value (for example, because of a
1421/// 'no-nans-float-math' flag) a combination of a fcmp and select has 'minimum'
1422/// semantics. In the presence of 'NaN' we have to preserve the original
1423/// select(fcmp(ult/le, L, R), L, R) semantics matched by this predicate.
1424///
1425/// min(L, R) iff L and R are not NaN
1426/// m_UnordFMin(L, R) = L iff L or R are NaN
1427template <typename LHS, typename RHS>
1428inline MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>
1429m_UnordFMin(const LHS &L, const RHS &R) {
1430 return MaxMin_match<FCmpInst, LHS, RHS, ufmin_pred_ty>(L, R);
1431}
1432
1433//===----------------------------------------------------------------------===//
1434// Matchers for overflow check patterns: e.g. (a + b) u< a
1435//
1436
1437template <typename LHS_t, typename RHS_t, typename Sum_t>
1438struct UAddWithOverflow_match {
1439 LHS_t L;
1440 RHS_t R;
1441 Sum_t S;
1442
1443 UAddWithOverflow_match(const LHS_t &L, const RHS_t &R, const Sum_t &S)
1444 : L(L), R(R), S(S) {}
1445
1446 template <typename OpTy> bool match(OpTy *V) {
1447 Value *ICmpLHS, *ICmpRHS;
1448 ICmpInst::Predicate Pred;
1449 if (!m_ICmp(Pred, m_Value(ICmpLHS), m_Value(ICmpRHS)).match(V))
1450 return false;
1451
1452 Value *AddLHS, *AddRHS;
1453 auto AddExpr = m_Add(m_Value(AddLHS), m_Value(AddRHS));
1454
1455 // (a + b) u< a, (a + b) u< b
1456 if (Pred == ICmpInst::ICMP_ULT)
1457 if (AddExpr.match(ICmpLHS) && (ICmpRHS == AddLHS || ICmpRHS == AddRHS))
1458 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpLHS);
1459
1460 // a >u (a + b), b >u (a + b)
1461 if (Pred == ICmpInst::ICMP_UGT)
1462 if (AddExpr.match(ICmpRHS) && (ICmpLHS == AddLHS || ICmpLHS == AddRHS))
1463 return L.match(AddLHS) && R.match(AddRHS) && S.match(ICmpRHS);
1464
1465 return false;
1466 }
1467};
1468
1469/// Match an icmp instruction checking for unsigned overflow on addition.
1470///
1471/// S is matched to the addition whose result is being checked for overflow, and
1472/// L and R are matched to the LHS and RHS of S.
1473template <typename LHS_t, typename RHS_t, typename Sum_t>
1474UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>
1475m_UAddWithOverflow(const LHS_t &L, const RHS_t &R, const Sum_t &S) {
1476 return UAddWithOverflow_match<LHS_t, RHS_t, Sum_t>(L, R, S);
1477}
1478
1479template <typename Opnd_t> struct Argument_match {
1480 unsigned OpI;
1481 Opnd_t Val;
1482
1483 Argument_match(unsigned OpIdx, const Opnd_t &V) : OpI(OpIdx), Val(V) {}
1484
1485 template <typename OpTy> bool match(OpTy *V) {
1486 CallSite CS(V);
1487 return CS.isCall() && Val.match(CS.getArgument(OpI));
1488 }
1489};
1490
1491/// Match an argument.
1492template <unsigned OpI, typename Opnd_t>
1493inline Argument_match<Opnd_t> m_Argument(const Opnd_t &Op) {
1494 return Argument_match<Opnd_t>(OpI, Op);
1495}
1496
1497/// Intrinsic matchers.
1498struct IntrinsicID_match {
1499 unsigned ID;
1500
1501 IntrinsicID_match(Intrinsic::ID IntrID) : ID(IntrID) {}
1502
1503 template <typename OpTy> bool match(OpTy *V) {
1504 if (const auto *CI = dyn_cast<CallInst>(V))
1505 if (const auto *F = CI->getCalledFunction())
1506 return F->getIntrinsicID() == ID;
1507 return false;
1508 }
1509};
1510
1511/// Intrinsic matches are combinations of ID matchers, and argument
1512/// matchers. Higher arity matcher are defined recursively in terms of and-ing
1513/// them with lower arity matchers. Here's some convenient typedefs for up to
1514/// several arguments, and more can be added as needed
1515template <typename T0 = void, typename T1 = void, typename T2 = void,
1516 typename T3 = void, typename T4 = void, typename T5 = void,
1517 typename T6 = void, typename T7 = void, typename T8 = void,
1518 typename T9 = void, typename T10 = void>
1519struct m_Intrinsic_Ty;
1520template <typename T0> struct m_Intrinsic_Ty<T0> {
1521 using Ty = match_combine_and<IntrinsicID_match, Argument_match<T0>>;
1522};
1523template <typename T0, typename T1> struct m_Intrinsic_Ty<T0, T1> {
1524 using Ty =
1525 match_combine_and<typename m_Intrinsic_Ty<T0>::Ty, Argument_match<T1>>;
1526};
1527template <typename T0, typename T1, typename T2>
1528struct m_Intrinsic_Ty<T0, T1, T2> {
1529 using Ty =
1530 match_combine_and<typename m_Intrinsic_Ty<T0, T1>::Ty,
1531 Argument_match<T2>>;
1532};
1533template <typename T0, typename T1, typename T2, typename T3>
1534struct m_Intrinsic_Ty<T0, T1, T2, T3> {
1535 using Ty =
1536 match_combine_and<typename m_Intrinsic_Ty<T0, T1, T2>::Ty,
1537 Argument_match<T3>>;
1538};
1539
1540/// Match intrinsic calls like this:
1541/// m_Intrinsic<Intrinsic::fabs>(m_Value(X))
1542template <Intrinsic::ID IntrID> inline IntrinsicID_match m_Intrinsic() {
1543 return IntrinsicID_match(IntrID);
1544}
1545
1546template <Intrinsic::ID IntrID, typename T0>
1547inline typename m_Intrinsic_Ty<T0>::Ty m_Intrinsic(const T0 &Op0) {
1548 return m_CombineAnd(m_Intrinsic<IntrID>(), m_Argument<0>(Op0));
1549}
1550
1551template <Intrinsic::ID IntrID, typename T0, typename T1>
1552inline typename m_Intrinsic_Ty<T0, T1>::Ty m_Intrinsic(const T0 &Op0,
1553 const T1 &Op1) {
1554 return m_CombineAnd(m_Intrinsic<IntrID>(Op0), m_Argument<1>(Op1));
1555}
1556
1557template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2>
1558inline typename m_Intrinsic_Ty<T0, T1, T2>::Ty
1559m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2) {
1560 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1), m_Argument<2>(Op2));
1561}
1562
1563template <Intrinsic::ID IntrID, typename T0, typename T1, typename T2,
1564 typename T3>
1565inline typename m_Intrinsic_Ty<T0, T1, T2, T3>::Ty
1566m_Intrinsic(const T0 &Op0, const T1 &Op1, const T2 &Op2, const T3 &Op3) {
1567 return m_CombineAnd(m_Intrinsic<IntrID>(Op0, Op1, Op2), m_Argument<3>(Op3));
1568}
1569
1570// Helper intrinsic matching specializations.
1571template <typename Opnd0>
1572inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BitReverse(const Opnd0 &Op0) {
1573 return m_Intrinsic<Intrinsic::bitreverse>(Op0);
1574}
1575
1576template <typename Opnd0>
1577inline typename m_Intrinsic_Ty<Opnd0>::Ty m_BSwap(const Opnd0 &Op0) {
1578 return m_Intrinsic<Intrinsic::bswap>(Op0);
1579}
1580
1581template <typename Opnd0, typename Opnd1>
1582inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMin(const Opnd0 &Op0,
1583 const Opnd1 &Op1) {
1584 return m_Intrinsic<Intrinsic::minnum>(Op0, Op1);
1585}
1586
1587template <typename Opnd0, typename Opnd1>
1588inline typename m_Intrinsic_Ty<Opnd0, Opnd1>::Ty m_FMax(const Opnd0 &Op0,
1589 const Opnd1 &Op1) {
1590 return m_Intrinsic<Intrinsic::maxnum>(Op0, Op1);
1591}
1592
1593template <typename Opnd_t> struct Signum_match {
1594 Opnd_t Val;
1595 Signum_match(const Opnd_t &V) : Val(V) {}
1596
1597 template <typename OpTy> bool match(OpTy *V) {
1598 unsigned TypeSize = V->getType()->getScalarSizeInBits();
1599 if (TypeSize == 0)
1600 return false;
1601
1602 unsigned ShiftWidth = TypeSize - 1;
1603 Value *OpL = nullptr, *OpR = nullptr;
1604
1605 // This is the representation of signum we match:
1606 //
1607 // signum(x) == (x >> 63) | (-x >>u 63)
1608 //
1609 // An i1 value is its own signum, so it's correct to match
1610 //
1611 // signum(x) == (x >> 0) | (-x >>u 0)
1612 //
1613 // for i1 values.
1614
1615 auto LHS = m_AShr(m_Value(OpL), m_SpecificInt(ShiftWidth));
1616 auto RHS = m_LShr(m_Neg(m_Value(OpR)), m_SpecificInt(ShiftWidth));
1617 auto Signum = m_Or(LHS, RHS);
1618
1619 return Signum.match(V) && OpL == OpR && Val.match(OpL);
1620 }
1621};
1622
1623/// Matches a signum pattern.
1624///
1625/// signum(x) =
1626/// x > 0 -> 1
1627/// x == 0 -> 0
1628/// x < 0 -> -1
1629template <typename Val_t> inline Signum_match<Val_t> m_Signum(const Val_t &V) {
1630 return Signum_match<Val_t>(V);
1631}
1632
1633//===----------------------------------------------------------------------===//
1634// Matchers for two-operands operators with the operators in either order
1635//
1636
1637/// Matches a BinaryOperator with LHS and RHS in either order.
1638template <typename LHS, typename RHS>
1639inline AnyBinaryOp_match<LHS, RHS, true> m_c_BinOp(const LHS &L, const RHS &R) {
1640 return AnyBinaryOp_match<LHS, RHS, true>(L, R);
1641}
1642
1643/// Matches an ICmp with a predicate over LHS and RHS in either order.
1644/// Does not swap the predicate.
1645template <typename LHS, typename RHS>
1646inline CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>
1647m_c_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R) {
1648 return CmpClass_match<LHS, RHS, ICmpInst, ICmpInst::Predicate, true>(Pred, L,
1649 R);
1650}
1651
1652/// Matches a Add with LHS and RHS in either order.
1653template <typename LHS, typename RHS>
1654inline BinaryOp_match<LHS, RHS, Instruction::Add, true> m_c_Add(const LHS &L,
1655 const RHS &R) {
1656 return BinaryOp_match<LHS, RHS, Instruction::Add, true>(L, R);
1657}
1658
1659/// Matches a Mul with LHS and RHS in either order.
1660template <typename LHS, typename RHS>
1661inline BinaryOp_match<LHS, RHS, Instruction::Mul, true> m_c_Mul(const LHS &L,
1662 const RHS &R) {
1663 return BinaryOp_match<LHS, RHS, Instruction::Mul, true>(L, R);
1664}
1665
1666/// Matches an And with LHS and RHS in either order.
1667template <typename LHS, typename RHS>
1668inline BinaryOp_match<LHS, RHS, Instruction::And, true> m_c_And(const LHS &L,
1669 const RHS &R) {
1670 return BinaryOp_match<LHS, RHS, Instruction::And, true>(L, R);
1671}
1672
1673/// Matches an Or with LHS and RHS in either order.
1674template <typename LHS, typename RHS>
1675inline BinaryOp_match<LHS, RHS, Instruction::Or, true> m_c_Or(const LHS &L,
1676 const RHS &R) {
1677 return BinaryOp_match<LHS, RHS, Instruction::Or, true>(L, R);
1678}
1679
1680/// Matches an Xor with LHS and RHS in either order.
1681template <typename LHS, typename RHS>
1682inline BinaryOp_match<LHS, RHS, Instruction::Xor, true> m_c_Xor(const LHS &L,
1683 const RHS &R) {
1684 return BinaryOp_match<LHS, RHS, Instruction::Xor, true>(L, R);
1685}
1686
1687/// Matches a 'Not' as 'xor V, -1' or 'xor -1, V'.
1688template <typename ValTy>
1689inline BinaryOp_match<ValTy, cst_pred_ty<is_all_ones>, Instruction::Xor, true>
1690m_Not(const ValTy &V) {
1691 return m_c_Xor(V, m_AllOnes());
1692}
1693
1694/// Matches an SMin with LHS and RHS in either order.
1695template <typename LHS, typename RHS>
1696inline MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>
1697m_c_SMin(const LHS &L, const RHS &R) {
1698 return MaxMin_match<ICmpInst, LHS, RHS, smin_pred_ty, true>(L, R);
1699}
1700/// Matches an SMax with LHS and RHS in either order.
1701template <typename LHS, typename RHS>
1702inline MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>
1703m_c_SMax(const LHS &L, const RHS &R) {
1704 return MaxMin_match<ICmpInst, LHS, RHS, smax_pred_ty, true>(L, R);
1705}
1706/// Matches a UMin with LHS and RHS in either order.
1707template <typename LHS, typename RHS>
1708inline MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>
1709m_c_UMin(const LHS &L, const RHS &R) {
1710 return MaxMin_match<ICmpInst, LHS, RHS, umin_pred_ty, true>(L, R);
1711}
1712/// Matches a UMax with LHS and RHS in either order.
1713template <typename LHS, typename RHS>
1714inline MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>
1715m_c_UMax(const LHS &L, const RHS &R) {
1716 return MaxMin_match<ICmpInst, LHS, RHS, umax_pred_ty, true>(L, R);
1717}
1718
1719/// Matches FAdd with LHS and RHS in either order.
1720template <typename LHS, typename RHS>
1721inline BinaryOp_match<LHS, RHS, Instruction::FAdd, true>
1722m_c_FAdd(const LHS &L, const RHS &R) {
1723 return BinaryOp_match<LHS, RHS, Instruction::FAdd, true>(L, R);
1724}
1725
1726/// Matches FMul with LHS and RHS in either order.
1727template <typename LHS, typename RHS>
1728inline BinaryOp_match<LHS, RHS, Instruction::FMul, true>
1729m_c_FMul(const LHS &L, const RHS &R) {
1730 return BinaryOp_match<LHS, RHS, Instruction::FMul, true>(L, R);
1731}
1732
1733} // end namespace PatternMatch
1734} // end namespace llvm
1735
1736#endif // LLVM_IR_PATTERNMATCH_H