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"
15 #include "llvm/Analysis/CmpInstAnalysis.h"
16 #include "llvm/Analysis/ConstantFolding.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/ValueTracking.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 
27 static SelectPatternFlavor
28 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
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 
44 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
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 
65 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy &Builder,
66                                           SelectPatternFlavor SPF, Value *A,
67                                           Value *B) {
68   CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
69   assert(CmpInst::isIntPredicate(Pred));
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 ///
189 static unsigned getSelectFoldableOperands(BinaryOperator *I) {
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.
209 static APInt getSelectFoldableConstant(BinaryOperator *I) {
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:
219     return APInt::getNullValue(I->getType()->getScalarSizeInBits());
220   case Instruction::And:
221     return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits());
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.
286   BinaryOperator *BO = dyn_cast<BinaryOperator>(TI);
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) {
351           APInt CI = getSelectFoldableConstant(TVI);
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) {
382           APInt CI = getSelectFoldableConstant(FVI);
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() !=
479                        V->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.
489     APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log);
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.
963   if (SelectPatternResult::isMinOrMax(SPF1) &&
964       SelectPatternResult::isMinOrMax(SPF2) &&
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 
975     Value *NewInner = generateMinMaxSelectPattern(
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)) {
1027           FastMathFlags Flags = AddOp->getFastMathFlags();
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 
1046         FastMathFlags Flags = AddOp->getFastMathFlags();
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();
1124   SmallVector<Constant *, 16> Mask;
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 
1200 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
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);
1238     Cond->setPredicate(CmpInst::getInversePredicate(Pred));
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 
1431     if (SelectPatternResult::isMinOrMax(SPF)) {
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)))) {
1443         CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
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)) {
1555     SI.setOperand(0, BinaryOperator::getNotArgument(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 }
1609