LLVM  6.0.0svn
InstCombineSelect.cpp
Go to the documentation of this file.
1 //===- InstCombineSelect.cpp ----------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the visitSelect function.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "InstCombineInternal.h"
19 #include "llvm/IR/MDBuilder.h"
20 #include "llvm/IR/PatternMatch.h"
21 #include "llvm/Support/KnownBits.h"
22 using namespace llvm;
23 using namespace PatternMatch;
24 
25 #define DEBUG_TYPE "instcombine"
26 
29  switch (SPF) {
30  default:
31  llvm_unreachable("unhandled!");
32 
33  case SPF_SMIN:
34  return SPF_SMAX;
35  case SPF_UMIN:
36  return SPF_UMAX;
37  case SPF_SMAX:
38  return SPF_SMIN;
39  case SPF_UMAX:
40  return SPF_UMIN;
41  }
42 }
43 
45  bool Ordered=false) {
46  switch (SPF) {
47  default:
48  llvm_unreachable("unhandled!");
49 
50  case SPF_SMIN:
51  return ICmpInst::ICMP_SLT;
52  case SPF_UMIN:
53  return ICmpInst::ICMP_ULT;
54  case SPF_SMAX:
55  return ICmpInst::ICMP_SGT;
56  case SPF_UMAX:
57  return ICmpInst::ICMP_UGT;
58  case SPF_FMINNUM:
59  return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
60  case SPF_FMAXNUM:
61  return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
62  }
63 }
64 
66  SelectPatternFlavor SPF, Value *A,
67  Value *B) {
70  return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B);
71 }
72 
73 /// If one of the constants is zero (we know they can't both be) and we have an
74 /// icmp instruction with zero, and we have an 'and' with the non-constant value
75 /// and a power of two we can turn the select into a shift on the result of the
76 /// 'and'.
77 /// This folds:
78 /// select (icmp eq (and X, C1)), C2, C3
79 /// iff C1 is a power 2 and the difference between C2 and C3 is a power of 2.
80 /// To something like:
81 /// (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3
82 /// Or:
83 /// (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3
84 /// With some variations depending if C3 is larger than C2, or the shift
85 /// isn't needed, or the bit widths don't match.
86 static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC,
87  APInt TrueVal, APInt FalseVal,
88  InstCombiner::BuilderTy &Builder) {
89  assert(SelType->isIntOrIntVectorTy() && "Not an integer select?");
90 
91  // If this is a vector select, we need a vector compare.
92  if (SelType->isVectorTy() != IC->getType()->isVectorTy())
93  return nullptr;
94 
95  Value *V;
96  APInt AndMask;
97  bool CreateAnd = false;
98  ICmpInst::Predicate Pred = IC->getPredicate();
99  if (ICmpInst::isEquality(Pred)) {
100  if (!match(IC->getOperand(1), m_Zero()))
101  return nullptr;
102 
103  V = IC->getOperand(0);
104 
105  const APInt *AndRHS;
106  if (!match(V, m_And(m_Value(), m_Power2(AndRHS))))
107  return nullptr;
108 
109  AndMask = *AndRHS;
110  } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1),
111  Pred, V, AndMask)) {
112  assert(ICmpInst::isEquality(Pred) && "Not equality test?");
113 
114  if (!AndMask.isPowerOf2())
115  return nullptr;
116 
117  CreateAnd = true;
118  } else {
119  return nullptr;
120  }
121 
122  // If both select arms are non-zero see if we have a select of the form
123  // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
124  // for 'x ? 2^n : 0' and fix the thing up at the end.
125  APInt Offset(TrueVal.getBitWidth(), 0);
126  if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) {
127  if ((TrueVal - FalseVal).isPowerOf2())
128  Offset = FalseVal;
129  else if ((FalseVal - TrueVal).isPowerOf2())
130  Offset = TrueVal;
131  else
132  return nullptr;
133 
134  // Adjust TrueVal and FalseVal to the offset.
135  TrueVal -= Offset;
136  FalseVal -= Offset;
137  }
138 
139  // Make sure one of the select arms is a power of 2.
140  if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2())
141  return nullptr;
142 
143  // Determine which shift is needed to transform result of the 'and' into the
144  // desired result.
145  const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal;
146  unsigned ValZeros = ValC.logBase2();
147  unsigned AndZeros = AndMask.logBase2();
148 
149  if (CreateAnd) {
150  // Insert the AND instruction on the input to the truncate.
151  V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask));
152  }
153 
154  // If types don't match we can still convert the select by introducing a zext
155  // or a trunc of the 'and'.
156  if (ValZeros > AndZeros) {
157  V = Builder.CreateZExtOrTrunc(V, SelType);
158  V = Builder.CreateShl(V, ValZeros - AndZeros);
159  } else if (ValZeros < AndZeros) {
160  V = Builder.CreateLShr(V, AndZeros - ValZeros);
161  V = Builder.CreateZExtOrTrunc(V, SelType);
162  } else
163  V = Builder.CreateZExtOrTrunc(V, SelType);
164 
165  // Okay, now we know that everything is set up, we just don't know whether we
166  // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
167  bool ShouldNotVal = !TrueVal.isNullValue();
168  ShouldNotVal ^= Pred == ICmpInst::ICMP_NE;
169  if (ShouldNotVal)
170  V = Builder.CreateXor(V, ValC);
171 
172  // Apply an offset if needed.
173  if (!Offset.isNullValue())
174  V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset));
175  return V;
176 }
177 
178 /// We want to turn code that looks like this:
179 /// %C = or %A, %B
180 /// %D = select %cond, %C, %A
181 /// into:
182 /// %C = select %cond, %B, 0
183 /// %D = or %A, %C
184 ///
185 /// Assuming that the specified instruction is an operand to the select, return
186 /// a bitmask indicating which operands of this instruction are foldable if they
187 /// equal the other incoming value of the select.
188 ///
190  switch (I->getOpcode()) {
191  case Instruction::Add:
192  case Instruction::Mul:
193  case Instruction::And:
194  case Instruction::Or:
195  case Instruction::Xor:
196  return 3; // Can fold through either operand.
197  case Instruction::Sub: // Can only fold on the amount subtracted.
198  case Instruction::Shl: // Can only fold on the shift amount.
199  case Instruction::LShr:
200  case Instruction::AShr:
201  return 1;
202  default:
203  return 0; // Cannot fold
204  }
205 }
206 
207 /// For the same transformation as the previous function, return the identity
208 /// constant that goes into the select.
210  switch (I->getOpcode()) {
211  default: llvm_unreachable("This cannot happen!");
212  case Instruction::Add:
213  case Instruction::Sub:
214  case Instruction::Or:
215  case Instruction::Xor:
216  case Instruction::Shl:
217  case Instruction::LShr:
218  case Instruction::AShr:
220  case Instruction::And:
222  case Instruction::Mul:
223  return APInt(I->getType()->getScalarSizeInBits(), 1);
224  }
225 }
226 
227 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
228 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
229  Instruction *FI) {
230  // Don't break up min/max patterns. The hasOneUse checks below prevent that
231  // for most cases, but vector min/max with bitcasts can be transformed. If the
232  // one-use restrictions are eased for other patterns, we still don't want to
233  // obfuscate min/max.
234  if ((match(&SI, m_SMin(m_Value(), m_Value())) ||
235  match(&SI, m_SMax(m_Value(), m_Value())) ||
236  match(&SI, m_UMin(m_Value(), m_Value())) ||
237  match(&SI, m_UMax(m_Value(), m_Value()))))
238  return nullptr;
239 
240  // If this is a cast from the same type, merge.
241  if (TI->getNumOperands() == 1 && TI->isCast()) {
242  Type *FIOpndTy = FI->getOperand(0)->getType();
243  if (TI->getOperand(0)->getType() != FIOpndTy)
244  return nullptr;
245 
246  // The select condition may be a vector. We may only change the operand
247  // type if the vector width remains the same (and matches the condition).
248  Type *CondTy = SI.getCondition()->getType();
249  if (CondTy->isVectorTy()) {
250  if (!FIOpndTy->isVectorTy())
251  return nullptr;
252  if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
253  return nullptr;
254 
255  // TODO: If the backend knew how to deal with casts better, we could
256  // remove this limitation. For now, there's too much potential to create
257  // worse codegen by promoting the select ahead of size-altering casts
258  // (PR28160).
259  //
260  // Note that ValueTracking's matchSelectPattern() looks through casts
261  // without checking 'hasOneUse' when it matches min/max patterns, so this
262  // transform may end up happening anyway.
263  if (TI->getOpcode() != Instruction::BitCast &&
264  (!TI->hasOneUse() || !FI->hasOneUse()))
265  return nullptr;
266 
267  } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
268  // TODO: The one-use restrictions for a scalar select could be eased if
269  // the fold of a select in visitLoadInst() was enhanced to match a pattern
270  // that includes a cast.
271  return nullptr;
272  }
273 
274  // Fold this by inserting a select from the input values.
275  Value *NewSI =
276  Builder.CreateSelect(SI.getCondition(), TI->getOperand(0),
277  FI->getOperand(0), SI.getName() + ".v", &SI);
278  return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
279  TI->getType());
280  }
281 
282  // Only handle binary operators with one-use here. As with the cast case
283  // above, it may be possible to relax the one-use constraint, but that needs
284  // be examined carefully since it may not reduce the total number of
285  // instructions.
287  if (!BO || !TI->hasOneUse() || !FI->hasOneUse())
288  return nullptr;
289 
290  // Figure out if the operations have any operands in common.
291  Value *MatchOp, *OtherOpT, *OtherOpF;
292  bool MatchIsOpZero;
293  if (TI->getOperand(0) == FI->getOperand(0)) {
294  MatchOp = TI->getOperand(0);
295  OtherOpT = TI->getOperand(1);
296  OtherOpF = FI->getOperand(1);
297  MatchIsOpZero = true;
298  } else if (TI->getOperand(1) == FI->getOperand(1)) {
299  MatchOp = TI->getOperand(1);
300  OtherOpT = TI->getOperand(0);
301  OtherOpF = FI->getOperand(0);
302  MatchIsOpZero = false;
303  } else if (!TI->isCommutative()) {
304  return nullptr;
305  } else if (TI->getOperand(0) == FI->getOperand(1)) {
306  MatchOp = TI->getOperand(0);
307  OtherOpT = TI->getOperand(1);
308  OtherOpF = FI->getOperand(0);
309  MatchIsOpZero = true;
310  } else if (TI->getOperand(1) == FI->getOperand(0)) {
311  MatchOp = TI->getOperand(1);
312  OtherOpT = TI->getOperand(0);
313  OtherOpF = FI->getOperand(1);
314  MatchIsOpZero = true;
315  } else {
316  return nullptr;
317  }
318 
319  // If we reach here, they do have operations in common.
320  Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
321  SI.getName() + ".v", &SI);
322  Value *Op0 = MatchIsOpZero ? MatchOp : NewSI;
323  Value *Op1 = MatchIsOpZero ? NewSI : MatchOp;
324  return BinaryOperator::Create(BO->getOpcode(), Op0, Op1);
325 }
326 
327 static bool isSelect01(const APInt &C1I, const APInt &C2I) {
328  if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero.
329  return false;
330  return C1I.isOneValue() || C1I.isAllOnesValue() ||
331  C2I.isOneValue() || C2I.isAllOnesValue();
332 }
333 
334 /// Try to fold the select into one of the operands to allow further
335 /// optimization.
336 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
337  Value *FalseVal) {
338  // See the comment above GetSelectFoldableOperands for a description of the
339  // transformation we are doing here.
340  if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) {
341  if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) {
342  if (unsigned SFO = getSelectFoldableOperands(TVI)) {
343  unsigned OpToFold = 0;
344  if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
345  OpToFold = 1;
346  } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
347  OpToFold = 2;
348  }
349 
350  if (OpToFold) {
352  Value *OOp = TVI->getOperand(2-OpToFold);
353  // Avoid creating select between 2 constants unless it's selecting
354  // between 0, 1 and -1.
355  const APInt *OOpC;
356  bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
357  if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
358  Value *C = ConstantInt::get(OOp->getType(), CI);
359  Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C);
360  NewSel->takeName(TVI);
361  BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(),
362  FalseVal, NewSel);
363  BO->copyIRFlags(TVI);
364  return BO;
365  }
366  }
367  }
368  }
369  }
370 
371  if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) {
372  if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) {
373  if (unsigned SFO = getSelectFoldableOperands(FVI)) {
374  unsigned OpToFold = 0;
375  if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
376  OpToFold = 1;
377  } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
378  OpToFold = 2;
379  }
380 
381  if (OpToFold) {
383  Value *OOp = FVI->getOperand(2-OpToFold);
384  // Avoid creating select between 2 constants unless it's selecting
385  // between 0, 1 and -1.
386  const APInt *OOpC;
387  bool OOpIsAPInt = match(OOp, m_APInt(OOpC));
388  if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) {
389  Value *C = ConstantInt::get(OOp->getType(), CI);
390  Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp);
391  NewSel->takeName(FVI);
392  BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(),
393  TrueVal, NewSel);
394  BO->copyIRFlags(FVI);
395  return BO;
396  }
397  }
398  }
399  }
400  }
401 
402  return nullptr;
403 }
404 
405 /// We want to turn:
406 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
407 /// into:
408 /// (or (shl (and X, C1), C3), Y)
409 /// iff:
410 /// C1 and C2 are both powers of 2
411 /// where:
412 /// C3 = Log(C2) - Log(C1)
413 ///
414 /// This transform handles cases where:
415 /// 1. The icmp predicate is inverted
416 /// 2. The select operands are reversed
417 /// 3. The magnitude of C2 and C1 are flipped
418 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal,
419  Value *FalseVal,
420  InstCombiner::BuilderTy &Builder) {
421  // Only handle integer compares. Also, if this is a vector select, we need a
422  // vector compare.
423  if (!TrueVal->getType()->isIntOrIntVectorTy() ||
424  TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy())
425  return nullptr;
426 
427  Value *CmpLHS = IC->getOperand(0);
428  Value *CmpRHS = IC->getOperand(1);
429 
430  Value *V;
431  unsigned C1Log;
432  bool IsEqualZero;
433  bool NeedAnd = false;
434  if (IC->isEquality()) {
435  if (!match(CmpRHS, m_Zero()))
436  return nullptr;
437 
438  const APInt *C1;
439  if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1))))
440  return nullptr;
441 
442  V = CmpLHS;
443  C1Log = C1->logBase2();
444  IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ;
445  } else if (IC->getPredicate() == ICmpInst::ICMP_SLT ||
446  IC->getPredicate() == ICmpInst::ICMP_SGT) {
447  // We also need to recognize (icmp slt (trunc (X)), 0) and
448  // (icmp sgt (trunc (X)), -1).
449  IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT;
450  if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) ||
451  (!IsEqualZero && !match(CmpRHS, m_Zero())))
452  return nullptr;
453 
454  if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V)))))
455  return nullptr;
456 
457  C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1;
458  NeedAnd = true;
459  } else {
460  return nullptr;
461  }
462 
463  const APInt *C2;
464  bool OrOnTrueVal = false;
465  bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
466  if (!OrOnFalseVal)
467  OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
468 
469  if (!OrOnFalseVal && !OrOnTrueVal)
470  return nullptr;
471 
472  Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
473 
474  unsigned C2Log = C2->logBase2();
475 
476  bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal);
477  bool NeedShift = C1Log != C2Log;
478  bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() !=
480 
481  // Make sure we don't create more instructions than we save.
482  Value *Or = OrOnFalseVal ? FalseVal : TrueVal;
483  if ((NeedShift + NeedXor + NeedZExtTrunc) >
484  (IC->hasOneUse() + Or->hasOneUse()))
485  return nullptr;
486 
487  if (NeedAnd) {
488  // Insert the AND instruction on the input to the truncate.
490  V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1));
491  }
492 
493  if (C2Log > C1Log) {
494  V = Builder.CreateZExtOrTrunc(V, Y->getType());
495  V = Builder.CreateShl(V, C2Log - C1Log);
496  } else if (C1Log > C2Log) {
497  V = Builder.CreateLShr(V, C1Log - C2Log);
498  V = Builder.CreateZExtOrTrunc(V, Y->getType());
499  } else
500  V = Builder.CreateZExtOrTrunc(V, Y->getType());
501 
502  if (NeedXor)
503  V = Builder.CreateXor(V, *C2);
504 
505  return Builder.CreateOr(V, Y);
506 }
507 
508 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
509 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
510 ///
511 /// For example, we can fold the following code sequence:
512 /// \code
513 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
514 /// %1 = icmp ne i32 %x, 0
515 /// %2 = select i1 %1, i32 %0, i32 32
516 /// \code
517 ///
518 /// into:
519 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
520 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
521  InstCombiner::BuilderTy &Builder) {
522  ICmpInst::Predicate Pred = ICI->getPredicate();
523  Value *CmpLHS = ICI->getOperand(0);
524  Value *CmpRHS = ICI->getOperand(1);
525 
526  // Check if the condition value compares a value for equality against zero.
527  if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
528  return nullptr;
529 
530  Value *Count = FalseVal;
531  Value *ValueOnZero = TrueVal;
532  if (Pred == ICmpInst::ICMP_NE)
533  std::swap(Count, ValueOnZero);
534 
535  // Skip zero extend/truncate.
536  Value *V = nullptr;
537  if (match(Count, m_ZExt(m_Value(V))) ||
538  match(Count, m_Trunc(m_Value(V))))
539  Count = V;
540 
541  // Check if the value propagated on zero is a constant number equal to the
542  // sizeof in bits of 'Count'.
543  unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
544  if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
545  return nullptr;
546 
547  // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
548  // input to the cttz/ctlz is used as LHS for the compare instruction.
549  if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
550  match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
551  IntrinsicInst *II = cast<IntrinsicInst>(Count);
552  // Explicitly clear the 'undef_on_zero' flag.
553  IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
554  NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext()));
555  Builder.Insert(NewI);
556  return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
557  }
558 
559  return nullptr;
560 }
561 
562 /// Return true if we find and adjust an icmp+select pattern where the compare
563 /// is with a constant that can be incremented or decremented to match the
564 /// minimum or maximum idiom.
565 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) {
566  ICmpInst::Predicate Pred = Cmp.getPredicate();
567  Value *CmpLHS = Cmp.getOperand(0);
568  Value *CmpRHS = Cmp.getOperand(1);
569  Value *TrueVal = Sel.getTrueValue();
570  Value *FalseVal = Sel.getFalseValue();
571 
572  // We may move or edit the compare, so make sure the select is the only user.
573  const APInt *CmpC;
574  if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC)))
575  return false;
576 
577  // These transforms only work for selects of integers or vector selects of
578  // integer vectors.
579  Type *SelTy = Sel.getType();
580  auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType());
581  if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy())
582  return false;
583 
584  Constant *AdjustedRHS;
585  if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
586  AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1);
587  else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
588  AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1);
589  else
590  return false;
591 
592  // X > C ? X : C+1 --> X < C+1 ? C+1 : X
593  // X < C ? X : C-1 --> X > C-1 ? C-1 : X
594  if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
595  (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
596  ; // Nothing to do here. Values match without any sign/zero extension.
597  }
598  // Types do not match. Instead of calculating this with mixed types, promote
599  // all to the larger type. This enables scalar evolution to analyze this
600  // expression.
601  else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) {
602  Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy);
603 
604  // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
605  // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
606  // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
607  // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
608  if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) {
609  CmpLHS = TrueVal;
610  AdjustedRHS = SextRHS;
611  } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
612  SextRHS == TrueVal) {
613  CmpLHS = FalseVal;
614  AdjustedRHS = SextRHS;
615  } else if (Cmp.isUnsigned()) {
616  Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy);
617  // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
618  // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
619  // zext + signed compare cannot be changed:
620  // 0xff <s 0x00, but 0x00ff >s 0x0000
621  if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) {
622  CmpLHS = TrueVal;
623  AdjustedRHS = ZextRHS;
624  } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
625  ZextRHS == TrueVal) {
626  CmpLHS = FalseVal;
627  AdjustedRHS = ZextRHS;
628  } else {
629  return false;
630  }
631  } else {
632  return false;
633  }
634  } else {
635  return false;
636  }
637 
638  Pred = ICmpInst::getSwappedPredicate(Pred);
639  CmpRHS = AdjustedRHS;
640  std::swap(FalseVal, TrueVal);
641  Cmp.setPredicate(Pred);
642  Cmp.setOperand(0, CmpLHS);
643  Cmp.setOperand(1, CmpRHS);
644  Sel.setOperand(1, TrueVal);
645  Sel.setOperand(2, FalseVal);
646  Sel.swapProfMetadata();
647 
648  // Move the compare instruction right before the select instruction. Otherwise
649  // the sext/zext value may be defined after the compare instruction uses it.
650  Cmp.moveBefore(&Sel);
651 
652  return true;
653 }
654 
655 /// If this is an integer min/max (icmp + select) with a constant operand,
656 /// create the canonical icmp for the min/max operation and canonicalize the
657 /// constant to the 'false' operand of the select:
658 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2
659 /// Note: if C1 != C2, this will change the icmp constant to the existing
660 /// constant operand of the select.
661 static Instruction *
662 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp,
663  InstCombiner::BuilderTy &Builder) {
664  if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1)))
665  return nullptr;
666 
667  // Canonicalize the compare predicate based on whether we have min or max.
668  Value *LHS, *RHS;
669  ICmpInst::Predicate NewPred;
670  SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS);
671  switch (SPR.Flavor) {
672  case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break;
673  case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break;
674  case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break;
675  case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break;
676  default: return nullptr;
677  }
678 
679  // Is this already canonical?
680  if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS &&
681  Cmp.getPredicate() == NewPred)
682  return nullptr;
683 
684  // Create the canonical compare and plug it into the select.
685  Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS));
686 
687  // If the select operands did not change, we're done.
688  if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS)
689  return &Sel;
690 
691  // If we are swapping the select operands, swap the metadata too.
692  assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS &&
693  "Unexpected results from matchSelectPattern");
694  Sel.setTrueValue(LHS);
695  Sel.setFalseValue(RHS);
696  Sel.swapProfMetadata();
697  return &Sel;
698 }
699 
700 /// Visit a SelectInst that has an ICmpInst as its first operand.
701 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
702  ICmpInst *ICI) {
703  Value *TrueVal = SI.getTrueValue();
704  Value *FalseVal = SI.getFalseValue();
705 
706  if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder))
707  return NewSel;
708 
709  bool Changed = adjustMinMax(SI, *ICI);
710 
711  ICmpInst::Predicate Pred = ICI->getPredicate();
712  Value *CmpLHS = ICI->getOperand(0);
713  Value *CmpRHS = ICI->getOperand(1);
714 
715  // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
716  // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
717  // FIXME: Type and constness constraints could be lifted, but we have to
718  // watch code size carefully. We should consider xor instead of
719  // sub/add when we decide to do that.
720  // TODO: Merge this with foldSelectICmpAnd somehow.
721  if (CmpLHS->getType()->isIntOrIntVectorTy() &&
722  CmpLHS->getType() == TrueVal->getType()) {
723  const APInt *C1, *C2;
724  if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) {
725  ICmpInst::Predicate Pred = ICI->getPredicate();
726  Value *X;
727  APInt Mask;
728  if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) {
729  if (Mask.isSignMask()) {
730  assert(X == CmpLHS && "Expected to use the compare input directly");
731  assert(ICmpInst::isEquality(Pred) && "Expected equality predicate");
732 
733  if (Pred == ICmpInst::ICMP_NE)
734  std::swap(C1, C2);
735 
736  // This shift results in either -1 or 0.
737  Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1);
738 
739  // Check if we can express the operation with a single or.
740  if (C2->isAllOnesValue())
741  return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1));
742 
743  Value *And = Builder.CreateAnd(AShr, *C2 - *C1);
744  return replaceInstUsesWith(SI, Builder.CreateAdd(And,
745  ConstantInt::get(And->getType(), *C1)));
746  }
747  }
748  }
749  }
750 
751  {
752  const APInt *TrueValC, *FalseValC;
753  if (match(TrueVal, m_APInt(TrueValC)) &&
754  match(FalseVal, m_APInt(FalseValC)))
755  if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC,
756  *FalseValC, Builder))
757  return replaceInstUsesWith(SI, V);
758  }
759 
760  // NOTE: if we wanted to, this is where to detect integer MIN/MAX
761 
762  if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
763  if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
764  // Transform (X == C) ? X : Y -> (X == C) ? C : Y
765  SI.setOperand(1, CmpRHS);
766  Changed = true;
767  } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
768  // Transform (X != C) ? Y : X -> (X != C) ? Y : C
769  SI.setOperand(2, CmpRHS);
770  Changed = true;
771  }
772  }
773 
774  // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
775  // decomposeBitTestICmp() might help.
776  {
777  unsigned BitWidth =
778  DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
779  APInt MinSignedValue = APInt::getSignedMinValue(BitWidth);
780  Value *X;
781  const APInt *Y, *C;
782  bool TrueWhenUnset;
783  bool IsBitTest = false;
784  if (ICmpInst::isEquality(Pred) &&
785  match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
786  match(CmpRHS, m_Zero())) {
787  IsBitTest = true;
788  TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
789  } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
790  X = CmpLHS;
791  Y = &MinSignedValue;
792  IsBitTest = true;
793  TrueWhenUnset = false;
794  } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
795  X = CmpLHS;
796  Y = &MinSignedValue;
797  IsBitTest = true;
798  TrueWhenUnset = true;
799  }
800  if (IsBitTest) {
801  Value *V = nullptr;
802  // (X & Y) == 0 ? X : X ^ Y --> X & ~Y
803  if (TrueWhenUnset && TrueVal == X &&
804  match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
805  V = Builder.CreateAnd(X, ~(*Y));
806  // (X & Y) != 0 ? X ^ Y : X --> X & ~Y
807  else if (!TrueWhenUnset && FalseVal == X &&
808  match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
809  V = Builder.CreateAnd(X, ~(*Y));
810  // (X & Y) == 0 ? X ^ Y : X --> X | Y
811  else if (TrueWhenUnset && FalseVal == X &&
812  match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
813  V = Builder.CreateOr(X, *Y);
814  // (X & Y) != 0 ? X : X ^ Y --> X | Y
815  else if (!TrueWhenUnset && TrueVal == X &&
816  match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
817  V = Builder.CreateOr(X, *Y);
818 
819  if (V)
820  return replaceInstUsesWith(SI, V);
821  }
822  }
823 
824  if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder))
825  return replaceInstUsesWith(SI, V);
826 
827  if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
828  return replaceInstUsesWith(SI, V);
829 
830  return Changed ? &SI : nullptr;
831 }
832 
833 
834 /// SI is a select whose condition is a PHI node (but the two may be in
835 /// different blocks). See if the true/false values (V) are live in all of the
836 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
837 ///
838 /// X = phi [ C1, BB1], [C2, BB2]
839 /// Y = add
840 /// Z = select X, Y, 0
841 ///
842 /// because Y is not live in BB1/BB2.
843 ///
844 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
845  const SelectInst &SI) {
846  // If the value is a non-instruction value like a constant or argument, it
847  // can always be mapped.
848  const Instruction *I = dyn_cast<Instruction>(V);
849  if (!I) return true;
850 
851  // If V is a PHI node defined in the same block as the condition PHI, we can
852  // map the arguments.
853  const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
854 
855  if (const PHINode *VP = dyn_cast<PHINode>(I))
856  if (VP->getParent() == CondPHI->getParent())
857  return true;
858 
859  // Otherwise, if the PHI and select are defined in the same block and if V is
860  // defined in a different block, then we can transform it.
861  if (SI.getParent() == CondPHI->getParent() &&
862  I->getParent() != CondPHI->getParent())
863  return true;
864 
865  // Otherwise we have a 'hard' case and we can't tell without doing more
866  // detailed dominator based analysis, punt.
867  return false;
868 }
869 
870 /// We have an SPF (e.g. a min or max) of an SPF of the form:
871 /// SPF2(SPF1(A, B), C)
872 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
873  SelectPatternFlavor SPF1,
874  Value *A, Value *B,
875  Instruction &Outer,
876  SelectPatternFlavor SPF2, Value *C) {
877  if (Outer.getType() != Inner->getType())
878  return nullptr;
879 
880  if (C == A || C == B) {
881  // MAX(MAX(A, B), B) -> MAX(A, B)
882  // MIN(MIN(a, b), a) -> MIN(a, b)
883  if (SPF1 == SPF2)
884  return replaceInstUsesWith(Outer, Inner);
885 
886  // MAX(MIN(a, b), a) -> a
887  // MIN(MAX(a, b), a) -> a
888  if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
889  (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
890  (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
891  (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
892  return replaceInstUsesWith(Outer, C);
893  }
894 
895  if (SPF1 == SPF2) {
896  const APInt *CB, *CC;
897  if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) {
898  // MIN(MIN(A, 23), 97) -> MIN(A, 23)
899  // MAX(MAX(A, 97), 23) -> MAX(A, 97)
900  if ((SPF1 == SPF_UMIN && CB->ule(*CC)) ||
901  (SPF1 == SPF_SMIN && CB->sle(*CC)) ||
902  (SPF1 == SPF_UMAX && CB->uge(*CC)) ||
903  (SPF1 == SPF_SMAX && CB->sge(*CC)))
904  return replaceInstUsesWith(Outer, Inner);
905 
906  // MIN(MIN(A, 97), 23) -> MIN(A, 23)
907  // MAX(MAX(A, 23), 97) -> MAX(A, 97)
908  if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) ||
909  (SPF1 == SPF_SMIN && CB->sgt(*CC)) ||
910  (SPF1 == SPF_UMAX && CB->ult(*CC)) ||
911  (SPF1 == SPF_SMAX && CB->slt(*CC))) {
912  Outer.replaceUsesOfWith(Inner, A);
913  return &Outer;
914  }
915  }
916  }
917 
918  // ABS(ABS(X)) -> ABS(X)
919  // NABS(NABS(X)) -> NABS(X)
920  if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
921  return replaceInstUsesWith(Outer, Inner);
922  }
923 
924  // ABS(NABS(X)) -> ABS(X)
925  // NABS(ABS(X)) -> NABS(X)
926  if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
927  (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
928  SelectInst *SI = cast<SelectInst>(Inner);
929  Value *NewSI =
930  Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(),
931  SI->getTrueValue(), SI->getName(), SI);
932  return replaceInstUsesWith(Outer, NewSI);
933  }
934 
935  auto IsFreeOrProfitableToInvert =
936  [&](Value *V, Value *&NotV, bool &ElidesXor) {
937  if (match(V, m_Not(m_Value(NotV)))) {
938  // If V has at most 2 uses then we can get rid of the xor operation
939  // entirely.
940  ElidesXor |= !V->hasNUsesOrMore(3);
941  return true;
942  }
943 
944  if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
945  NotV = nullptr;
946  return true;
947  }
948 
949  return false;
950  };
951 
952  Value *NotA, *NotB, *NotC;
953  bool ElidesXor = false;
954 
955  // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
956  // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
957  // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
958  // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
959  //
960  // This transform is performance neutral if we can elide at least one xor from
961  // the set of three operands, since we'll be tacking on an xor at the very
962  // end.
965  IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
966  IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
967  IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
968  if (!NotA)
969  NotA = Builder.CreateNot(A);
970  if (!NotB)
971  NotB = Builder.CreateNot(B);
972  if (!NotC)
973  NotC = Builder.CreateNot(C);
974 
976  Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
977  Value *NewOuter = Builder.CreateNot(generateMinMaxSelectPattern(
978  Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
979  return replaceInstUsesWith(Outer, NewOuter);
980  }
981 
982  return nullptr;
983 }
984 
985 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
986 /// This is even legal for FP.
987 static Instruction *foldAddSubSelect(SelectInst &SI,
988  InstCombiner::BuilderTy &Builder) {
989  Value *CondVal = SI.getCondition();
990  Value *TrueVal = SI.getTrueValue();
991  Value *FalseVal = SI.getFalseValue();
992  auto *TI = dyn_cast<Instruction>(TrueVal);
993  auto *FI = dyn_cast<Instruction>(FalseVal);
994  if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
995  return nullptr;
996 
997  Instruction *AddOp = nullptr, *SubOp = nullptr;
998  if ((TI->getOpcode() == Instruction::Sub &&
999  FI->getOpcode() == Instruction::Add) ||
1000  (TI->getOpcode() == Instruction::FSub &&
1001  FI->getOpcode() == Instruction::FAdd)) {
1002  AddOp = FI;
1003  SubOp = TI;
1004  } else if ((FI->getOpcode() == Instruction::Sub &&
1005  TI->getOpcode() == Instruction::Add) ||
1006  (FI->getOpcode() == Instruction::FSub &&
1007  TI->getOpcode() == Instruction::FAdd)) {
1008  AddOp = TI;
1009  SubOp = FI;
1010  }
1011 
1012  if (AddOp) {
1013  Value *OtherAddOp = nullptr;
1014  if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
1015  OtherAddOp = AddOp->getOperand(1);
1016  } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
1017  OtherAddOp = AddOp->getOperand(0);
1018  }
1019 
1020  if (OtherAddOp) {
1021  // So at this point we know we have (Y -> OtherAddOp):
1022  // select C, (add X, Y), (sub X, Z)
1023  Value *NegVal; // Compute -Z
1024  if (SI.getType()->isFPOrFPVectorTy()) {
1025  NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
1026  if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
1028  Flags &= SubOp->getFastMathFlags();
1029  NegInst->setFastMathFlags(Flags);
1030  }
1031  } else {
1032  NegVal = Builder.CreateNeg(SubOp->getOperand(1));
1033  }
1034 
1035  Value *NewTrueOp = OtherAddOp;
1036  Value *NewFalseOp = NegVal;
1037  if (AddOp != TI)
1038  std::swap(NewTrueOp, NewFalseOp);
1039  Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
1040  SI.getName() + ".p", &SI);
1041 
1042  if (SI.getType()->isFPOrFPVectorTy()) {
1043  Instruction *RI =
1044  BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
1045 
1047  Flags &= SubOp->getFastMathFlags();
1048  RI->setFastMathFlags(Flags);
1049  return RI;
1050  } else
1051  return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
1052  }
1053  }
1054  return nullptr;
1055 }
1056 
1057 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
1058  Instruction *ExtInst;
1059  if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
1060  !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
1061  return nullptr;
1062 
1063  auto ExtOpcode = ExtInst->getOpcode();
1064  if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
1065  return nullptr;
1066 
1067  // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
1068  Value *X = ExtInst->getOperand(0);
1069  Type *SmallType = X->getType();
1070  if (!SmallType->isIntOrIntVectorTy(1))
1071  return nullptr;
1072 
1073  Constant *C;
1074  if (!match(Sel.getTrueValue(), m_Constant(C)) &&
1075  !match(Sel.getFalseValue(), m_Constant(C)))
1076  return nullptr;
1077 
1078  // If the constant is the same after truncation to the smaller type and
1079  // extension to the original type, we can narrow the select.
1080  Value *Cond = Sel.getCondition();
1081  Type *SelType = Sel.getType();
1082  Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
1083  Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
1084  if (ExtC == C) {
1085  Value *TruncCVal = cast<Value>(TruncC);
1086  if (ExtInst == Sel.getFalseValue())
1087  std::swap(X, TruncCVal);
1088 
1089  // select Cond, (ext X), C --> ext(select Cond, X, C')
1090  // select Cond, C, (ext X) --> ext(select Cond, C', X)
1091  Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
1092  return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
1093  }
1094 
1095  // If one arm of the select is the extend of the condition, replace that arm
1096  // with the extension of the appropriate known bool value.
1097  if (Cond == X) {
1098  if (ExtInst == Sel.getTrueValue()) {
1099  // select X, (sext X), C --> select X, -1, C
1100  // select X, (zext X), C --> select X, 1, C
1101  Constant *One = ConstantInt::getTrue(SmallType);
1102  Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
1103  return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel);
1104  } else {
1105  // select X, C, (sext X) --> select X, C, 0
1106  // select X, C, (zext X) --> select X, C, 0
1107  Constant *Zero = ConstantInt::getNullValue(SelType);
1108  return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel);
1109  }
1110  }
1111 
1112  return nullptr;
1113 }
1114 
1115 /// Try to transform a vector select with a constant condition vector into a
1116 /// shuffle for easier combining with other shuffles and insert/extract.
1117 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
1118  Value *CondVal = SI.getCondition();
1119  Constant *CondC;
1120  if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
1121  return nullptr;
1122 
1123  unsigned NumElts = CondVal->getType()->getVectorNumElements();
1125  Mask.reserve(NumElts);
1126  Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
1127  for (unsigned i = 0; i != NumElts; ++i) {
1128  Constant *Elt = CondC->getAggregateElement(i);
1129  if (!Elt)
1130  return nullptr;
1131 
1132  if (Elt->isOneValue()) {
1133  // If the select condition element is true, choose from the 1st vector.
1134  Mask.push_back(ConstantInt::get(Int32Ty, i));
1135  } else if (Elt->isNullValue()) {
1136  // If the select condition element is false, choose from the 2nd vector.
1137  Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1138  } else if (isa<UndefValue>(Elt)) {
1139  // Undef in a select condition (choose one of the operands) does not mean
1140  // the same thing as undef in a shuffle mask (any value is acceptable), so
1141  // give up.
1142  return nullptr;
1143  } else {
1144  // Bail out on a constant expression.
1145  return nullptr;
1146  }
1147  }
1148 
1149  return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1150  ConstantVector::get(Mask));
1151 }
1152 
1153 /// Reuse bitcasted operands between a compare and select:
1154 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1155 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D))
1156 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel,
1157  InstCombiner::BuilderTy &Builder) {
1158  Value *Cond = Sel.getCondition();
1159  Value *TVal = Sel.getTrueValue();
1160  Value *FVal = Sel.getFalseValue();
1161 
1162  CmpInst::Predicate Pred;
1163  Value *A, *B;
1164  if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B))))
1165  return nullptr;
1166 
1167  // The select condition is a compare instruction. If the select's true/false
1168  // values are already the same as the compare operands, there's nothing to do.
1169  if (TVal == A || TVal == B || FVal == A || FVal == B)
1170  return nullptr;
1171 
1172  Value *C, *D;
1173  if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D))))
1174  return nullptr;
1175 
1176  // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc)
1177  Value *TSrc, *FSrc;
1178  if (!match(TVal, m_BitCast(m_Value(TSrc))) ||
1179  !match(FVal, m_BitCast(m_Value(FSrc))))
1180  return nullptr;
1181 
1182  // If the select true/false values are *different bitcasts* of the same source
1183  // operands, make the select operands the same as the compare operands and
1184  // cast the result. This is the canonical select form for min/max.
1185  Value *NewSel;
1186  if (TSrc == C && FSrc == D) {
1187  // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) -->
1188  // bitcast (select (cmp A, B), A, B)
1189  NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel);
1190  } else if (TSrc == D && FSrc == C) {
1191  // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) -->
1192  // bitcast (select (cmp A, B), B, A)
1193  NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel);
1194  } else {
1195  return nullptr;
1196  }
1197  return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType());
1198 }
1199 
1201  Value *CondVal = SI.getCondition();
1202  Value *TrueVal = SI.getTrueValue();
1203  Value *FalseVal = SI.getFalseValue();
1204  Type *SelType = SI.getType();
1205 
1206  // FIXME: Remove this workaround when freeze related patches are done.
1207  // For select with undef operand which feeds into an equality comparison,
1208  // don't simplify it so loop unswitch can know the equality comparison
1209  // may have an undef operand. This is a workaround for PR31652 caused by
1210  // descrepancy about branch on undef between LoopUnswitch and GVN.
1211  if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) {
1212  if (any_of(SI.users(), [&](User *U) {
1213  ICmpInst *CI = dyn_cast<ICmpInst>(U);
1214  if (CI && CI->isEquality())
1215  return true;
1216  return false;
1217  })) {
1218  return nullptr;
1219  }
1220  }
1221 
1222  if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal,
1223  SQ.getWithInstruction(&SI)))
1224  return replaceInstUsesWith(SI, V);
1225 
1226  if (Instruction *I = canonicalizeSelectToShuffle(SI))
1227  return I;
1228 
1229  // Canonicalize a one-use integer compare with a non-canonical predicate by
1230  // inverting the predicate and swapping the select operands. This matches a
1231  // compare canonicalization for conditional branches.
1232  // TODO: Should we do the same for FP compares?
1233  CmpInst::Predicate Pred;
1234  if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) &&
1235  !isCanonicalPredicate(Pred)) {
1236  // Swap true/false values and condition.
1237  CmpInst *Cond = cast<CmpInst>(CondVal);
1239  SI.setOperand(1, FalseVal);
1240  SI.setOperand(2, TrueVal);
1241  SI.swapProfMetadata();
1242  Worklist.Add(Cond);
1243  return &SI;
1244  }
1245 
1246  if (SelType->isIntOrIntVectorTy(1) &&
1247  TrueVal->getType() == CondVal->getType()) {
1248  if (match(TrueVal, m_One())) {
1249  // Change: A = select B, true, C --> A = or B, C
1250  return BinaryOperator::CreateOr(CondVal, FalseVal);
1251  }
1252  if (match(TrueVal, m_Zero())) {
1253  // Change: A = select B, false, C --> A = and !B, C
1254  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1255  return BinaryOperator::CreateAnd(NotCond, FalseVal);
1256  }
1257  if (match(FalseVal, m_Zero())) {
1258  // Change: A = select B, C, false --> A = and B, C
1259  return BinaryOperator::CreateAnd(CondVal, TrueVal);
1260  }
1261  if (match(FalseVal, m_One())) {
1262  // Change: A = select B, C, true --> A = or !B, C
1263  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1264  return BinaryOperator::CreateOr(NotCond, TrueVal);
1265  }
1266 
1267  // select a, a, b -> a | b
1268  // select a, b, a -> a & b
1269  if (CondVal == TrueVal)
1270  return BinaryOperator::CreateOr(CondVal, FalseVal);
1271  if (CondVal == FalseVal)
1272  return BinaryOperator::CreateAnd(CondVal, TrueVal);
1273 
1274  // select a, ~a, b -> (~a) & b
1275  // select a, b, ~a -> (~a) | b
1276  if (match(TrueVal, m_Not(m_Specific(CondVal))))
1277  return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1278  if (match(FalseVal, m_Not(m_Specific(CondVal))))
1279  return BinaryOperator::CreateOr(TrueVal, FalseVal);
1280  }
1281 
1282  // Selecting between two integer or vector splat integer constants?
1283  //
1284  // Note that we don't handle a scalar select of vectors:
1285  // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1286  // because that may need 3 instructions to splat the condition value:
1287  // extend, insertelement, shufflevector.
1288  if (SelType->isIntOrIntVectorTy() &&
1289  CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1290  // select C, 1, 0 -> zext C to int
1291  if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1292  return new ZExtInst(CondVal, SelType);
1293 
1294  // select C, -1, 0 -> sext C to int
1295  if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1296  return new SExtInst(CondVal, SelType);
1297 
1298  // select C, 0, 1 -> zext !C to int
1299  if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1300  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1301  return new ZExtInst(NotCond, SelType);
1302  }
1303 
1304  // select C, 0, -1 -> sext !C to int
1305  if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1306  Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName());
1307  return new SExtInst(NotCond, SelType);
1308  }
1309  }
1310 
1311  // See if we are selecting two values based on a comparison of the two values.
1312  if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1313  if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1314  // Transform (X == Y) ? X : Y -> Y
1315  if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1316  // This is not safe in general for floating point:
1317  // consider X== -0, Y== +0.
1318  // It becomes safe if either operand is a nonzero constant.
1319  ConstantFP *CFPt, *CFPf;
1320  if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1321  !CFPt->getValueAPF().isZero()) ||
1322  ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1323  !CFPf->getValueAPF().isZero()))
1324  return replaceInstUsesWith(SI, FalseVal);
1325  }
1326  // Transform (X une Y) ? X : Y -> X
1327  if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1328  // This is not safe in general for floating point:
1329  // consider X== -0, Y== +0.
1330  // It becomes safe if either operand is a nonzero constant.
1331  ConstantFP *CFPt, *CFPf;
1332  if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1333  !CFPt->getValueAPF().isZero()) ||
1334  ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1335  !CFPf->getValueAPF().isZero()))
1336  return replaceInstUsesWith(SI, TrueVal);
1337  }
1338 
1339  // Canonicalize to use ordered comparisons by swapping the select
1340  // operands.
1341  //
1342  // e.g.
1343  // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1344  if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1345  FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1346  IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1347  Builder.setFastMathFlags(FCI->getFastMathFlags());
1348  Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal,
1349  FCI->getName() + ".inv");
1350 
1351  return SelectInst::Create(NewCond, FalseVal, TrueVal,
1352  SI.getName() + ".p");
1353  }
1354 
1355  // NOTE: if we wanted to, this is where to detect MIN/MAX
1356  } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1357  // Transform (X == Y) ? Y : X -> X
1358  if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1359  // This is not safe in general for floating point:
1360  // consider X== -0, Y== +0.
1361  // It becomes safe if either operand is a nonzero constant.
1362  ConstantFP *CFPt, *CFPf;
1363  if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1364  !CFPt->getValueAPF().isZero()) ||
1365  ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1366  !CFPf->getValueAPF().isZero()))
1367  return replaceInstUsesWith(SI, FalseVal);
1368  }
1369  // Transform (X une Y) ? Y : X -> Y
1370  if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1371  // This is not safe in general for floating point:
1372  // consider X== -0, Y== +0.
1373  // It becomes safe if either operand is a nonzero constant.
1374  ConstantFP *CFPt, *CFPf;
1375  if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1376  !CFPt->getValueAPF().isZero()) ||
1377  ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1378  !CFPf->getValueAPF().isZero()))
1379  return replaceInstUsesWith(SI, TrueVal);
1380  }
1381 
1382  // Canonicalize to use ordered comparisons by swapping the select
1383  // operands.
1384  //
1385  // e.g.
1386  // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1387  if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1388  FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1389  IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1390  Builder.setFastMathFlags(FCI->getFastMathFlags());
1391  Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal,
1392  FCI->getName() + ".inv");
1393 
1394  return SelectInst::Create(NewCond, FalseVal, TrueVal,
1395  SI.getName() + ".p");
1396  }
1397 
1398  // NOTE: if we wanted to, this is where to detect MIN/MAX
1399  }
1400  // NOTE: if we wanted to, this is where to detect ABS
1401  }
1402 
1403  // See if we are selecting two values based on a comparison of the two values.
1404  if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1405  if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1406  return Result;
1407 
1408  if (Instruction *Add = foldAddSubSelect(SI, Builder))
1409  return Add;
1410 
1411  // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1412  auto *TI = dyn_cast<Instruction>(TrueVal);
1413  auto *FI = dyn_cast<Instruction>(FalseVal);
1414  if (TI && FI && TI->getOpcode() == FI->getOpcode())
1415  if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1416  return IV;
1417 
1418  if (Instruction *I = foldSelectExtConst(SI))
1419  return I;
1420 
1421  // See if we can fold the select into one of our operands.
1422  if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1423  if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1424  return FoldI;
1425 
1426  Value *LHS, *RHS, *LHS2, *RHS2;
1427  Instruction::CastOps CastOp;
1428  SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1429  auto SPF = SPR.Flavor;
1430 
1432  // Canonicalize so that
1433  // - type casts are outside select patterns.
1434  // - float clamp is transformed to min/max pattern
1435 
1436  bool IsCastNeeded = LHS->getType() != SelType;
1437  Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0);
1438  Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1);
1439  if (IsCastNeeded ||
1440  (LHS->getType()->isFPOrFPVectorTy() &&
1441  ((CmpLHS != LHS && CmpLHS != RHS) ||
1442  (CmpRHS != LHS && CmpRHS != RHS)))) {
1444 
1445  Value *Cmp;
1446  if (CmpInst::isIntPredicate(Pred)) {
1447  Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1448  } else {
1449  IRBuilder<>::FastMathFlagGuard FMFG(Builder);
1450  auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1451  Builder.setFastMathFlags(FMF);
1452  Cmp = Builder.CreateFCmp(Pred, LHS, RHS);
1453  }
1454 
1455  Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI);
1456  if (!IsCastNeeded)
1457  return replaceInstUsesWith(SI, NewSI);
1458 
1459  Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType);
1460  return replaceInstUsesWith(SI, NewCast);
1461  }
1462  }
1463 
1464  if (SPF) {
1465  // MAX(MAX(a, b), a) -> MAX(a, b)
1466  // MIN(MIN(a, b), a) -> MIN(a, b)
1467  // MAX(MIN(a, b), a) -> a
1468  // MIN(MAX(a, b), a) -> a
1469  // ABS(ABS(a)) -> ABS(a)
1470  // NABS(NABS(a)) -> NABS(a)
1471  if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1472  if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1473  SI, SPF, RHS))
1474  return R;
1475  if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1476  if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1477  SI, SPF, LHS))
1478  return R;
1479  }
1480 
1481  // MAX(~a, ~b) -> ~MIN(a, b)
1482  if ((SPF == SPF_SMAX || SPF == SPF_UMAX) &&
1483  IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1484  IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1485  // For this transform to be profitable, we need to eliminate at least two
1486  // 'not' instructions if we're going to add one 'not' instruction.
1487  int NumberOfNots =
1488  (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) +
1489  (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) +
1490  (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1491 
1492  if (NumberOfNots >= 2) {
1493  Value *NewLHS = Builder.CreateNot(LHS);
1494  Value *NewRHS = Builder.CreateNot(RHS);
1495  Value *NewCmp = SPF == SPF_SMAX ? Builder.CreateICmpSLT(NewLHS, NewRHS)
1496  : Builder.CreateICmpULT(NewLHS, NewRHS);
1497  Value *NewSI =
1498  Builder.CreateNot(Builder.CreateSelect(NewCmp, NewLHS, NewRHS));
1499  return replaceInstUsesWith(SI, NewSI);
1500  }
1501  }
1502 
1503  // TODO.
1504  // ABS(-X) -> ABS(X)
1505  }
1506 
1507  // See if we can fold the select into a phi node if the condition is a select.
1508  if (auto *PN = dyn_cast<PHINode>(SI.getCondition()))
1509  // The true/false values have to be live in the PHI predecessor's blocks.
1510  if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1511  canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1512  if (Instruction *NV = foldOpIntoPhi(SI, PN))
1513  return NV;
1514 
1515  if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1516  if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1517  // select(C, select(C, a, b), c) -> select(C, a, c)
1518  if (TrueSI->getCondition() == CondVal) {
1519  if (SI.getTrueValue() == TrueSI->getTrueValue())
1520  return nullptr;
1521  SI.setOperand(1, TrueSI->getTrueValue());
1522  return &SI;
1523  }
1524  // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1525  // We choose this as normal form to enable folding on the And and shortening
1526  // paths for the values (this helps GetUnderlyingObjects() for example).
1527  if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1528  Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition());
1529  SI.setOperand(0, And);
1530  SI.setOperand(1, TrueSI->getTrueValue());
1531  return &SI;
1532  }
1533  }
1534  }
1535  if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1536  if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1537  // select(C, a, select(C, b, c)) -> select(C, a, c)
1538  if (FalseSI->getCondition() == CondVal) {
1539  if (SI.getFalseValue() == FalseSI->getFalseValue())
1540  return nullptr;
1541  SI.setOperand(2, FalseSI->getFalseValue());
1542  return &SI;
1543  }
1544  // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1545  if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1546  Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition());
1547  SI.setOperand(0, Or);
1548  SI.setOperand(2, FalseSI->getFalseValue());
1549  return &SI;
1550  }
1551  }
1552  }
1553 
1554  if (BinaryOperator::isNot(CondVal)) {
1556  SI.setOperand(1, FalseVal);
1557  SI.setOperand(2, TrueVal);
1558  return &SI;
1559  }
1560 
1561  if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
1562  unsigned VWidth = VecTy->getNumElements();
1563  APInt UndefElts(VWidth, 0);
1564  APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1565  if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1566  if (V != &SI)
1567  return replaceInstUsesWith(SI, V);
1568  return &SI;
1569  }
1570  }
1571 
1572  // See if we can determine the result of this select based on a dominating
1573  // condition.
1574  BasicBlock *Parent = SI.getParent();
1575  if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1576  auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1577  if (PBI && PBI->isConditional() &&
1578  PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1579  (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1580  bool CondIsTrue = PBI->getSuccessor(0) == Parent;
1581  Optional<bool> Implication = isImpliedCondition(
1582  PBI->getCondition(), SI.getCondition(), DL, CondIsTrue);
1583  if (Implication) {
1584  Value *V = *Implication ? TrueVal : FalseVal;
1585  return replaceInstUsesWith(SI, V);
1586  }
1587  }
1588  }
1589 
1590  // If we can compute the condition, there's no need for a select.
1591  // Like the above fold, we are attempting to reduce compile-time cost by
1592  // putting this fold here with limitations rather than in InstSimplify.
1593  // The motivation for this call into value tracking is to take advantage of
1594  // the assumption cache, so make sure that is populated.
1595  if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) {
1596  KnownBits Known(1);
1597  computeKnownBits(CondVal, Known, 0, &SI);
1598  if (Known.One.isOneValue())
1599  return replaceInstUsesWith(SI, TrueVal);
1600  if (Known.Zero.isOneValue())
1601  return replaceInstUsesWith(SI, FalseVal);
1602  }
1603 
1604  if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder))
1605  return BitCastSel;
1606 
1607  return nullptr;
1608 }
MaxMin_match< ICmpInst, LHS, RHS, umin_pred_ty > m_UMin(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
Definition: PatternMatch.h:574
uint64_t CallInst * C
static bool isSelect01(const APInt &C1I, const APInt &C2I)
static ConstantInt * getFalse(LLVMContext &Context)
Definition: Constants.cpp:523
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:72
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1634
This class is the base class for the comparison instructions.
Definition: InstrTypes.h:850
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...
bool isSignMask() const
Check if the APInt&#39;s value is returned by getSignMask.
Definition: APInt.h:466
bool isZero() const
Definition: APFloat.h:1128
static bool IsFreeToInvert(Value *V, bool WillInvertAllUses)
Return true if the specified value is free to invert (apply ~ to).
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
Definition: PatternMatch.h:80
static APInt getAllOnesValue(unsigned numBits)
Get the all-ones value.
Definition: APInt.h:555
DiagnosticInfoOptimizationBase::Argument NV
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:1391
struct fuzzer::@309 Flags
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
BinaryOps getOpcode() const
Definition: InstrTypes.h:523
Value * CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1558
Value * CreateXor(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1095
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.
match_zero m_Zero()
Match an arbitrary zero/null constant.
Definition: PatternMatch.h:145
This class represents zero extension of integer types.
Value * CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1570
bool slt(const APInt &RHS) const
Signed less than comparison.
Definition: APInt.h:1183
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:91
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 than
Definition: InstrTypes.h:885
0 1 0 0 True if ordered and less than
Definition: InstrTypes.h:866
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:697
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:876
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:1253
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
This class represents a sign extension of integer types.
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:227
void reserve(size_type N)
Definition: SmallVector.h:380
bool sle(const APInt &RHS) const
Signed less or equal comparison.
Definition: APInt.h:1218
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
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:1488
Signed maximum.
static Constant * getNullValue(Type *Ty)
Constructor to create a &#39;0&#39; constant of arbitrary type.
Definition: Constants.cpp:207
Value * CreateNot(Value *V, const Twine &Name="")
Definition: IRBuilder.h:1142
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
static Value * foldSelectICmpAnd(Type *SelType, const ICmpInst *IC, APInt TrueVal, APInt FalseVal, InstCombiner::BuilderTy &Builder)
If one of the constants is zero (we know they can&#39;t both be) and we have an icmp instruction with zer...
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
Definition: PatternMatch.h:586
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:958
Absolute value.
bool isUnsigned() const
Determine if this instruction is using an unsigned comparison.
Definition: InstrTypes.h:1007
CastClass_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
Definition: PatternMatch.h:912
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:664
static Constant * getSExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1556
Value * CreateAdd(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:889
static SelectPatternFlavor getInverseMinMaxSelectPattern(SelectPatternFlavor SPF)
not_match< LHS > m_Not(const LHS &L)
Definition: PatternMatch.h:985
static Constant * getZExt(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:1570
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:86
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:245
CastClass_match< OpTy, Instruction::ZExt > m_ZExt(const OpTy &Op)
Matches ZExt.
Definition: PatternMatch.h:924
This instruction compares its operands according to the predicate given to the constructor.
MaxMin_match< ICmpInst, LHS, RHS, smin_pred_ty > m_SMin(const LHS &L, const RHS &R)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:125
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition: Type.h:203
cst_pred_ty< is_power2 > m_Power2()
Match an integer or vector power of 2.
Definition: PatternMatch.h:330
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:290
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
static const Value * getNotArgument(const Value *BinOp)
Value * getOperand(unsigned i) const
Definition: User.h:154
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Definition: User.cpp:22
SelectPatternResult matchSelectPattern(Value *V, Value *&LHS, Value *&RHS, Instruction::CastOps *CastOp=nullptr)
Pattern match integer [SU]MIN, [SU]MAX and ABS idioms, returning the kind and providing the out param...
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1079
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:277
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return &#39;this&#39;.
Definition: Type.h:301
Value * CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1641
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:63
bool hasNUsesOrMore(unsigned N) const
Return true if this value has N users or more.
Definition: Value.cpp:134
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:389
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:126
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
Definition: PatternMatch.h:260
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
Definition: BasicBlock.cpp:217
Value * CreateAShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1045
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:46
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
Definition: PatternMatch.h:580
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition: APInt.h:1164
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
Definition: PatternMatch.h:900
This is an important base class in LLVM.
Definition: Constant.h:42
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.h:1689
ConstantFP - Floating Point Values [float, double].
Definition: Constants.h:264
bool isOneValue() const
Determine if this is a value of 1.
Definition: APInt.h:404
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:581
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:382
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:823
Value * CreateNeg(Value *V, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1120
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:860
static bool isNot(const Value *V)
Class to represent integer types.
Definition: DerivedTypes.h:40
const Value * getCondition() const
bool isCast() const
Definition: Instruction.h:131
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:887
const APFloat & getValueAPF() const
Definition: Constants.h:294
CastClass_match< OpTy, Instruction::SExt > m_SExt(const OpTy &Op)
Matches SExt.
Definition: PatternMatch.h:918
Floating point maxnum.
0 0 1 0 True if ordered and greater than
Definition: InstrTypes.h:864
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:176
SelectPatternFlavor Flavor
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
Definition: Type.cpp:130
Unsigned maximum.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
1 1 0 0 True if unordered or less than
Definition: InstrTypes.h:874
SelectPatternFlavor
Specific patterns of select instructions we can match.
Floating point minnum.
signed less than
Definition: InstrTypes.h:889
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:1542
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:560
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1272
static ConstantInt * getTrue(LLVMContext &Context)
Definition: Constants.cpp:516
bool isCommutative() const
Return true if the instruction is commutative:
Definition: Instruction.h:420
Instruction * visitSelectInst(SelectInst &SI)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
Definition: InstrTypes.h:939
void setOperand(unsigned i, Value *Val)
Definition: User.h:159
unsigned logBase2() const
Definition: APInt.h:1727
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:923
unsigned getVectorNumElements() const
Definition: DerivedTypes.h:462
bool isIntPredicate() const
Definition: InstrTypes.h:952
Class to represent vector types.
Definition: DerivedTypes.h:393
Class for arbitrary precision integers.
Definition: APInt.h:69
bool ule(const APInt &RHS) const
Unsigned less or equal comparison.
Definition: APInt.h:1202
bool isPowerOf2() const
Check if this APInt&#39;s value is a power of two greater than zero.
Definition: APInt.h:457
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 greather or equal comparison.
Definition: APInt.h:1288
iterator_range< user_iterator > users()
Definition: Value.h:395
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
Definition: Constants.cpp:1435
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1008
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:1234
Predicate getPredicate() const
Return the predicate for this instruction.
Definition: InstrTypes.h:934
static cl::opt< bool > NeedAnd("extract-needand", cl::init(true), cl::Hidden, cl::desc("Require & in extract patterns"))
void setTrueValue(Value *V)
static IntegerType * getInt32Ty(LLVMContext &C)
Definition: Type.cpp:176
static bool isMinOrMax(SelectPatternFlavor SPF)
When implementing this min/max pattern as fcmp; select, does the fcmp have to be ordered?
static bool isUnordered(Predicate predicate)
Determine if the predicate is an unordered operation.
match_one m_One()
Match an integer 1 or a vector with all elements equal to 1.
Definition: PatternMatch.h:194
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:218
bool isEquality() const
Return true if this predicate is either EQ or NE.
#define I(x, y, z)
Definition: MD5.cpp:58
void setArgOperand(unsigned i, Value *v)
MaxMin_match< ICmpInst, LHS, RHS, smax_pred_ty > m_SMax(const LHS &L, const RHS &R)
static Value * generateMinMaxSelectPattern(InstCombiner::BuilderTy &Builder, SelectPatternFlavor SPF, Value *A, Value *B)
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:323
void setFalseValue(Value *V)
1 0 1 0 True if unordered or greater than
Definition: InstrTypes.h:872
Signed minimum.
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition: IRBuilder.h:1063
Optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition: IRBuilder.h:715
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition: Type.h:185
bool isOneValue() const
Returns true if the value is one.
Definition: Constants.cpp:127
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:1476
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:371
static APInt getSignedMinValue(unsigned numBits)
Gets minimum signed value of APInt for a specific bit width.
Definition: APInt.h:538
match_all_ones m_AllOnes()
Match an integer or vector with all bits set to true.
Definition: PatternMatch.h:205
0 0 0 1 True if ordered and equal
Definition: InstrTypes.h:863
LLVM Value Representation.
Definition: Value.h:73
static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF, bool Ordered=false)
This file provides internal interfaces used to implement the InstCombine.
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:81
void setFastMathFlags(FastMathFlags NewFMF)
Set the fast-math flags to be used with generated fp-math operators.
Definition: IRBuilder.h:221
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:88
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition: IRBuilder.h:1027
bool hasOneUse() const
Return true if there is exactly one user of this value.
Definition: Value.h:408
Convenience struct for specifying and reasoning about fast-math flags.
Definition: Operator.h:160
unsigned greater than
Definition: InstrTypes.h:883
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
Definition: InstrTypes.h:974
static APInt getNullValue(unsigned numBits)
Get the &#39;0&#39; value.
Definition: APInt.h:562
specific_intval m_SpecificInt(uint64_t V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:443
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)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
static Constant * get(ArrayRef< Constant *> V)
Definition: Constants.cpp:984
Value * CreateFNeg(Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1135
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:359
bool isNullValue() const
Determine if all bits are clear.
Definition: APInt.h:399
IntegerType * Int32Ty
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
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)
Definition: PatternMatch.h:837