LLVM  9.0.0svn
InstCombineSelect.cpp
Go to the documentation of this file.
1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitSelect function.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APInt.h"
15 #include "llvm/ADT/Optional.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/IR/BasicBlock.h"
23 #include "llvm/IR/Constant.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/IRBuilder.h"
27 #include "llvm/IR/InstrTypes.h"
28 #include "llvm/IR/Instruction.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/Type.h"
35 #include "llvm/IR/User.h"
36 #include "llvm/IR/Value.h"
37 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/KnownBits.h"
41 #include <cassert>
42 #include <utility>
43 
44 using namespace llvm;
45 using namespace PatternMatch;
46 
47 #define DEBUG_TYPE "instcombine"
48 
50  SelectPatternFlavor SPF, Value *A, Value *B) {
52  assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate");
53  return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
54 }
55 
56 /// Replace a select operand based on an equality comparison with the identity
57 /// constant of a binop.
59  const TargetLibraryInfo &TLI) {
60  // The select condition must be an equality compare with a constant operand.
61  Value *X;
62  Constant *C;
63  CmpInst::Predicate Pred;
64  if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C))))
65  return nullptr;
66 
67  bool IsEq;
68  if (ICmpInst::isEquality(Pred))
69  IsEq = Pred == ICmpInst::ICMP_EQ;
70  else if (Pred == FCmpInst::FCMP_OEQ)
71  IsEq = true;
72  else if (Pred == FCmpInst::FCMP_UNE)
73  IsEq = false;
74  else
75  return nullptr;
76 
77  // A select operand must be a binop.
78  BinaryOperator *BO;
79  if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO)))
80  return nullptr;
81 
82  // The compare constant must be the identity constant for that binop.
83  // If this a floating-point compare with 0.0, any zero constant will do.
84  Type *Ty = BO->getType();
85  Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true);
86  if (IdC != C) {
87  if (!IdC || !CmpInst::isFPPredicate(Pred))
88  return nullptr;
89  if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP()))
90  return nullptr;
91  }
92 
93  // Last, match the compare variable operand with a binop operand.
94  Value *Y;
95  if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X))))
96  return nullptr;
97  if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X))))
98  return nullptr;
99 
100  // +0.0 compares equal to -0.0, and so it does not behave as required for this
101  // transform. Bail out if we can not exclude that possibility.
102  if (isa<FPMathOperator>(BO))
103  if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI))
104  return nullptr;
105 
106  // BO = binop Y, X
107  // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO }
108  // =>
109  // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y }
110  Sel.setOperand(IsEq ? 1 : 2, Y);
111  return &Sel;
112 }
113 
114 /// This folds:
115 /// select (icmp eq (and X, C1)), TC, FC
116 /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2.
117 /// To something like:
118 /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC
119 /// Or:
120 /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC
121 /// With some variations depending if FC is larger than TC, or the shift
122 /// isn't needed, or the bit widths don't match.
124  InstCombiner::BuilderTy &Builder) {
125  const APInt *SelTC, *SelFC;
126  if (!match(Sel.getTrueValue(), m_APInt(SelTC)) ||
127  !match(Sel.getFalseValue(), m_APInt(SelFC)))
128  return nullptr;
129 
130  // If this is a vector select, we need a vector compare.
131  Type *SelType = Sel.getType();
132  if (SelType->isVectorTy() != Cmp->getType()->isVectorTy())
133  return nullptr;
134 
135  Value *V;
136  APInt AndMask;
137  bool CreateAnd = false;
138  ICmpInst::Predicate Pred = Cmp->getPredicate();
139  if (ICmpInst::isEquality(Pred)) {
140  if (!match(Cmp->getOperand(1), m_Zero()))
141  return nullptr;
142 
143  V = Cmp->getOperand(0);
144  const APInt *AndRHS;
145  if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
146  return nullptr;
147 
148  AndMask = *AndRHS;
149  } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1),
150  Pred, V, AndMask)) {
151  assert(ICmpInst::isEquality(Pred) && "Not equality test?");
152  if (!AndMask.isPowerOf2())
153  return nullptr;
154 
155  CreateAnd = true;
156  } else {
157  return nullptr;
158  }
159 
160  // In general, when both constants are non-zero, we would need an offset to
161  // replace the select. This would require more instructions than we started
162  // with. But there's one special-case that we handle here because it can
163  // simplify/reduce the instructions.
164  APInt TC = *SelTC;
165  APInt FC = *SelFC;
166  if (!TC.isNullValue() && !FC.isNullValue()) {
167  // If the select constants differ by exactly one bit and that's the same
168  // bit that is masked and checked by the select condition, the select can
169  // be replaced by bitwise logic to set/clear one bit of the constant result.
170  if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask)
171  return nullptr;
172  if (CreateAnd) {
173  // If we have to create an 'and', then we must kill the cmp to not
174  // increase the instruction count.
175  if (!Cmp->hasOneUse())
176  return nullptr;
177  V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask));
178  }
179  bool ExtraBitInTC = TC.ugt(FC);
180  if (Pred == ICmpInst::ICMP_EQ) {
181  // If the masked bit in V is clear, clear or set the bit in the result:
182  // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC
183  // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC
184  Constant *C = ConstantInt::get(SelType, TC);
185  return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C);
186  }
187  if (Pred == ICmpInst::ICMP_NE) {
188  // If the masked bit in V is set, set or clear the bit in the result:
189  // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC
190  // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC
191  Constant *C = ConstantInt::get(SelType, FC);
192  return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C);
193  }
194  llvm_unreachable("Only expecting equality predicates");
195  }
196 
197  // Make sure one of the select arms is a power-of-2.
198  if (!TC.isPowerOf2() && !FC.isPowerOf2())
199  return nullptr;
200 
201  // Determine which shift is needed to transform result of the 'and' into the
202  // desired result.
203  const APInt &ValC = !TC.isNullValue() ? TC : FC;
204  unsigned ValZeros = ValC.logBase2();
205  unsigned AndZeros = AndMask.logBase2();
206 
207  // Insert the 'and' instruction on the input to the truncate.
208  if (CreateAnd)
209  V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
210 
211  // If types don't match, we can still convert the select by introducing a zext
212  // or a trunc of the 'and'.
213  if (ValZeros > AndZeros) {
214  V = Builder.CreateZExtOrTrunc(V, SelType);
215  V = Builder.CreateShl(V, ValZeros - AndZeros);
216  } else if (ValZeros < AndZeros) {
217  V = Builder.CreateLShr(V, AndZeros - ValZeros);
218  V = Builder.CreateZExtOrTrunc(V, SelType);
219  } else {
220  V = Builder.CreateZExtOrTrunc(V, SelType);
221  }
222 
223  // Okay, now we know that everything is set up, we just don't know whether we
224  // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
225  bool ShouldNotVal = !TC.isNullValue();
226  ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
227  if (ShouldNotVal)
228  V = Builder.CreateXor(V, ValC);
229 
230  return V;
231 }
232 
233 /// We want to turn code that looks like this:
234 /// %C = or %A, %B
235 /// %D = select %cond, %C, %A
236 /// into:
237 /// %C = select %cond, %B, 0
238 /// %D = or %A, %C
239 ///
240 /// Assuming that the specified instruction is an operand to the select, return
241 /// a bitmask indicating which operands of this instruction are foldable if they
242 /// equal the other incoming value of the select.
244  switch (I->getOpcode()) {
245  case Instruction::Add:
246  case Instruction::Mul:
247  case Instruction::And:
248  case Instruction::Or:
249  case Instruction::Xor:
250  return 3; // Can fold through either operand.
251  case Instruction::Sub: // Can only fold on the amount subtracted.
252  case Instruction::Shl: // Can only fold on the shift amount.
253  case Instruction::LShr:
254  case Instruction::AShr:
255  return 1;
256  default:
257  return 0; // Cannot fold
258  }
259 }
260 
261 /// For the same transformation as the previous function, return the identity
262 /// constant that goes into the select.
264  switch (I->getOpcode()) {
265  default: llvm_unreachable("This cannot happen!");
266  case Instruction::Add:
267  case Instruction::Sub:
268  case Instruction::Or:
269  case Instruction::Xor:
270  case Instruction::Shl:
271  case Instruction::LShr:
272  case Instruction::AShr:
274  case Instruction::And:
276  case Instruction::Mul:
277  return APInt(I->getType()->getScalarSizeInBits(), 1);
278  }
279 }
280 
281 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
282 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
283  Instruction *FI) {
284  // Don't break up min/max patterns. The hasOneUse checks below prevent that
285  // for most cases, but vector min/max with bitcasts can be transformed. If the
286  // one-use restrictions are eased for other patterns, we still don't want to
287  // obfuscate min/max.
288  if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
289  match(&SI, m_SMax(m_Value(), m_Value())) ||
290  match(&SI, m_UMin(m_Value(), m_Value())) ||
291  match(&SI, m_UMax(m_Value(), m_Value()))))
292  return nullptr;
293 
294  // If this is a cast from the same type, merge.
295  if (TI->getNumOperands() == 1 && TI->isCast()) {
296  Type *FIOpndTy = FI->getOperand(0)->getType();
297  if (TI->getOperand(0)->getType() != FIOpndTy)
298  return nullptr;
299 
300  // The select condition may be a vector. We may only change the operand
301  // type if the vector width remains the same (and matches the condition).
302  Type *CondTy = SI.getCondition()->getType();
303  if (CondTy->isVectorTy()) {
304  if (!FIOpndTy->isVectorTy())
305  return nullptr;
306  if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
307  return nullptr;
308 
309  // TODO: If the backend knew how to deal with casts better, we could
310  // remove this limitation. For now, there's too much potential to create
311  // worse codegen by promoting the select ahead of size-altering casts
312  // (PR28160).
313  //
314  // Note that ValueTracking's matchSelectPattern() looks through casts
315  // without checking 'hasOneUse' when it matches min/max patterns, so this
316  // transform may end up happening anyway.
317  if (TI->getOpcode() != Instruction::BitCast &&
318  (!TI->hasOneUse() || !FI->hasOneUse()))
319  return nullptr;
320  } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
321  // TODO: The one-use restrictions for a scalar select could be eased if
322  // the fold of a select in visitLoadInst() was enhanced to match a pattern
323  // that includes a cast.
324  return nullptr;
325  }
326 
327  // Fold this by inserting a select from the input values.
328  Value *NewSI =
329  Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
330  FI->getOperand(0), SI.getName() + ".v", &SI);
331  return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
332  TI->getType());
333  }
334 
335  // Only handle binary operators (including two-operand getelementptr) with
336  // one-use here. As with the cast case above, it may be possible to relax the
337  // one-use constraint, but that needs be examined carefully since it may not
338  // reduce the total number of instructions.
339  if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 ||
340  (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) ||
341  !TI->hasOneUse() || !FI->hasOneUse())
342  return nullptr;
343 
344  // Figure out if the operations have any operands in common.
345  Value *MatchOp, *OtherOpT, *OtherOpF;
346  bool MatchIsOpZero;
347  if (TI->getOperand(0) == FI->getOperand(0)) {
348  MatchOp = TI->getOperand(0);
349  OtherOpT = TI->getOperand(1);
350  OtherOpF = FI->getOperand(1);
351  MatchIsOpZero = true;
352  } else if (TI->getOperand(1) == FI->getOperand(1)) {
353  MatchOp = TI->getOperand(1);
354  OtherOpT = TI->getOperand(0);
355  OtherOpF = FI->getOperand(0);
356  MatchIsOpZero = false;
357  } else if (!TI->isCommutative()) {
358  return nullptr;
359  } else if (TI->getOperand(0) == FI->getOperand(1)) {
360  MatchOp = TI->getOperand(0);
361  OtherOpT = TI->getOperand(1);
362  OtherOpF = FI->getOperand(0);
363  MatchIsOpZero = true;
364  } else if (TI->getOperand(1) == FI->getOperand(0)) {
365  MatchOp = TI->getOperand(1);
366  OtherOpT = TI->getOperand(0);
367  OtherOpF = FI->getOperand(1);
368  MatchIsOpZero = true;
369  } else {
370  return nullptr;
371  }
372 
373  // If the select condition is a vector, the operands of the original select's
374  // operands also must be vectors. This may not be the case for getelementptr
375  // for example.
376  if (SI.getCondition()->getType()->isVectorTy() &&
377  (!OtherOpT->getType()->isVectorTy() ||
378  !OtherOpF->getType()->isVectorTy()))
379  return nullptr;
380 
381  // If we reach here, they do have operations in common.
382  Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
383  SI.getName() + ".v", &SI);
384  Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
385  Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
386  if (auto *BO = dyn_cast<BinaryOperator>(TI)) {
387  BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
388  NewBO->copyIRFlags(TI);
389  NewBO->andIRFlags(FI);
390  return NewBO;
391  }
392  if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) {
393  auto *FGEP = cast<GetElementPtrInst>(FI);
394  Type *ElementType = TGEP->getResultElementType();
395  return TGEP->isInBounds() && FGEP->isInBounds()
396  ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1})
397  : GetElementPtrInst::Create(ElementType, Op0, {Op1});
398  }
399  llvm_unreachable("Expected BinaryOperator or GEP");
400  return nullptr;
401 }
402 
403 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
404  if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
405  return false;
406  return C1I.isOneValue() || C1I.isAllOnesValue() ||
407  C2I.isOneValue() || C2I.isAllOnesValue();
408 }
409 
410 /// Try to fold the select into one of the operands to allow further
411 /// optimization.
412 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
413  Value *FalseVal) {
414  // See the comment above GetSelectFoldableOperands for a description of the
415  // transformation we are doing here.
416  if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
417  if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
418  if (unsigned SFO = getSelectFoldableOperands(TVI)) {
419  unsigned OpToFold = 0;
420  if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
421  OpToFold = 1;
422  } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
423  OpToFold = 2;
424  }
425 
426  if (OpToFold) {
428  Value *OOp = TVI->getOperand(2-OpToFold);
429  // Avoid creating select between 2 constants unless it's selecting
430  // between 0, 1 and -1.
431  const APInt *OOpC;
432  bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
433  if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
434  Value *C = ConstantInt::get(OOp->getType(), CI);
435  Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
436  NewSel->takeName(TVI);
437  BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
438  FalseVal, NewSel);
439  BO->copyIRFlags(TVI);
440  return BO;
441  }
442  }
443  }
444  }
445  }
446 
447  if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
448  if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
449  if (unsigned SFO = getSelectFoldableOperands(FVI)) {
450  unsigned OpToFold = 0;
451  if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
452  OpToFold = 1;
453  } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
454  OpToFold = 2;
455  }
456 
457  if (OpToFold) {
459  Value *OOp = FVI->getOperand(2-OpToFold);
460  // Avoid creating select between 2 constants unless it's selecting
461  // between 0, 1 and -1.
462  const APInt *OOpC;
463  bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
464  if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
465  Value *C = ConstantInt::get(OOp->getType(), CI);
466  Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
467  NewSel->takeName(FVI);
468  BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
469  TrueVal, NewSel);
470  BO->copyIRFlags(FVI);
471  return BO;
472  }
473  }
474  }
475  }
476  }
477 
478  return nullptr;
479 }
480 
481 /// We want to turn:
482 /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1)
483 /// into:
484 /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0)
485 /// Note:
486 /// Z may be 0 if lshr is missing.
487 /// Worst-case scenario is that we will replace 5 instructions with 5 different
488 /// instructions, but we got rid of select.
489 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp,
490  Value *TVal, Value *FVal,
491  InstCombiner::BuilderTy &Builder) {
492  if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() &&
493  Cmp->getPredicate() == ICmpInst::ICMP_EQ &&
494  match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One())))
495  return nullptr;
496 
497  // The TrueVal has general form of: and %B, 1
498  Value *B;
499  if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One()))))
500  return nullptr;
501 
502  // Where %B may be optionally shifted: lshr %X, %Z.
503  Value *X, *Z;
504  const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z))));
505  if (!HasShift)
506  X = B;
507 
508  Value *Y;
509  if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y))))
510  return nullptr;
511 
512  // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0
513  // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0
514  Constant *One = ConstantInt::get(SelType, 1);
515  Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One;
516  Value *FullMask = Builder.CreateOr(Y, MaskB);
517  Value *MaskedX = Builder.CreateAnd(X, FullMask);
518  Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX);
519  return new ZExtInst(ICmpNeZero, SelType);
520 }
521 
522 /// We want to turn:
523 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
524 /// into:
525 /// (or (shl (and X, C1), C3), Y)
526 /// iff:
527 /// C1 and C2 are both powers of 2
528 /// where:
529 /// C3 = Log(C2) - Log(C1)
530 ///
531 /// This transform handles cases where:
532 /// 1. The icmp predicate is inverted
533 /// 2. The select operands are reversed
534 /// 3. The magnitude of C2 and C1 are flipped
535 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
536  Value *FalseVal,
537  InstCombiner::BuilderTy &Builder) {
538  // Only handle integer compares. Also, if this is a vector select, we need a
539  // vector compare.
540  if (!TrueVal->getType()->isIntOrIntVectorTy() ||
541  TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
542  return nullptr;
543 
544  Value *CmpLHS = IC->getOperand(0);
545  Value *CmpRHS = IC->getOperand(1);
546 
547  Value *V;
548  unsigned C1Log;
549  bool IsEqualZero;
550  bool NeedAnd = false;
551  if (IC->isEquality()) {
552  if (!match(CmpRHS, m_Zero()))
553  return nullptr;
554 
555  const APInt *C1;
556  if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
557  return nullptr;
558 
559  V = CmpLHS;
560  C1Log = C1->logBase2();
561  IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
562  } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
563  IC->getPredicate() == ICmpInst::ICMP_SGT) {
564  // We also need to recognize (icmp slt (trunc (X)), 0) and
565  // (icmp sgt (trunc (X)), -1).
566  IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
567  if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
568  (!IsEqualZero && !match(CmpRHS, m_Zero())))
569  return nullptr;
570 
571  if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
572  return nullptr;
573 
574  C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
575  NeedAnd = true;
576  } else {
577  return nullptr;
578  }
579 
580  const APInt *C2;
581  bool OrOnTrueVal = false;
582  bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
583  if (!OrOnFalseVal)
584  OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
585 
586  if (!OrOnFalseVal && !OrOnTrueVal)
587  return nullptr;
588 
589  Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
590 
591  unsigned C2Log = C2->logBase2();
592 
593  bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
594  bool NeedShift = C1Log != C2Log;
595  bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
597 
598  // Make sure we don't create more instructions than we save.
599  Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
600  if ((NeedShift + NeedXor + NeedZExtTrunc) >
601  (IC->hasOneUse() + Or->hasOneUse()))
602  return nullptr;
603 
604  if (NeedAnd) {
605  // Insert the AND instruction on the input to the truncate.
607  V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
608  }
609 
610  if (C2Log > C1Log) {
611  V = Builder.CreateZExtOrTrunc(V, Y->getType());
612  V = Builder.CreateShl(V, C2Log - C1Log);
613  } else if (C1Log > C2Log) {
614  V = Builder.CreateLShr(V, C1Log - C2Log);
615  V = Builder.CreateZExtOrTrunc(V, Y->getType());
616  } else
617  V = Builder.CreateZExtOrTrunc(V, Y->getType());
618 
619  if (NeedXor)
620  V = Builder.CreateXor(V, *C2);
621 
622  return Builder.CreateOr(V, Y);
623 }
624 
625 /// Transform patterns such as: (a > b) ? a - b : 0
626 /// into: ((a > b) ? a : b) - b)
627 /// This produces a canonical max pattern that is more easily recognized by the
628 /// backend and converted into saturated subtraction instructions if those
629 /// exist.
630 /// There are 8 commuted/swapped variants of this pattern.
631 /// TODO: Also support a - UMIN(a,b) patterns.
633  const Value *TrueVal,
634  const Value *FalseVal,
635  InstCombiner::BuilderTy &Builder) {
636  ICmpInst::Predicate Pred = ICI->getPredicate();
637  if (!ICmpInst::isUnsigned(Pred))
638  return nullptr;
639 
640  // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0
641  if (match(TrueVal, m_Zero())) {
642  Pred = ICmpInst::getInversePredicate(Pred);
643  std::swap(TrueVal, FalseVal);
644  }
645  if (!match(FalseVal, m_Zero()))
646  return nullptr;
647 
648  Value *A = ICI->getOperand(0);
649  Value *B = ICI->getOperand(1);
650  if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) {
651  // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0
652  std::swap(A, B);
653  Pred = ICmpInst::getSwappedPredicate(Pred);
654  }
655 
656  assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) &&
657  "Unexpected isUnsigned predicate!");
658 
659  // Account for swapped form of subtraction: ((a > b) ? b - a : 0).
660  bool IsNegative = false;
661  if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A))))
662  IsNegative = true;
663  else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B))))
664  return nullptr;
665 
666  // If sub is used anywhere else, we wouldn't be able to eliminate it
667  // afterwards.
668  if (!TrueVal->hasOneUse())
669  return nullptr;
670 
671  // All checks passed, convert to canonical unsigned saturated subtraction
672  // form: sub(max()).
673  // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b)
674  Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
675  return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B);
676 }
677 
678 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal,
679  InstCombiner::BuilderTy &Builder) {
680  if (!Cmp->hasOneUse())
681  return nullptr;
682 
683  // Match unsigned saturated add with constant.
684  Value *Cmp0 = Cmp->getOperand(0);
685  Value *Cmp1 = Cmp->getOperand(1);
686  ICmpInst::Predicate Pred = Cmp->getPredicate();
687  Value *X;
688  const APInt *C, *CmpC;
689  if (Pred == ICmpInst::ICMP_ULT &&
690  match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 &&
691  match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) {
692  // Commute compare predicate and select operands:
693  // (X u< ~C) ? (X + C) : -1 --> (X u> ~C) ? -1 : (X + C)
694  Value *NewCmp = Builder.CreateICmp(ICmpInst::ICMP_UGT, X, Cmp1);
695  return Builder.CreateSelect(NewCmp, FVal, TVal);
696  }
697 
698  // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
699  // There are 8 commuted variants.
700  // Canonicalize -1 (saturated result) to true value of the select.
701  if (match(FVal, m_AllOnes())) {
702  std::swap(TVal, FVal);
703  std::swap(Cmp0, Cmp1);
704  }
705  if (!match(TVal, m_AllOnes()))
706  return nullptr;
707 
708  // Canonicalize predicate to 'ULT'.
709  if (Pred == ICmpInst::ICMP_UGT) {
710  Pred = ICmpInst::ICMP_ULT;
711  std::swap(Cmp0, Cmp1);
712  }
713  if (Pred != ICmpInst::ICMP_ULT)
714  return nullptr;
715 
716  // Match unsigned saturated add of 2 variables with an unnecessary 'not'.
717  Value *Y;
718  if (match(Cmp0, m_Not(m_Value(X))) &&
719  match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) {
720  // Change the comparison to use the sum (false value of the select). That is
721  // a canonical pattern match form for uadd.with.overflow and eliminates a
722  // use of the 'not' op:
723  // (~X u< Y) ? -1 : (X + Y) --> ((X + Y) u< Y) ? -1 : (X + Y)
724  // (~X u< Y) ? -1 : (Y + X) --> ((Y + X) u< Y) ? -1 : (Y + X)
725  Value *NewCmp = Builder.CreateICmp(ICmpInst::ICMP_ULT, FVal, Y);
726  return Builder.CreateSelect(NewCmp, TVal, FVal);
727  }
728 
729  return nullptr;
730 }
731 
732 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
733 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
734 ///
735 /// For example, we can fold the following code sequence:
736 /// \code
737 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
738 /// %1 = icmp ne i32 %x, 0
739 /// %2 = select i1 %1, i32 %0, i32 32
740 /// \code
741 ///
742 /// into:
743 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
744 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
745  InstCombiner::BuilderTy &Builder) {
746  ICmpInst::Predicate Pred = ICI->getPredicate();
747  Value *CmpLHS = ICI->getOperand(0);
748  Value *CmpRHS = ICI->getOperand(1);
749 
750  // Check if the condition value compares a value for equality against zero.
751  if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
752  return nullptr;
753 
754  Value *Count = FalseVal;
755  Value *ValueOnZero = TrueVal;
756  if (Pred == ICmpInst::ICMP_NE)
757  std::swap(Count, ValueOnZero);
758 
759  // Skip zero extend/truncate.
760  Value *V = nullptr;
761  if (match(Count, m_ZExt(m_Value(V))) ||
762  match(Count, m_Trunc(m_Value(V))))
763  Count = V;
764 
765  // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
766  // input to the cttz/ctlz is used as LHS for the compare instruction.
767  if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) &&
768  !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS))))
769  return nullptr;
770 
771  IntrinsicInst *II = cast<IntrinsicInst>(Count);
772 
773  // Check if the value propagated on zero is a constant number equal to the
774  // sizeof in bits of 'Count'.
775  unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
776  if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) {
777  // Explicitly clear the 'undef_on_zero' flag.
778  IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
780  Builder.Insert(NewI);
781  return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
782  }
783 
784  // If the ValueOnZero is not the bitwidth, we can at least make use of the
785  // fact that the cttz/ctlz result will not be used if the input is zero, so
786  // it's okay to relax it to undef for that case.
787  if (II->hasOneUse() && !match(II->getArgOperand(1), m_One()))
789 
790  return nullptr;
791 }
792 
793 /// Return true if we find and adjust an icmp+select pattern where the compare
794 /// is with a constant that can be incremented or decremented to match the
795 /// minimum or maximum idiom.
796 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
797  ICmpInst::Predicate Pred = Cmp.getPredicate();
798  Value *CmpLHS = Cmp.getOperand(0);
799  Value *CmpRHS = Cmp.getOperand(1);
800  Value *TrueVal = Sel.getTrueValue();
801  Value *FalseVal = Sel.getFalseValue();
802 
803  // We may move or edit the compare, so make sure the select is the only user.
804  const APInt *CmpC;
805  if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
806  return false;
807 
808  // These transforms only work for selects of integers or vector selects of
809  // integer vectors.
810  Type *SelTy = Sel.getType();
811  auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
812  if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
813  return false;
814 
815  Constant *AdjustedRHS;
816  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
817  AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
818  else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
819  AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
820  else
821  return false;
822 
823  // X > C ? X : C+1 --> X < C+1 ? C+1 : X
824  // X < C ? X : C-1 --> X > C-1 ? C-1 : X
825  if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
826  (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
827  ; // Nothing to do here. Values match without any sign/zero extension.
828  }
829  // Types do not match. Instead of calculating this with mixed types, promote
830  // all to the larger type. This enables scalar evolution to analyze this
831  // expression.
832  else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
833  Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
834 
835  // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
836  // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
837  // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
838  // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
839  if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
840  CmpLHS = TrueVal;
841  AdjustedRHS = SextRHS;
842  } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
843  SextRHS == TrueVal) {
844  CmpLHS = FalseVal;
845  AdjustedRHS = SextRHS;
846  } else if (Cmp.isUnsigned()) {
847  Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
848  // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
849  // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
850  // zext + signed compare cannot be changed:
851  // 0xff <s 0x00, but 0x00ff >s 0x0000
852  if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
853  CmpLHS = TrueVal;
854  AdjustedRHS = ZextRHS;
855  } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
856  ZextRHS == TrueVal) {
857  CmpLHS = FalseVal;
858  AdjustedRHS = ZextRHS;
859  } else {
860  return false;
861  }
862  } else {
863  return false;
864  }
865  } else {
866  return false;
867  }
868 
869  Pred = ICmpInst::getSwappedPredicate(Pred);
870  CmpRHS = AdjustedRHS;
871  std::swap(FalseVal, TrueVal);
872  Cmp.setPredicate(Pred);
873  Cmp.setOperand(0, CmpLHS);
874  Cmp.setOperand(1, CmpRHS);
875  Sel.setOperand(1, TrueVal);
876  Sel.setOperand(2, FalseVal);
877  Sel.swapProfMetadata();
878 
879  // Move the compare instruction right before the select instruction. Otherwise
880  // the sext/zext value may be defined after the compare instruction uses it.
881  Cmp.moveBefore(&Sel);
882 
883  return true;
884 }
885 
886 /// If this is an integer min/max (icmp + select) with a constant operand,
887 /// create the canonical icmp for the min/max operation and canonicalize the
888 /// constant to the 'false' operand of the select:
889 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
890 /// Note: if C1 != C2, this will change the icmp constant to the existing
891 /// constant operand of the select.
892 static Instruction *
893 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
894  InstCombiner::BuilderTy &Builder) {
895  if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
896  return nullptr;
897 
898  // Canonicalize the compare predicate based on whether we have min or max.
899  Value *LHS, *RHS;
900  SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
902  return nullptr;
903 
904  // Is this already canonical?
905  ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor);
906  if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
907  Cmp.getPredicate() == CanonicalPred)
908  return nullptr;
909 
910  // Create the canonical compare and plug it into the select.
911  Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS));
912 
913  // If the select operands did not change, we're done.
914  if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
915  return &Sel;
916 
917  // If we are swapping the select operands, swap the metadata too.
918  assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
919  "Unexpected results from matchSelectPattern");
920  Sel.setTrueValue(LHS);
921  Sel.setFalseValue(RHS);
922  Sel.swapProfMetadata();
923  return &Sel;
924 }
925 
926 /// There are many select variants for each of ABS/NABS.
927 /// In matchSelectPattern(), there are different compare constants, compare
928 /// predicates/operands and select operands.
929 /// In isKnownNegation(), there are different formats of negated operands.
930 /// Canonicalize all these variants to 1 pattern.
931 /// This makes CSE more likely.
932 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp,
933  InstCombiner::BuilderTy &Builder) {
934  if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
935  return nullptr;
936 
937  // Choose a sign-bit check for the compare (likely simpler for codegen).
938  // ABS: (X <s 0) ? -X : X
939  // NABS: (X <s 0) ? X : -X
940  Value *LHS, *RHS;
941  SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor;
942  if (SPF != SelectPatternFlavor::SPF_ABS &&
944  return nullptr;
945 
946  Value *TVal = Sel.getTrueValue();
947  Value *FVal = Sel.getFalseValue();
948  assert(isKnownNegation(TVal, FVal) &&
949  "Unexpected result from matchSelectPattern");
950 
951  // The compare may use the negated abs()/nabs() operand, or it may use
952  // negation in non-canonical form such as: sub A, B.
953  bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) ||
954  match(Cmp.getOperand(0), m_Neg(m_Specific(FVal)));
955 
956  bool CmpCanonicalized = !CmpUsesNegatedOp &&
957  match(Cmp.getOperand(1), m_ZeroInt()) &&
959  bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS)));
960 
961  // Is this already canonical?
962  if (CmpCanonicalized && RHSCanonicalized)
963  return nullptr;
964 
965  // If RHS is used by other instructions except compare and select, don't
966  // canonicalize it to not increase the instruction count.
967  if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp)))
968  return nullptr;
969 
970  // Create the canonical compare: icmp slt LHS 0.
971  if (!CmpCanonicalized) {
974  if (CmpUsesNegatedOp)
975  Cmp.setOperand(0, LHS);
976  }
977 
978  // Create the canonical RHS: RHS = sub (0, LHS).
979  if (!RHSCanonicalized) {
980  assert(RHS->hasOneUse() && "RHS use number is not right");
981  RHS = Builder.CreateNeg(LHS);
982  if (TVal == LHS) {
983  Sel.setFalseValue(RHS);
984  FVal = RHS;
985  } else {
986  Sel.setTrueValue(RHS);
987  TVal = RHS;
988  }
989  }
990 
991  // If the select operands do not change, we're done.
992  if (SPF == SelectPatternFlavor::SPF_NABS) {
993  if (TVal == LHS)
994  return &Sel;
995  assert(FVal == LHS && "Unexpected results from matchSelectPattern");
996  } else {
997  if (FVal == LHS)
998  return &Sel;
999  assert(TVal == LHS && "Unexpected results from matchSelectPattern");
1000  }
1001 
1002  // We are swapping the select operands, so swap the metadata too.
1003  Sel.setTrueValue(FVal);
1004  Sel.setFalseValue(TVal);
1005  Sel.swapProfMetadata();
1006  return &Sel;
1007 }
1008 
1009 /// Visit a SelectInst that has an ICmpInst as its first operand.
1010 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
1011  ICmpInst *ICI) {
1012  Value *TrueVal = SI.getTrueValue();
1013  Value *FalseVal = SI.getFalseValue();
1014 
1015  if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
1016  return NewSel;
1017 
1018  if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder))
1019  return NewAbs;
1020 
1021  bool Changed = adjustMinMax(SI, *ICI);
1022 
1023  if (Value *V = foldSelectICmpAnd(SI, ICI, Builder))
1024  return replaceInstUsesWith(SI, V);
1025 
1026  // NOTE: if we wanted to, this is where to detect integer MIN/MAX
1027  ICmpInst::Predicate Pred = ICI->getPredicate();
1028  Value *CmpLHS = ICI->getOperand(0);
1029  Value *CmpRHS = ICI->getOperand(1);
1030  if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
1031  if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
1032  // Transform (X == C) ? X : Y -> (X == C) ? C : Y
1033  SI.setOperand(1, CmpRHS);
1034  Changed = true;
1035  } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
1036  // Transform (X != C) ? Y : X -> (X != C) ? Y : C
1037  SI.setOperand(2, CmpRHS);
1038  Changed = true;
1039  }
1040  }
1041 
1042  // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
1043  // decomposeBitTestICmp() might help.
1044  {
1045  unsigned BitWidth =
1046  DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
1047  APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
1048  Value *X;
1049  const APInt *Y, *C;
1050  bool TrueWhenUnset;
1051  bool IsBitTest = false;
1052  if (ICmpInst::isEquality(Pred) &&
1053  match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
1054  match(CmpRHS, m_Zero())) {
1055  IsBitTest = true;
1056  TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
1057  } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
1058  X = CmpLHS;
1059  Y = &MinSignedValue;
1060  IsBitTest = true;
1061  TrueWhenUnset = false;
1062  } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
1063  X = CmpLHS;
1064  Y = &MinSignedValue;
1065  IsBitTest = true;
1066  TrueWhenUnset = true;
1067  }
1068  if (IsBitTest) {
1069  Value *V = nullptr;
1070  // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
1071  if (TrueWhenUnset && TrueVal == X &&
1072  match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1073  V = Builder.CreateAnd(X, ~(*Y));
1074  // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
1075  else if (!TrueWhenUnset && FalseVal == X &&
1076  match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1077  V = Builder.CreateAnd(X, ~(*Y));
1078  // (X & Y) == 0 ? X ^ Y : X --> X | Y
1079  else if (TrueWhenUnset && FalseVal == X &&
1080  match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1081  V = Builder.CreateOr(X, *Y);
1082  // (X & Y) != 0 ? X : X ^ Y --> X | Y
1083  else if (!TrueWhenUnset && TrueVal == X &&
1084  match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
1085  V = Builder.CreateOr(X, *Y);
1086 
1087  if (V)
1088  return replaceInstUsesWith(SI, V);
1089  }
1090  }
1091 
1092  if (Instruction *V =
1093  foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder))
1094  return V;
1095 
1096  if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
1097  return replaceInstUsesWith(SI, V);
1098 
1099  if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
1100  return replaceInstUsesWith(SI, V);
1101 
1102  if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder))
1103  return replaceInstUsesWith(SI, V);
1104 
1105  if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder))
1106  return replaceInstUsesWith(SI, V);
1107 
1108  return Changed ? &SI : nullptr;
1109 }
1110 
1111 /// SI is a select whose condition is a PHI node (but the two may be in
1112 /// different blocks). See if the true/false values (V) are live in all of the
1113 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
1114 ///
1115 /// X = phi [ C1, BB1], [C2, BB2]
1116 /// Y = add
1117 /// Z = select X, Y, 0
1118 ///
1119 /// because Y is not live in BB1/BB2.
1120 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
1121  const SelectInst &SI) {
1122  // If the value is a non-instruction value like a constant or argument, it
1123  // can always be mapped.
1124  const Instruction *I = dyn_cast<Instruction>(V);
1125  if (!I) return true;
1126 
1127  // If V is a PHI node defined in the same block as the condition PHI, we can
1128  // map the arguments.
1129  const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
1130 
1131  if (const PHINode *VP = dyn_cast<PHINode>(I))
1132  if (VP->getParent() == CondPHI->getParent())
1133  return true;
1134 
1135  // Otherwise, if the PHI and select are defined in the same block and if V is
1136  // defined in a different block, then we can transform it.
1137  if (SI.getParent() == CondPHI->getParent() &&
1138  I->getParent() != CondPHI->getParent())
1139  return true;
1140 
1141  // Otherwise we have a 'hard' case and we can't tell without doing more
1142  // detailed dominator based analysis, punt.
1143  return false;
1144 }
1145 
1146 /// We have an SPF (e.g. a min or max) of an SPF of the form:
1147 /// SPF2(SPF1(A, B), C)
1148 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
1149  SelectPatternFlavor SPF1,
1150  Value *A, Value *B,
1151  Instruction &Outer,
1152  SelectPatternFlavor SPF2, Value *C) {
1153  if (Outer.getType() != Inner->getType())
1154  return nullptr;
1155 
1156  if (C == A || C == B) {
1157  // MAX(MAX(A, B), B) -> MAX(A, B)
1158  // MIN(MIN(a, b), a) -> MIN(a, b)
1159  // TODO: This could be done in instsimplify.
1160  if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1))
1161  return replaceInstUsesWith(Outer, Inner);
1162 
1163  // MAX(MIN(a, b), a) -> a
1164  // MIN(MAX(a, b), a) -> a
1165  // TODO: This could be done in instsimplify.
1166  if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
1167  (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
1168  (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
1169  (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
1170  return replaceInstUsesWith(Outer, C);
1171  }
1172 
1173  if (SPF1 == SPF2) {
1174  const APInt *CB, *CC;
1175  if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
1176  // MIN(MIN(A, 23), 97) -> MIN(A, 23)
1177  // MAX(MAX(A, 97), 23) -> MAX(A, 97)
1178  // TODO: This could be done in instsimplify.
1179  if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
1180  (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
1181  (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
1182  (SPF1 == SPF_SMAX && CB->sge(*CC)))
1183  return replaceInstUsesWith(Outer, Inner);
1184 
1185  // MIN(MIN(A, 97), 23) -> MIN(A, 23)
1186  // MAX(MAX(A, 23), 97) -> MAX(A, 97)
1187  if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
1188  (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
1189  (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
1190  (SPF1 == SPF_SMAX && CB->slt(*CC))) {
1191  Outer.replaceUsesOfWith(Inner, A);
1192  return &Outer;
1193  }
1194  }
1195  }
1196 
1197  // ABS(ABS(X)) -> ABS(X)
1198  // NABS(NABS(X)) -> NABS(X)
1199  // TODO: This could be done in instsimplify.
1200  if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
1201  return replaceInstUsesWith(Outer, Inner);
1202  }
1203 
1204  // ABS(NABS(X)) -> ABS(X)
1205  // NABS(ABS(X)) -> NABS(X)
1206  if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
1207  (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
1208  SelectInst *SI = cast<SelectInst>(Inner);
1209  Value *NewSI =
1210  Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
1211  SI->getTrueValue(), SI->getName(), SI);
1212  return replaceInstUsesWith(Outer, NewSI);
1213  }
1214 
1215  auto IsFreeOrProfitableToInvert =
1216  [&](Value *V, Value *&NotV, bool &ElidesXor) {
1217  if (match(V, m_Not(m_Value(NotV)))) {
1218  // If V has at most 2 uses then we can get rid of the xor operation
1219  // entirely.
1220  ElidesXor |= !V->hasNUsesOrMore(3);
1221  return true;
1222  }
1223 
1224  if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
1225  NotV = nullptr;
1226  return true;
1227  }
1228 
1229  return false;
1230  };
1231 
1232  Value *NotA, *NotB, *NotC;
1233  bool ElidesXor = false;
1234 
1235  // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
1236  // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
1237  // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
1238  // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
1239  //
1240  // This transform is performance neutral if we can elide at least one xor from
1241  // the set of three operands, since we'll be tacking on an xor at the very
1242  // end.
1243  if (SelectPatternResult::isMinOrMax(SPF1) &&
1245  IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
1246  IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
1247  IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
1248  if (!NotA)
1249  NotA = Builder.CreateNot(A);
1250  if (!NotB)
1251  NotB = Builder.CreateNot(B);
1252  if (!NotC)
1253  NotC = Builder.CreateNot(C);
1254 
1255  Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA,
1256  NotB);
1257  Value *NewOuter = Builder.CreateNot(
1258  createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC));
1259  return replaceInstUsesWith(Outer, NewOuter);
1260  }
1261 
1262  return nullptr;
1263 }
1264 
1265 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
1266 /// This is even legal for FP.
1267 static Instruction *foldAddSubSelect(SelectInst &SI,
1268  InstCombiner::BuilderTy &Builder) {
1269  Value *CondVal = SI.getCondition();
1270  Value *TrueVal = SI.getTrueValue();
1271  Value *FalseVal = SI.getFalseValue();
1272  auto *TI = dyn_cast<Instruction>(TrueVal);
1273  auto *FI = dyn_cast<Instruction>(FalseVal);
1274  if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
1275  return nullptr;
1276 
1277  Instruction *AddOp = nullptr, *SubOp = nullptr;
1278  if ((TI->getOpcode() == Instruction::Sub &&
1279  FI->getOpcode() == Instruction::Add) ||
1280  (TI->getOpcode() == Instruction::FSub &&
1281  FI->getOpcode() == Instruction::FAdd)) {
1282  AddOp = FI;
1283  SubOp = TI;
1284  } else if ((FI->getOpcode() == Instruction::Sub &&
1285  TI->getOpcode() == Instruction::Add) ||
1286  (FI->getOpcode() == Instruction::FSub &&
1287  TI->getOpcode() == Instruction::FAdd)) {
1288  AddOp = TI;
1289  SubOp = FI;
1290  }
1291 
1292  if (AddOp) {
1293  Value *OtherAddOp = nullptr;
1294  if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1295  OtherAddOp = AddOp->getOperand(1);
1296  } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1297  OtherAddOp = AddOp->getOperand(0);
1298  }
1299 
1300  if (OtherAddOp) {
1301  // So at this point we know we have (Y -> OtherAddOp):
1302  // select C, (add X, Y), (sub X, Z)
1303  Value *NegVal; // Compute -Z
1304  if (SI.getType()->isFPOrFPVectorTy()) {
1305  NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1306  if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1307  FastMathFlags Flags = AddOp->getFastMathFlags();
1308  Flags &= SubOp->getFastMathFlags();
1309  NegInst->setFastMathFlags(Flags);
1310  }
1311  } else {
1312  NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1313  }
1314 
1315  Value *NewTrueOp = OtherAddOp;
1316  Value *NewFalseOp = NegVal;
1317  if (AddOp != TI)
1318  std::swap(NewTrueOp, NewFalseOp);
1319  Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1320  SI.getName() + ".p", &SI);
1321 
1322  if (SI.getType()->isFPOrFPVectorTy()) {
1323  Instruction *RI =
1324  BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1325 
1326  FastMathFlags Flags = AddOp->getFastMathFlags();
1327  Flags &= SubOp->getFastMathFlags();
1328  RI->setFastMathFlags(Flags);
1329  return RI;
1330  } else
1331  return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1332  }
1333  }
1334  return nullptr;
1335 }
1336 
1337 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1338  Constant *C;
1339  if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1340  !match(Sel.getFalseValue(), m_Constant(C)))
1341  return nullptr;
1342 
1343  Instruction *ExtInst;
1344  if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1345  !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1346  return nullptr;
1347 
1348  auto ExtOpcode = ExtInst->getOpcode();
1349  if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1350  return nullptr;
1351 
1352  // If we are extending from a boolean type or if we can create a select that
1353  // has the same size operands as its condition, try to narrow the select.
1354  Value *X = ExtInst->getOperand(0);
1355  Type *SmallType = X->getType();
1356  Value *Cond = Sel.getCondition();
1357  auto *Cmp = dyn_cast<CmpInst>(Cond);
1358  if (!SmallType->isIntOrIntVectorTy(1) &&
1359  (!Cmp || Cmp->getOperand(0)->getType() != SmallType))
1360  return nullptr;
1361 
1362  // If the constant is the same after truncation to the smaller type and
1363  // extension to the original type, we can narrow the select.
1364  Type *SelType = Sel.getType();
1365  Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1366  Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1367  if (ExtC == C) {
1368  Value *TruncCVal = cast<Value>(TruncC);
1369  if (ExtInst == Sel.getFalseValue())
1370  std::swap(X, TruncCVal);
1371 
1372  // select Cond, (ext X), C --> ext(select Cond, X, C')
1373  // select Cond, C, (ext X) --> ext(select Cond, C', X)
1374  Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1375  return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1376  }
1377 
1378  // If one arm of the select is the extend of the condition, replace that arm
1379  // with the extension of the appropriate known bool value.
1380  if (Cond == X) {
1381  if (ExtInst == Sel.getTrueValue()) {
1382  // select X, (sext X), C --> select X, -1, C
1383  // select X, (zext X), C --> select X, 1, C
1384  Constant *One = ConstantInt::getTrue(SmallType);
1385  Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1386  return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1387  } else {
1388  // select X, C, (sext X) --> select X, C, 0
1389  // select X, C, (zext X) --> select X, C, 0
1390  Constant *Zero = ConstantInt::getNullValue(SelType);
1391  return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1392  }
1393  }
1394 
1395  return nullptr;
1396 }
1397 
1398 /// Try to transform a vector select with a constant condition vector into a
1399 /// shuffle for easier combining with other shuffles and insert/extract.
1400 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1401  Value *CondVal = SI.getCondition();
1402  Constant *CondC;
1403  if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1404  return nullptr;
1405 
1406  unsigned NumElts = CondVal->getType()->getVectorNumElements();
1408  Mask.reserve(NumElts);
1409  Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1410  for (unsigned i = 0; i != NumElts; ++i) {
1411  Constant *Elt = CondC->getAggregateElement(i);
1412  if (!Elt)
1413  return nullptr;
1414 
1415  if (Elt->isOneValue()) {
1416  // If the select condition element is true, choose from the 1st vector.
1417  Mask.push_back(ConstantInt::get(Int32Ty, i));
1418  } else if (Elt->isNullValue()) {
1419  // If the select condition element is false, choose from the 2nd vector.
1420  Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1421  } else if (isa<UndefValue>(Elt)) {
1422  // Undef in a select condition (choose one of the operands) does not mean
1423  // the same thing as undef in a shuffle mask (any value is acceptable), so
1424  // give up.
1425  return nullptr;
1426  } else {
1427  // Bail out on a constant expression.
1428  return nullptr;
1429  }
1430  }
1431 
1432  return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1433  ConstantVector::get(Mask));
1434 }
1435 
1436 /// Reuse bitcasted operands between a compare and select:
1437 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1438 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1439 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1440  InstCombiner::BuilderTy &Builder) {
1441  Value *Cond = Sel.getCondition();
1442  Value *TVal = Sel.getTrueValue();
1443  Value *FVal = Sel.getFalseValue();
1444 
1445  CmpInst::Predicate Pred;
1446  Value *A, *B;
1447  if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1448  return nullptr;
1449 
1450  // The select condition is a compare instruction. If the select's true/false
1451  // values are already the same as the compare operands, there's nothing to do.
1452  if (TVal == A || TVal == B || FVal == A || FVal == B)
1453  return nullptr;
1454 
1455  Value *C, *D;
1456  if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1457  return nullptr;
1458 
1459  // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1460  Value *TSrc, *FSrc;
1461  if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1462  !match(FVal, m_BitCast(m_Value(FSrc))))
1463  return nullptr;
1464 
1465  // If the select true/false values are *different bitcasts* of the same source
1466  // operands, make the select operands the same as the compare operands and
1467  // cast the result. This is the canonical select form for min/max.
1468  Value *NewSel;
1469  if (TSrc == C && FSrc == D) {
1470  // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1471  // bitcast (select (cmp A, B), A, B)
1472  NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1473  } else if (TSrc == D && FSrc == C) {
1474  // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1475  // bitcast (select (cmp A, B), B, A)
1476  NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1477  } else {
1478  return nullptr;
1479  }
1480  return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1481 }
1482 
1483 /// Try to eliminate select instructions that test the returned flag of cmpxchg
1484 /// instructions.
1485 ///
1486 /// If a select instruction tests the returned flag of a cmpxchg instruction and
1487 /// selects between the returned value of the cmpxchg instruction its compare
1488 /// operand, the result of the select will always be equal to its false value.
1489 /// For example:
1490 ///
1491 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1492 /// %1 = extractvalue { i64, i1 } %0, 1
1493 /// %2 = extractvalue { i64, i1 } %0, 0
1494 /// %3 = select i1 %1, i64 %compare, i64 %2
1495 /// ret i64 %3
1496 ///
1497 /// The returned value of the cmpxchg instruction (%2) is the original value
1498 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2
1499 /// must have been equal to %compare. Thus, the result of the select is always
1500 /// equal to %2, and the code can be simplified to:
1501 ///
1502 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst
1503 /// %1 = extractvalue { i64, i1 } %0, 0
1504 /// ret i64 %1
1505 ///
1506 static Instruction *foldSelectCmpXchg(SelectInst &SI) {
1507  // A helper that determines if V is an extractvalue instruction whose
1508  // aggregate operand is a cmpxchg instruction and whose single index is equal
1509  // to I. If such conditions are true, the helper returns the cmpxchg
1510  // instruction; otherwise, a nullptr is returned.
1511  auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * {
1512  auto *Extract = dyn_cast<ExtractValueInst>(V);
1513  if (!Extract)
1514  return nullptr;
1515  if (Extract->getIndices()[0] != I)
1516  return nullptr;
1517  return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand());
1518  };
1519 
1520  // If the select has a single user, and this user is a select instruction that
1521  // we can simplify, skip the cmpxchg simplification for now.
1522  if (SI.hasOneUse())
1523  if (auto *Select = dyn_cast<SelectInst>(SI.user_back()))
1524  if (Select->getCondition() == SI.getCondition())
1525  if (Select->getFalseValue() == SI.getTrueValue() ||
1526  Select->getTrueValue() == SI.getFalseValue())
1527  return nullptr;
1528 
1529  // Ensure the select condition is the returned flag of a cmpxchg instruction.
1530  auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1);
1531  if (!CmpXchg)
1532  return nullptr;
1533 
1534  // Check the true value case: The true value of the select is the returned
1535  // value of the same cmpxchg used by the condition, and the false value is the
1536  // cmpxchg instruction's compare operand.
1537  if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0))
1538  if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) {
1539  SI.setTrueValue(SI.getFalseValue());
1540  return &SI;
1541  }
1542 
1543  // Check the false value case: The false value of the select is the returned
1544  // value of the same cmpxchg used by the condition, and the true value is the
1545  // cmpxchg instruction's compare operand.
1546  if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0))
1547  if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) {
1548  SI.setTrueValue(SI.getFalseValue());
1549  return &SI;
1550  }
1551 
1552  return nullptr;
1553 }
1554 
1555 /// Reduce a sequence of min/max with a common operand.
1556 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS,
1557  Value *RHS,
1558  InstCombiner::BuilderTy &Builder) {
1559  assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max");
1560  // TODO: Allow FP min/max with nnan/nsz.
1561  if (!LHS->getType()->isIntOrIntVectorTy())
1562  return nullptr;
1563 
1564  // Match 3 of the same min/max ops. Example: umin(umin(), umin()).
1565  Value *A, *B, *C, *D;
1566  SelectPatternResult L = matchSelectPattern(LHS, A, B);
1567  SelectPatternResult R = matchSelectPattern(RHS, C, D);
1568  if (SPF != L.Flavor || L.Flavor != R.Flavor)
1569  return nullptr;
1570 
1571  // Look for a common operand. The use checks are different than usual because
1572  // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by
1573  // the select.
1574  Value *MinMaxOp = nullptr;
1575  Value *ThirdOp = nullptr;
1576  if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) {
1577  // If the LHS is only used in this chain and the RHS is used outside of it,
1578  // reuse the RHS min/max because that will eliminate the LHS.
1579  if (D == A || C == A) {
1580  // min(min(a, b), min(c, a)) --> min(min(c, a), b)
1581  // min(min(a, b), min(a, d)) --> min(min(a, d), b)
1582  MinMaxOp = RHS;
1583  ThirdOp = B;
1584  } else if (D == B || C == B) {
1585  // min(min(a, b), min(c, b)) --> min(min(c, b), a)
1586  // min(min(a, b), min(b, d)) --> min(min(b, d), a)
1587  MinMaxOp = RHS;
1588  ThirdOp = A;
1589  }
1590  } else if (!RHS->hasNUsesOrMore(3)) {
1591  // Reuse the LHS. This will eliminate the RHS.
1592  if (D == A || D == B) {
1593  // min(min(a, b), min(c, a)) --> min(min(a, b), c)
1594  // min(min(a, b), min(c, b)) --> min(min(a, b), c)
1595  MinMaxOp = LHS;
1596  ThirdOp = C;
1597  } else if (C == A || C == B) {
1598  // min(min(a, b), min(b, d)) --> min(min(a, b), d)
1599  // min(min(a, b), min(c, b)) --> min(min(a, b), d)
1600  MinMaxOp = LHS;
1601  ThirdOp = D;
1602  }
1603  }
1604  if (!MinMaxOp || !ThirdOp)
1605  return nullptr;
1606 
1608  Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp);
1609  return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp);
1610 }
1611 
1612 /// Try to reduce a rotate pattern that includes a compare and select into a
1613 /// funnel shift intrinsic. Example:
1614 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b)))
1615 /// --> call llvm.fshl.i32(a, a, b)
1616 static Instruction *foldSelectRotate(SelectInst &Sel) {
1617  // The false value of the select must be a rotate of the true value.
1618  Value *Or0, *Or1;
1619  if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1)))))
1620  return nullptr;
1621 
1622  Value *TVal = Sel.getTrueValue();
1623  Value *SA0, *SA1;
1624  if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) ||
1625  !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1)))))
1626  return nullptr;
1627 
1628  auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode();
1629  auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode();
1630  if (ShiftOpcode0 == ShiftOpcode1)
1631  return nullptr;
1632 
1633  // We have one of these patterns so far:
1634  // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1))
1635  // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1))
1636  // This must be a power-of-2 rotate for a bitmasking transform to be valid.
1637  unsigned Width = Sel.getType()->getScalarSizeInBits();
1638  if (!isPowerOf2_32(Width))
1639  return nullptr;
1640 
1641  // Check the shift amounts to see if they are an opposite pair.
1642  Value *ShAmt;
1643  if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0)))))
1644  ShAmt = SA0;
1645  else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1)))))
1646  ShAmt = SA1;
1647  else
1648  return nullptr;
1649 
1650  // Finally, see if the select is filtering out a shift-by-zero.
1651  Value *Cond = Sel.getCondition();
1652  ICmpInst::Predicate Pred;
1653  if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) ||
1654  Pred != ICmpInst::ICMP_EQ)
1655  return nullptr;
1656 
1657  // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way.
1658  // Convert to funnel shift intrinsic.
1659  bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) ||
1660  (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl);
1661  Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr;
1662  Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType());
1663  return IntrinsicInst::Create(F, { TVal, TVal, ShAmt });
1664 }
1665 
1667  Value *CondVal = SI.getCondition();
1668  Value *TrueVal = SI.getTrueValue();
1669  Value *FalseVal = SI.getFalseValue();
1670  Type *SelType = SI.getType();
1671 
1672  // FIXME: Remove this workaround when freeze related patches are done.
1673  // For select with undef operand which feeds into an equality comparison,
1674  // don't simplify it so loop unswitch can know the equality comparison
1675  // may have an undef operand. This is a workaround for PR31652 caused by
1676  // descrepancy about branch on undef between LoopUnswitch and GVN.
1677  if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1678  if (llvm::any_of(SI.users(), [&](User *U) {
1679  ICmpInst *CI = dyn_cast<ICmpInst>(U);
1680  if (CI && CI->isEquality())
1681  return true;
1682  return false;
1683  })) {
1684  return nullptr;
1685  }
1686  }
1687 
1688  if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1689  SQ.getWithInstruction(&SI)))
1690  return replaceInstUsesWith(SI, V);
1691 
1692  if (Instruction *I = canonicalizeSelectToShuffle(SI))
1693  return I;
1694 
1695  // Canonicalize a one-use integer compare with a non-canonical predicate by
1696  // inverting the predicate and swapping the select operands. This matches a
1697  // compare canonicalization for conditional branches.
1698  // TODO: Should we do the same for FP compares?
1699  CmpInst::Predicate Pred;
1700  if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1701  !isCanonicalPredicate(Pred)) {
1702  // Swap true/false values and condition.
1703  CmpInst *Cond = cast<CmpInst>(CondVal);
1705  SI.setOperand(1, FalseVal);
1706  SI.setOperand(2, TrueVal);
1707  SI.swapProfMetadata();
1708  Worklist.Add(Cond);
1709  return &SI;
1710  }
1711 
1712  if (SelType->isIntOrIntVectorTy(1) &&
1713  TrueVal->getType() == CondVal->getType()) {
1714  if (match(TrueVal, m_One())) {
1715  // Change: A = select B, true, C --> A = or B, C
1716  return BinaryOperator::CreateOr(CondVal, FalseVal);
1717  }
1718  if (match(TrueVal, m_Zero())) {
1719  // Change: A = select B, false, C --> A = and !B, C
1720  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1721  return BinaryOperator::CreateAnd(NotCond, FalseVal);
1722  }
1723  if (match(FalseVal, m_Zero())) {
1724  // Change: A = select B, C, false --> A = and B, C
1725  return BinaryOperator::CreateAnd(CondVal, TrueVal);
1726  }
1727  if (match(FalseVal, m_One())) {
1728  // Change: A = select B, C, true --> A = or !B, C
1729  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1730  return BinaryOperator::CreateOr(NotCond, TrueVal);
1731  }
1732 
1733  // select a, a, b -> a | b
1734  // select a, b, a -> a & b
1735  if (CondVal == TrueVal)
1736  return BinaryOperator::CreateOr(CondVal, FalseVal);
1737  if (CondVal == FalseVal)
1738  return BinaryOperator::CreateAnd(CondVal, TrueVal);
1739 
1740  // select a, ~a, b -> (~a) & b
1741  // select a, b, ~a -> (~a) | b
1742  if (match(TrueVal, m_Not(m_Specific(CondVal))))
1743  return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1744  if (match(FalseVal, m_Not(m_Specific(CondVal))))
1745  return BinaryOperator::CreateOr(TrueVal, FalseVal);
1746  }
1747 
1748  // Selecting between two integer or vector splat integer constants?
1749  //
1750  // Note that we don't handle a scalar select of vectors:
1751  // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1752  // because that may need 3 instructions to splat the condition value:
1753  // extend, insertelement, shufflevector.
1754  if (SelType->isIntOrIntVectorTy() &&
1755  CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1756  // select C, 1, 0 -> zext C to int
1757  if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1758  return new ZExtInst(CondVal, SelType);
1759 
1760  // select C, -1, 0 -> sext C to int
1761  if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1762  return new SExtInst(CondVal, SelType);
1763 
1764  // select C, 0, 1 -> zext !C to int
1765  if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1766  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1767  return new ZExtInst(NotCond, SelType);
1768  }
1769 
1770  // select C, 0, -1 -> sext !C to int
1771  if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1772  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1773  return new SExtInst(NotCond, SelType);
1774  }
1775  }
1776 
1777  // See if we are selecting two values based on a comparison of the two values.
1778  if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1779  if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1780  // Canonicalize to use ordered comparisons by swapping the select
1781  // operands.
1782  //
1783  // e.g.
1784  // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1785  if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1786  FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1787  IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1788  Builder.setFastMathFlags(FCI->getFastMathFlags());
1789  Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1790  FCI->getName() + ".inv");
1791 
1792  return SelectInst::Create(NewCond, FalseVal, TrueVal,
1793  SI.getName() + ".p");
1794  }
1795 
1796  // NOTE: if we wanted to, this is where to detect MIN/MAX
1797  } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1798  // Canonicalize to use ordered comparisons by swapping the select
1799  // operands.
1800  //
1801  // e.g.
1802  // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1803  if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1804  FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1805  IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1806  Builder.setFastMathFlags(FCI->getFastMathFlags());
1807  Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1808  FCI->getName() + ".inv");
1809 
1810  return SelectInst::Create(NewCond, FalseVal, TrueVal,
1811  SI.getName() + ".p");
1812  }
1813 
1814  // NOTE: if we wanted to, this is where to detect MIN/MAX
1815  }
1816 
1817  // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need
1818  // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We
1819  // also require nnan because we do not want to unintentionally change the
1820  // sign of a NaN value.
1821  Value *X = FCI->getOperand(0);
1822  FCmpInst::Predicate Pred = FCI->getPredicate();
1823  if (match(FCI->getOperand(1), m_AnyZeroFP()) && FCI->hasNoNaNs()) {
1824  // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X)
1825  // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X)
1826  if ((X == FalseVal && Pred == FCmpInst::FCMP_OLE &&
1827  match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(X)))) ||
1828  (X == TrueVal && Pred == FCmpInst::FCMP_OGT &&
1829  match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(X))))) {
1830  Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1831  return replaceInstUsesWith(SI, Fabs);
1832  }
1833  // With nsz:
1834  // (X < +/-0.0) ? -X : X --> fabs(X)
1835  // (X <= +/-0.0) ? -X : X --> fabs(X)
1836  // (X > +/-0.0) ? X : -X --> fabs(X)
1837  // (X >= +/-0.0) ? X : -X --> fabs(X)
1838  if (FCI->hasNoSignedZeros() &&
1839  ((X == FalseVal && match(TrueVal, m_FNeg(m_Specific(X))) &&
1840  (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE)) ||
1841  (X == TrueVal && match(FalseVal, m_FNeg(m_Specific(X))) &&
1842  (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE)))) {
1843  Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, X, FCI);
1844  return replaceInstUsesWith(SI, Fabs);
1845  }
1846  }
1847  }
1848 
1849  // See if we are selecting two values based on a comparison of the two values.
1850  if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1851  if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1852  return Result;
1853 
1854  if (Instruction *Add = foldAddSubSelect(SI, Builder))
1855  return Add;
1856 
1857  // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1858  auto *TI = dyn_cast<Instruction>(TrueVal);
1859  auto *FI = dyn_cast<Instruction>(FalseVal);
1860  if (TI && FI && TI->getOpcode() == FI->getOpcode())
1861  if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1862  return IV;
1863 
1864  if (Instruction *I = foldSelectExtConst(SI))
1865  return I;
1866 
1867  // See if we can fold the select into one of our operands.
1868  if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1869  if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1870  return FoldI;
1871 
1872  Value *LHS, *RHS;
1873  Instruction::CastOps CastOp;
1874  SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1875  auto SPF = SPR.Flavor;
1876  if (SPF) {
1877  Value *LHS2, *RHS2;
1878  if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1879  if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2,
1880  RHS2, SI, SPF, RHS))
1881  return R;
1882  if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1883  if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2,
1884  RHS2, SI, SPF, LHS))
1885  return R;
1886  // TODO.
1887  // ABS(-X) -> ABS(X)
1888  }
1889 
1891  // Canonicalize so that
1892  // - type casts are outside select patterns.
1893  // - float clamp is transformed to min/max pattern
1894 
1895  bool IsCastNeeded = LHS->getType() != SelType;
1896  Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1897  Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1898  if (IsCastNeeded ||
1899  (LHS->getType()->isFPOrFPVectorTy() &&
1900  ((CmpLHS != LHS && CmpLHS != RHS) ||
1901  (CmpRHS != LHS && CmpRHS != RHS)))) {
1902  CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered);
1903 
1904  Value *Cmp;
1905  if (CmpInst::isIntPredicate(Pred)) {
1906  Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1907  } else {
1908  IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1909  auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1910  Builder.setFastMathFlags(FMF);
1911  Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1912  }
1913 
1914  Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1915  if (!IsCastNeeded)
1916  return replaceInstUsesWith(SI, NewSI);
1917 
1918  Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1919  return replaceInstUsesWith(SI, NewCast);
1920  }
1921 
1922  // MAX(~a, ~b) -> ~MIN(a, b)
1923  // MAX(~a, C) -> ~MIN(a, ~C)
1924  // MIN(~a, ~b) -> ~MAX(a, b)
1925  // MIN(~a, C) -> ~MAX(a, ~C)
1926  auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * {
1927  Value *A;
1928  if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) &&
1929  !IsFreeToInvert(A, A->hasOneUse()) &&
1930  // Passing false to only consider m_Not and constants.
1931  IsFreeToInvert(Y, false)) {
1932  Value *B = Builder.CreateNot(Y);
1933  Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF),
1934  A, B);
1935  // Copy the profile metadata.
1936  if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) {
1937  cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD);
1938  // Swap the metadata if the operands are swapped.
1939  if (X == SI.getFalseValue() && Y == SI.getTrueValue())
1940  cast<SelectInst>(NewMinMax)->swapProfMetadata();
1941  }
1942 
1943  return BinaryOperator::CreateNot(NewMinMax);
1944  }
1945 
1946  return nullptr;
1947  };
1948 
1949  if (Instruction *I = moveNotAfterMinMax(LHS, RHS))
1950  return I;
1951  if (Instruction *I = moveNotAfterMinMax(RHS, LHS))
1952  return I;
1953 
1954  if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder))
1955  return I;
1956  }
1957  }
1958 
1959  // See if we can fold the select into a phi node if the condition is a select.
1960  if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1961  // The true/false values have to be live in the PHI predecessor's blocks.
1962  if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1963  canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1964  if (Instruction *NV = foldOpIntoPhi(SI, PN))
1965  return NV;
1966 
1967  if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1968  if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1969  // select(C, select(C, a, b), c) -> select(C, a, c)
1970  if (TrueSI->getCondition() == CondVal) {
1971  if (SI.getTrueValue() == TrueSI->getTrueValue())
1972  return nullptr;
1973  SI.setOperand(1, TrueSI->getTrueValue());
1974  return &SI;
1975  }
1976  // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1977  // We choose this as normal form to enable folding on the And and shortening
1978  // paths for the values (this helps GetUnderlyingObjects() for example).
1979  if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1980  Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1981  SI.setOperand(0, And);
1982  SI.setOperand(1, TrueSI->getTrueValue());
1983  return &SI;
1984  }
1985  }
1986  }
1987  if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1988  if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1989  // select(C, a, select(C, b, c)) -> select(C, a, c)
1990  if (FalseSI->getCondition() == CondVal) {
1991  if (SI.getFalseValue() == FalseSI->getFalseValue())
1992  return nullptr;
1993  SI.setOperand(2, FalseSI->getFalseValue());
1994  return &SI;
1995  }
1996  // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1997  if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1998  Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1999  SI.setOperand(0, Or);
2000  SI.setOperand(2, FalseSI->getFalseValue());
2001  return &SI;
2002  }
2003  }
2004  }
2005 
2006  auto canMergeSelectThroughBinop = [](BinaryOperator *BO) {
2007  // The select might be preventing a division by 0.
2008  switch (BO->getOpcode()) {
2009  default:
2010  return true;
2011  case Instruction::SRem:
2012  case Instruction::URem:
2013  case Instruction::SDiv:
2014  case Instruction::UDiv:
2015  return false;
2016  }
2017  };
2018 
2019  // Try to simplify a binop sandwiched between 2 selects with the same
2020  // condition.
2021  // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z)
2022  BinaryOperator *TrueBO;
2023  if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) &&
2024  canMergeSelectThroughBinop(TrueBO)) {
2025  if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) {
2026  if (TrueBOSI->getCondition() == CondVal) {
2027  TrueBO->setOperand(0, TrueBOSI->getTrueValue());
2028  Worklist.Add(TrueBO);
2029  return &SI;
2030  }
2031  }
2032  if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) {
2033  if (TrueBOSI->getCondition() == CondVal) {
2034  TrueBO->setOperand(1, TrueBOSI->getTrueValue());
2035  Worklist.Add(TrueBO);
2036  return &SI;
2037  }
2038  }
2039  }
2040 
2041  // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W))
2042  BinaryOperator *FalseBO;
2043  if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) &&
2044  canMergeSelectThroughBinop(FalseBO)) {
2045  if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) {
2046  if (FalseBOSI->getCondition() == CondVal) {
2047  FalseBO->setOperand(0, FalseBOSI->getFalseValue());
2048  Worklist.Add(FalseBO);
2049  return &SI;
2050  }
2051  }
2052  if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) {
2053  if (FalseBOSI->getCondition() == CondVal) {
2054  FalseBO->setOperand(1, FalseBOSI->getFalseValue());
2055  Worklist.Add(FalseBO);
2056  return &SI;
2057  }
2058  }
2059  }
2060 
2061  Value *NotCond;
2062  if (match(CondVal, m_Not(m_Value(NotCond)))) {
2063  SI.setOperand(0, NotCond);
2064  SI.setOperand(1, FalseVal);
2065  SI.setOperand(2, TrueVal);
2066  SI.swapProfMetadata();
2067  return &SI;
2068  }
2069 
2070  if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
2071  unsigned VWidth = VecTy->getNumElements();
2072  APInt UndefElts(VWidth, 0);
2073  APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2074  if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
2075  if (V != &SI)
2076  return replaceInstUsesWith(SI, V);
2077  return &SI;
2078  }
2079  }
2080 
2081  // If we can compute the condition, there's no need for a select.
2082  // Like the above fold, we are attempting to reduce compile-time cost by
2083  // putting this fold here with limitations rather than in InstSimplify.
2084  // The motivation for this call into value tracking is to take advantage of
2085  // the assumption cache, so make sure that is populated.
2086  if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
2087  KnownBits Known(1);
2088  computeKnownBits(CondVal, Known, 0, &SI);
2089  if (Known.One.isOneValue())
2090  return replaceInstUsesWith(SI, TrueVal);
2091  if (Known.Zero.isOneValue())
2092  return replaceInstUsesWith(SI, FalseVal);
2093  }
2094 
2095  if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
2096  return BitCastSel;
2097 
2098  // Simplify selects that test the returned flag of cmpxchg instructions.
2099  if (Instruction *Select = foldSelectCmpXchg(SI))
2100  return Select;
2101 
2102  if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI))
2103  return Select;
2104 
2105  if (Instruction *Rot = foldSelectRotate(SI))
2106  return Rot;
2107 
2108  return nullptr;
2109 }
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
bool isFPPredicate() const
Definition: InstrTypes.h:738
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Definition: PatternMatch.h:748
uint64_t CallInst * C
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, OptimizationRemarkEmitter *ORE=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static bool isSelect01(const APInt &C1I, const APInt &C2I)
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:584
static Instruction * foldSelectBinOpIdentity(SelectInst &Sel, const TargetLibraryInfo &TLI)
Replace a select operand based on an equality comparison with the identity constant of a binop...
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:70
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1984
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:636
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
void setFastMathFlags(FastMathFlags FMF)
Convenience function for setting multiple fast-math flags on this instruction, which must be an opera...
static bool IsFreeToInvert(Value *V, bool WillInvertAllUses)
Return true if the specified value is free to invert (apply ~ to).
bool hasNoSignedZeros() const
Determine whether the no-signed-zeros flag is set.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
Definition: PatternMatch.h:78
This instruction extracts a struct member or array element value from an aggregate value...
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:561
BinaryOp_match< LHS, RHS, Instruction::Sub > m_Sub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:653
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
Definition: PatternMatch.h:375
DiagnosticInfoOptimizationBase::Argument NV
static BinaryOperator * CreateNot(Value *Op, const Twine &Name="", Instruction *InsertBefore=nullptr)
Value * CreateIsNotNull(Value *Arg, const Twine &Name="")
Return an i1 value testing if Arg is not null.
Definition: IRBuilder.h:2152
Unsigned minimum.
Value * CreateZExtOrTrunc(Value *V, Type *DestTy, const Twine &Name="")
Create a ZExt or Trunc from the integer value V to DestTy.
Definition: IRBuilder.h:1704
This class represents lattice values for constants.
Definition: AllocatorList.h:23
BinaryOps getOpcode() const
Definition: InstrTypes.h:316
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1235
bool decomposeBitTestICmp(Value *LHS, Value *RHS, CmpInst::Predicate &Pred, Value *&X, APInt &Mask, bool LookThroughTrunc=true)
Decompose an icmp into the form ((X & Mask) pred 0) if possible.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
Definition: Instructions.h:528
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
This class represents zero extension of integer types.
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Definition: Instructions.h:899
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1203
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:89
static bool isCanonicalPredicate(CmpInst::Predicate Pred)
Predicate canonicalization reduces the number of patterns that need to be matched by other transforms...
const Value * getTrueValue() const
unsigned less or equal
Definition: InstrTypes.h:672
unsigned less than
Definition: InstrTypes.h:671
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:652
This instruction constructs a fixed permutation of two input vectors.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:705
static unsigned getSelectFoldableOperands(BinaryOperator *I)
We want to turn code that looks like this: C = or A, B D = select cond, C, A into: C = select cond...
1 1 1 0 True if unordered or not equal
Definition: InstrTypes.h:662
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
bool sgt(const APInt &RHS) const
Signed greather than comparison.
Definition: APInt.h:1273
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
void setArgOperand(unsigned i, Value *v)
Definition: InstrTypes.h:1160
Metadata node.
Definition: Metadata.h:863
SelectPatternFlavor getInverseMinMaxFlavor(SelectPatternFlavor SPF)
Return the inverse minimum/maximum flavor of the specified flavor.
F(f)
This class represents a sign extension of integer types.
BinaryOp_match< LHS, RHS, Instruction::FSub > m_FSub(const LHS &L, const RHS &R)
Definition: PatternMatch.h:659
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:229
void reserve(size_type N)
Definition: SmallVector.h:368
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition: APInt.h:1238
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:363
bool Ordered
Only applicable if Flavor is SPF_FMINNUM or SPF_FMAXNUM.
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition: APInt.h:1508
Signed maximum.
BinOpPred_match< LHS, RHS, is_logical_shift_op > m_LogicalShift(const LHS &L, const RHS &R)
Matches logical shift operations.
Definition: PatternMatch.h:940
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:264
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1369
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1155
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:47
static Value * foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp, InstCombiner::BuilderTy &Builder)
This folds: select (icmp eq (and X, C1)), TC, FC iff C1 is a power 2 and the difference between TC an...
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
Definition: PatternMatch.h:760
This class represents the LLVM &#39;select&#39; instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
Definition: InstrTypes.h:745
Absolute value.
static Optional< unsigned > getOpcode(ArrayRef< VPValue *> Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:196
bool isUnsigned() const
Definition: InstrTypes.h:822
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:742
0 1 0 1 True if ordered and less than or equal
Definition: InstrTypes.h:653
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1650
This file implements a class to represent arbitrary precision integral constant values and operations...
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
Definition: PatternMatch.h:641
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1664
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
bool isNullValue() const
Return true if this is the value that would be returned by getNullValue.
Definition: Constants.cpp:84
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:244
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
This instruction compares its operands according to the predicate given to the constructor.
void andIRFlags(const Value *V)
Logical &#39;and&#39; of any supported wrapping, exact, and fast-math flags of V and this instruction...
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
Definition: Instruction.h:234
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
cstfp_pred_ty< is_pos_zero_fp > m_PosZeroFP()
Match a floating-point positive zero.
Definition: PatternMatch.h:444
Value * CreateSub(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1066
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:202
CallInst * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Definition: IRBuilder.cpp:733
static Instruction * foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp, Value *TVal, Value *FVal, InstCombiner::BuilderTy &Builder)
We want to turn: (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1) into: zext (icmp ne i32 (a...
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power-of-2.
Definition: PatternMatch.h:384
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:291
Function * getDeclaration(Module *M, ID id, ArrayRef< Type *> Tys=None)
Create or insert an LLVM Function declaration for an intrinsic, and return it.
Definition: Function.cpp:1018
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
Value * getOperand(unsigned i) const
Definition: User.h:169
bool CannotBeNegativeZero(const Value *V, const TargetLibraryInfo *TLI, unsigned Depth=0)
Return true if we can prove that the specified FP value is never equal to -0.0.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:20
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1217
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:334
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:303
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1992
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:61
#define P(N)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
Definition: PatternMatch.h:772
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
Definition: Value.cpp:135
Value * SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q)
Given operands for a SelectInst, fold the result or return null.
bool isAllOnesValue() const
Determine if all bits are set.
Definition: APInt.h:395
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
MaxMin_match< ICmpInst, LHS, RHS, umax_pred_ty > m_UMax(const LHS &L, const RHS &R)
bool hasNUses(unsigned N) const
Return true if this Value has exactly N users.
Definition: Value.cpp:131
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
Definition: PatternMatch.h:175
BinaryOp_match< LHS, RHS, Instruction::Add, true > m_c_Add(const LHS &L, const RHS &R)
Matches a Add with LHS and RHS in either order.
bool isKnownNegation(const Value *X, const Value *Y, bool NeedNSW=false)
Return true if the two given values are negation.
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:428
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Definition: PatternMatch.h:754
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1184
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
This is an important base class in LLVM.
Definition: Constant.h:41
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:2057
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
bool isOneValue() const
Determine if this is a value of 1.
Definition: APInt.h:410
cst_pred_ty< is_all_ones > m_AllOnes()
Match an integer or vector with all bits set.
Definition: PatternMatch.h:308
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:587
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:501
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1192
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1343
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:646
static Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false)
Return the identity constant for a binary opcode.
Definition: Constants.cpp:2325
CmpInst::Predicate getMinMaxPred(SelectPatternFlavor SPF, bool Ordered=false)
Return the canonical comparison predicate for the specified minimum/maximum flavor.
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:73
Class to represent integer types.
Definition: DerivedTypes.h:39
const Value * getCondition() const
bool isCast() const
Definition: Instruction.h:133
C setMetadata(LLVMContext::MD_range, MDNode::get(Context, LowAndHigh))
void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
signed greater than
Definition: InstrTypes.h:673
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
Floating point maxnum.
static Value * createMinMax(InstCombiner::BuilderTy &Builder, SelectPatternFlavor SPF, Value *A, Value *B)
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:650
static Value * foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal, Value *FalseVal, InstCombiner::BuilderTy &Builder)
We want to turn: (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) into: (or (shl (and X...
unsigned getNumOperands() const
Definition: User.h:191
SelectPatternFlavor Flavor
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:129
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:839
SelectPatternFlavor
Specific patterns of select instructions we can match.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Definition: Instruction.h:63
Provides information about what library functions are available for the current target.
signed less than
Definition: InstrTypes.h:675
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1636
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Definition: Constants.cpp:621
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1292
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:577
bool isCommutative() const
Return true if the instruction is commutative:
Definition: Instruction.h:491
Instruction * visitSelectInst(SelectInst &SI)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition: InstrTypes.h:726
void setOperand(unsigned i, Value *Val)
Definition: User.h:174
unsigned logBase2() const
Definition: APInt.h:1747
BinaryOp_match< cst_pred_ty< is_zero_int >, ValTy, Instruction::Sub > m_Neg(const ValTy &V)
Matches a &#39;Neg&#39; as &#39;sub 0, V&#39;.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:940
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:493
bool isIntPredicate() const
Definition: InstrTypes.h:739
Class to represent vector types.
Definition: DerivedTypes.h:424
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:55
Class for arbitrary precision integers.
Definition: APInt.h:69
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1222
static Value * canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal, InstCombiner::BuilderTy &Builder)
bool isPowerOf2() const
Check if this APInt&#39;s value is a power of two greater than zero.
Definition: APInt.h:463
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
bool sge(const APInt &RHS) const
Signed greater or equal comparison.
Definition: APInt.h:1308
iterator_range< user_iterator > users()
Definition: Value.h:399
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1529
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1138
const Value * getFalseValue() const
void setCondition(Value *V)
static APInt getSelectFoldableConstant(BinaryOperator *I)
For the same transformation as the previous function, return the identity constant that goes into the...
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass&#39;s ...
bool ugt(const APInt &RHS) const
Unsigned greather than comparison.
Definition: APInt.h:1254
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:721
static cl::opt< bool > NeedAnd("extract-needand", cl::init(true), cl::Hidden, cl::desc("Require & in extract patterns"))
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match &#39;fneg X&#39; as &#39;fsub -0.0, X&#39;.
Definition: PatternMatch.h:688
static Value * canonicalizeSaturatedSubtract(const ICmpInst *ICI, const Value *TrueVal, const Value *FalseVal, InstCombiner::BuilderTy &Builder)
Transform patterns such as: (a > b) ? a - b : 0 into: ((a > b) ? a : b) - b) This produces a canonica...
void setTrueValue(Value *V)
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:175
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
unsigned greater or equal
Definition: InstrTypes.h:670
static bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:214
bool isEquality() const
Return true if this predicate is either EQ or NE.
#define I(x, y, z)
Definition: MD5.cpp:58
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:322
void setFalseValue(Value *V)
Signed minimum.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1199
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:793
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:184
bool isOneValue() const
Returns true if the value is one.
Definition: Constants.cpp:125
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1804
static GetElementPtrInst * CreateInBounds(Value *Ptr, ArrayRef< Value *> IdxList, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Create an "inbounds" getelementptr.
Definition: Instructions.h:933
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:544
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:649
LLVM Value Representation.
Definition: Value.h:72
This file provides internal interfaces used to implement the InstCombine.
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr, unsigned Depth=0)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
cst_pred_ty< is_one > m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:354
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:219
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:86
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1159
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:412
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:159
unsigned greater than
Definition: InstrTypes.h:669
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:761
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:568
specific_intval m_SpecificInt(uint64_t V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:578
cstfp_pred_ty< is_any_zero_fp > m_AnyZeroFP()
Match a floating-point negative zero or positive zero.
Definition: PatternMatch.h:435
0 0 1 1 True if ordered and greater than or equal
Definition: InstrTypes.h:651
static Constant * get(ArrayRef< Constant *> V)
Definition: Constants.cpp:1078
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1361
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:478
BinaryOp_match< ValTy, cst_pred_ty< is_all_ones >, Instruction::Xor, true > m_Not(const ValTy &V)
Matches a &#39;Not&#39; as &#39;xor V, -1&#39; or &#39;xor -1, V&#39;.
bool isNullValue() const
Determine if all bits are clear.
Definition: APInt.h:405
IntegerType * Int32Ty
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:43
const BasicBlock * getParent() const
Definition: Instruction.h:66
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)