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