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/ConstantFolding.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/ValueTracking.h"
18 #include "llvm/IR/MDBuilder.h"
19 #include "llvm/IR/PatternMatch.h"
20 using namespace llvm;
21 using namespace PatternMatch;
22 
23 #define DEBUG_TYPE "instcombine"
24 
25 static SelectPatternFlavor
26 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
27   switch (SPF) {
28   default:
29     llvm_unreachable("unhandled!");
30 
31   case SPF_SMIN:
32     return SPF_SMAX;
33   case SPF_UMIN:
34     return SPF_UMAX;
35   case SPF_SMAX:
36     return SPF_SMIN;
37   case SPF_UMAX:
38     return SPF_UMIN;
39   }
40 }
41 
42 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
43                                                    bool Ordered=false) {
44   switch (SPF) {
45   default:
46     llvm_unreachable("unhandled!");
47 
48   case SPF_SMIN:
49     return ICmpInst::ICMP_SLT;
50   case SPF_UMIN:
51     return ICmpInst::ICMP_ULT;
52   case SPF_SMAX:
53     return ICmpInst::ICMP_SGT;
54   case SPF_UMAX:
55     return ICmpInst::ICMP_UGT;
56   case SPF_FMINNUM:
57     return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
58   case SPF_FMAXNUM:
59     return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
60   }
61 }
62 
63 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
64                                           SelectPatternFlavor SPF, Value *A,
65                                           Value *B) {
66   CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
67   assert(CmpInst::isIntPredicate(Pred));
68   return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
69 }
70 
71 /// We want to turn code that looks like this:
72 ///   %C = or %A, %B
73 ///   %D = select %cond, %C, %A
74 /// into:
75 ///   %C = select %cond, %B, 0
76 ///   %D = or %A, %C
77 ///
78 /// Assuming that the specified instruction is an operand to the select, return
79 /// a bitmask indicating which operands of this instruction are foldable if they
80 /// equal the other incoming value of the select.
81 ///
82 static unsigned getSelectFoldableOperands(Instruction *I) {
83   switch (I->getOpcode()) {
84   case Instruction::Add:
85   case Instruction::Mul:
86   case Instruction::And:
87   case Instruction::Or:
88   case Instruction::Xor:
89     return 3;              // Can fold through either operand.
90   case Instruction::Sub:   // Can only fold on the amount subtracted.
91   case Instruction::Shl:   // Can only fold on the shift amount.
92   case Instruction::LShr:
93   case Instruction::AShr:
94     return 1;
95   default:
96     return 0;              // Cannot fold
97   }
98 }
99 
100 /// For the same transformation as the previous function, return the identity
101 /// constant that goes into the select.
102 static Constant *getSelectFoldableConstant(Instruction *I) {
103   switch (I->getOpcode()) {
104   default: llvm_unreachable("This cannot happen!");
105   case Instruction::Add:
106   case Instruction::Sub:
107   case Instruction::Or:
108   case Instruction::Xor:
109   case Instruction::Shl:
110   case Instruction::LShr:
111   case Instruction::AShr:
112     return Constant::getNullValue(I->getType());
113   case Instruction::And:
114     return Constant::getAllOnesValue(I->getType());
115   case Instruction::Mul:
116     return ConstantInt::get(I->getType(), 1);
117   }
118 }
119 
120 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode.
121 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI,
122                                           Instruction *FI) {
123   // If this is a cast from the same type, merge.
124   if (TI->getNumOperands() == 1 && TI->isCast()) {
125     Type *FIOpndTy = FI->getOperand(0)->getType();
126     if (TI->getOperand(0)->getType() != FIOpndTy)
127       return nullptr;
128 
129     // The select condition may be a vector. We may only change the operand
130     // type if the vector width remains the same (and matches the condition).
131     Type *CondTy = SI.getCondition()->getType();
132     if (CondTy->isVectorTy()) {
133       if (!FIOpndTy->isVectorTy())
134         return nullptr;
135       if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())
136         return nullptr;
137 
138       // TODO: If the backend knew how to deal with casts better, we could
139       // remove this limitation. For now, there's too much potential to create
140       // worse codegen by promoting the select ahead of size-altering casts
141       // (PR28160).
142       //
143       // Note that ValueTracking's matchSelectPattern() looks through casts
144       // without checking 'hasOneUse' when it matches min/max patterns, so this
145       // transform may end up happening anyway.
146       if (TI->getOpcode() != Instruction::BitCast &&
147           (!TI->hasOneUse() || !FI->hasOneUse()))
148         return nullptr;
149 
150     } else if (!TI->hasOneUse() || !FI->hasOneUse()) {
151       // TODO: The one-use restrictions for a scalar select could be eased if
152       // the fold of a select in visitLoadInst() was enhanced to match a pattern
153       // that includes a cast.
154       return nullptr;
155     }
156 
157     // Fold this by inserting a select from the input values.
158     Value *NewSI =
159         Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
160                               FI->getOperand(0), SI.getName() + ".v", &SI);
161     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
162                             TI->getType());
163   }
164 
165   // TODO: This function ends awkwardly in unreachable - fix to be more normal.
166 
167   // Only handle binary operators with one-use here. As with the cast case
168   // above, it may be possible to relax the one-use constraint, but that needs
169   // be examined carefully since it may not reduce the total number of
170   // instructions.
171   if (!isa<BinaryOperator>(TI) || !TI->hasOneUse() || !FI->hasOneUse())
172     return nullptr;
173 
174   // Figure out if the operations have any operands in common.
175   Value *MatchOp, *OtherOpT, *OtherOpF;
176   bool MatchIsOpZero;
177   if (TI->getOperand(0) == FI->getOperand(0)) {
178     MatchOp  = TI->getOperand(0);
179     OtherOpT = TI->getOperand(1);
180     OtherOpF = FI->getOperand(1);
181     MatchIsOpZero = true;
182   } else if (TI->getOperand(1) == FI->getOperand(1)) {
183     MatchOp  = TI->getOperand(1);
184     OtherOpT = TI->getOperand(0);
185     OtherOpF = FI->getOperand(0);
186     MatchIsOpZero = false;
187   } else if (!TI->isCommutative()) {
188     return nullptr;
189   } else if (TI->getOperand(0) == FI->getOperand(1)) {
190     MatchOp  = TI->getOperand(0);
191     OtherOpT = TI->getOperand(1);
192     OtherOpF = FI->getOperand(0);
193     MatchIsOpZero = true;
194   } else if (TI->getOperand(1) == FI->getOperand(0)) {
195     MatchOp  = TI->getOperand(1);
196     OtherOpT = TI->getOperand(0);
197     OtherOpF = FI->getOperand(1);
198     MatchIsOpZero = true;
199   } else {
200     return nullptr;
201   }
202 
203   // If we reach here, they do have operations in common.
204   Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, OtherOpF,
205                                        SI.getName() + ".v", &SI);
206 
207   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
208     if (MatchIsOpZero)
209       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
210     else
211       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
212   }
213   llvm_unreachable("Shouldn't get here");
214 }
215 
216 static bool isSelect01(Constant *C1, Constant *C2) {
217   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
218   if (!C1I)
219     return false;
220   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
221   if (!C2I)
222     return false;
223   if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
224     return false;
225   return C1I->isOne() || C1I->isAllOnesValue() ||
226          C2I->isOne() || C2I->isAllOnesValue();
227 }
228 
229 /// Try to fold the select into one of the operands to allow further
230 /// optimization.
231 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal,
232                                             Value *FalseVal) {
233   // See the comment above GetSelectFoldableOperands for a description of the
234   // transformation we are doing here.
235   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
236     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
237         !isa<Constant>(FalseVal)) {
238       if (unsigned SFO = getSelectFoldableOperands(TVI)) {
239         unsigned OpToFold = 0;
240         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
241           OpToFold = 1;
242         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
243           OpToFold = 2;
244         }
245 
246         if (OpToFold) {
247           Constant *C = getSelectFoldableConstant(TVI);
248           Value *OOp = TVI->getOperand(2-OpToFold);
249           // Avoid creating select between 2 constants unless it's selecting
250           // between 0, 1 and -1.
251           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
252             Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
253             NewSel->takeName(TVI);
254             BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
255             BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
256                                                         FalseVal, NewSel);
257             BO->copyIRFlags(TVI_BO);
258             return BO;
259           }
260         }
261       }
262     }
263   }
264 
265   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
266     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
267         !isa<Constant>(TrueVal)) {
268       if (unsigned SFO = getSelectFoldableOperands(FVI)) {
269         unsigned OpToFold = 0;
270         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
271           OpToFold = 1;
272         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
273           OpToFold = 2;
274         }
275 
276         if (OpToFold) {
277           Constant *C = getSelectFoldableConstant(FVI);
278           Value *OOp = FVI->getOperand(2-OpToFold);
279           // Avoid creating select between 2 constants unless it's selecting
280           // between 0, 1 and -1.
281           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
282             Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
283             NewSel->takeName(FVI);
284             BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
285             BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
286                                                         TrueVal, NewSel);
287             BO->copyIRFlags(FVI_BO);
288             return BO;
289           }
290         }
291       }
292     }
293   }
294 
295   return nullptr;
296 }
297 
298 /// We want to turn:
299 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
300 /// into:
301 ///   (or (shl (and X, C1), C3), y)
302 /// iff:
303 ///   C1 and C2 are both powers of 2
304 /// where:
305 ///   C3 = Log(C2) - Log(C1)
306 ///
307 /// This transform handles cases where:
308 /// 1. The icmp predicate is inverted
309 /// 2. The select operands are reversed
310 /// 3. The magnitude of C2 and C1 are flipped
311 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
312                                   Value *FalseVal,
313                                   InstCombiner::BuilderTy *Builder) {
314   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
315   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
316     return nullptr;
317 
318   Value *CmpLHS = IC->getOperand(0);
319   Value *CmpRHS = IC->getOperand(1);
320 
321   if (!match(CmpRHS, m_Zero()))
322     return nullptr;
323 
324   Value *X;
325   const APInt *C1;
326   if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
327     return nullptr;
328 
329   const APInt *C2;
330   bool OrOnTrueVal = false;
331   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
332   if (!OrOnFalseVal)
333     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
334 
335   if (!OrOnFalseVal && !OrOnTrueVal)
336     return nullptr;
337 
338   Value *V = CmpLHS;
339   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
340 
341   unsigned C1Log = C1->logBase2();
342   unsigned C2Log = C2->logBase2();
343   if (C2Log > C1Log) {
344     V = Builder->CreateZExtOrTrunc(V, Y->getType());
345     V = Builder->CreateShl(V, C2Log - C1Log);
346   } else if (C1Log > C2Log) {
347     V = Builder->CreateLShr(V, C1Log - C2Log);
348     V = Builder->CreateZExtOrTrunc(V, Y->getType());
349   } else
350     V = Builder->CreateZExtOrTrunc(V, Y->getType());
351 
352   ICmpInst::Predicate Pred = IC->getPredicate();
353   if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
354       (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
355     V = Builder->CreateXor(V, *C2);
356 
357   return Builder->CreateOr(V, Y);
358 }
359 
360 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
361 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
362 ///
363 /// For example, we can fold the following code sequence:
364 /// \code
365 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
366 ///   %1 = icmp ne i32 %x, 0
367 ///   %2 = select i1 %1, i32 %0, i32 32
368 /// \code
369 ///
370 /// into:
371 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
372 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
373                                   InstCombiner::BuilderTy *Builder) {
374   ICmpInst::Predicate Pred = ICI->getPredicate();
375   Value *CmpLHS = ICI->getOperand(0);
376   Value *CmpRHS = ICI->getOperand(1);
377 
378   // Check if the condition value compares a value for equality against zero.
379   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
380     return nullptr;
381 
382   Value *Count = FalseVal;
383   Value *ValueOnZero = TrueVal;
384   if (Pred == ICmpInst::ICMP_NE)
385     std::swap(Count, ValueOnZero);
386 
387   // Skip zero extend/truncate.
388   Value *V = nullptr;
389   if (match(Count, m_ZExt(m_Value(V))) ||
390       match(Count, m_Trunc(m_Value(V))))
391     Count = V;
392 
393   // Check if the value propagated on zero is a constant number equal to the
394   // sizeof in bits of 'Count'.
395   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
396   if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
397     return nullptr;
398 
399   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
400   // input to the cttz/ctlz is used as LHS for the compare instruction.
401   if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
402       match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
403     IntrinsicInst *II = cast<IntrinsicInst>(Count);
404     IRBuilder<> Builder(II);
405     // Explicitly clear the 'undef_on_zero' flag.
406     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
407     Type *Ty = NewI->getArgOperand(1)->getType();
408     NewI->setArgOperand(1, Constant::getNullValue(Ty));
409     Builder.Insert(NewI);
410     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
411   }
412 
413   return nullptr;
414 }
415 
416 /// Visit a SelectInst that has an ICmpInst as its first operand.
417 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI,
418                                                    ICmpInst *ICI) {
419   bool Changed = false;
420   ICmpInst::Predicate Pred = ICI->getPredicate();
421   Value *CmpLHS = ICI->getOperand(0);
422   Value *CmpRHS = ICI->getOperand(1);
423   Value *TrueVal = SI.getTrueValue();
424   Value *FalseVal = SI.getFalseValue();
425 
426   // Check cases where the comparison is with a constant that
427   // can be adjusted to fit the min/max idiom. We may move or edit ICI
428   // here, so make sure the select is the only user.
429   if (ICI->hasOneUse())
430     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
431       switch (Pred) {
432       default: break;
433       case ICmpInst::ICMP_ULT:
434       case ICmpInst::ICMP_SLT:
435       case ICmpInst::ICMP_UGT:
436       case ICmpInst::ICMP_SGT: {
437         // These transformations only work for selects over integers.
438         IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
439         if (!SelectTy)
440           break;
441 
442         Constant *AdjustedRHS;
443         if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
444           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
445         else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
446           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
447 
448         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
449         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
450         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
451             (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
452           ; // Nothing to do here. Values match without any sign/zero extension.
453 
454         // Types do not match. Instead of calculating this with mixed types
455         // promote all to the larger type. This enables scalar evolution to
456         // analyze this expression.
457         else if (CmpRHS->getType()->getScalarSizeInBits()
458                  < SelectTy->getBitWidth()) {
459           Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
460 
461           // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
462           // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
463           // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
464           // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
465           if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
466                 sextRHS == FalseVal) {
467             CmpLHS = TrueVal;
468             AdjustedRHS = sextRHS;
469           } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
470                      sextRHS == TrueVal) {
471             CmpLHS = FalseVal;
472             AdjustedRHS = sextRHS;
473           } else if (ICI->isUnsigned()) {
474             Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
475             // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
476             // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
477             // zext + signed compare cannot be changed:
478             //    0xff <s 0x00, but 0x00ff >s 0x0000
479             if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
480                 zextRHS == FalseVal) {
481               CmpLHS = TrueVal;
482               AdjustedRHS = zextRHS;
483             } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
484                        zextRHS == TrueVal) {
485               CmpLHS = FalseVal;
486               AdjustedRHS = zextRHS;
487             } else
488               break;
489           } else
490             break;
491         } else
492           break;
493 
494         Pred = ICmpInst::getSwappedPredicate(Pred);
495         CmpRHS = AdjustedRHS;
496         std::swap(FalseVal, TrueVal);
497         ICI->setPredicate(Pred);
498         ICI->setOperand(0, CmpLHS);
499         ICI->setOperand(1, CmpRHS);
500         SI.setOperand(1, TrueVal);
501         SI.setOperand(2, FalseVal);
502         SI.swapProfMetadata();
503 
504         // Move ICI instruction right before the select instruction. Otherwise
505         // the sext/zext value may be defined after the ICI instruction uses it.
506         ICI->moveBefore(&SI);
507 
508         Changed = true;
509         break;
510       }
511       }
512     }
513 
514   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
515   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
516   // FIXME: Type and constness constraints could be lifted, but we have to
517   //        watch code size carefully. We should consider xor instead of
518   //        sub/add when we decide to do that.
519   if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
520     if (TrueVal->getType() == Ty) {
521       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
522         ConstantInt *C1 = nullptr, *C2 = nullptr;
523         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
524           C1 = dyn_cast<ConstantInt>(TrueVal);
525           C2 = dyn_cast<ConstantInt>(FalseVal);
526         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
527           C1 = dyn_cast<ConstantInt>(FalseVal);
528           C2 = dyn_cast<ConstantInt>(TrueVal);
529         }
530         if (C1 && C2) {
531           // This shift results in either -1 or 0.
532           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
533 
534           // Check if we can express the operation with a single or.
535           if (C2->isAllOnesValue())
536             return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
537 
538           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
539           return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
540         }
541       }
542     }
543   }
544 
545   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
546 
547   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
548     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
549       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
550       SI.setOperand(1, CmpRHS);
551       Changed = true;
552     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
553       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
554       SI.setOperand(2, CmpRHS);
555       Changed = true;
556     }
557   }
558 
559   // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring
560   // decomposeBitTestICmp() might help.
561   {
562     unsigned BitWidth =
563         DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
564     APInt MinSignedValue = APInt::getSignBit(BitWidth);
565     Value *X;
566     const APInt *Y, *C;
567     bool TrueWhenUnset;
568     bool IsBitTest = false;
569     if (ICmpInst::isEquality(Pred) &&
570         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
571         match(CmpRHS, m_Zero())) {
572       IsBitTest = true;
573       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
574     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
575       X = CmpLHS;
576       Y = &MinSignedValue;
577       IsBitTest = true;
578       TrueWhenUnset = false;
579     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
580       X = CmpLHS;
581       Y = &MinSignedValue;
582       IsBitTest = true;
583       TrueWhenUnset = true;
584     }
585     if (IsBitTest) {
586       Value *V = nullptr;
587       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
588       if (TrueWhenUnset && TrueVal == X &&
589           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
590         V = Builder->CreateAnd(X, ~(*Y));
591       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
592       else if (!TrueWhenUnset && FalseVal == X &&
593                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
594         V = Builder->CreateAnd(X, ~(*Y));
595       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
596       else if (TrueWhenUnset && FalseVal == X &&
597                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
598         V = Builder->CreateOr(X, *Y);
599       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
600       else if (!TrueWhenUnset && TrueVal == X &&
601                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
602         V = Builder->CreateOr(X, *Y);
603 
604       if (V)
605         return replaceInstUsesWith(SI, V);
606     }
607   }
608 
609   if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
610     return replaceInstUsesWith(SI, V);
611 
612   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
613     return replaceInstUsesWith(SI, V);
614 
615   return Changed ? &SI : nullptr;
616 }
617 
618 
619 /// SI is a select whose condition is a PHI node (but the two may be in
620 /// different blocks). See if the true/false values (V) are live in all of the
621 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
622 ///
623 ///   X = phi [ C1, BB1], [C2, BB2]
624 ///   Y = add
625 ///   Z = select X, Y, 0
626 ///
627 /// because Y is not live in BB1/BB2.
628 ///
629 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V,
630                                                    const SelectInst &SI) {
631   // If the value is a non-instruction value like a constant or argument, it
632   // can always be mapped.
633   const Instruction *I = dyn_cast<Instruction>(V);
634   if (!I) return true;
635 
636   // If V is a PHI node defined in the same block as the condition PHI, we can
637   // map the arguments.
638   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
639 
640   if (const PHINode *VP = dyn_cast<PHINode>(I))
641     if (VP->getParent() == CondPHI->getParent())
642       return true;
643 
644   // Otherwise, if the PHI and select are defined in the same block and if V is
645   // defined in a different block, then we can transform it.
646   if (SI.getParent() == CondPHI->getParent() &&
647       I->getParent() != CondPHI->getParent())
648     return true;
649 
650   // Otherwise we have a 'hard' case and we can't tell without doing more
651   // detailed dominator based analysis, punt.
652   return false;
653 }
654 
655 /// We have an SPF (e.g. a min or max) of an SPF of the form:
656 ///   SPF2(SPF1(A, B), C)
657 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner,
658                                         SelectPatternFlavor SPF1,
659                                         Value *A, Value *B,
660                                         Instruction &Outer,
661                                         SelectPatternFlavor SPF2, Value *C) {
662   if (Outer.getType() != Inner->getType())
663     return nullptr;
664 
665   if (C == A || C == B) {
666     // MAX(MAX(A, B), B) -> MAX(A, B)
667     // MIN(MIN(a, b), a) -> MIN(a, b)
668     if (SPF1 == SPF2)
669       return replaceInstUsesWith(Outer, Inner);
670 
671     // MAX(MIN(a, b), a) -> a
672     // MIN(MAX(a, b), a) -> a
673     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
674         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
675         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
676         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
677       return replaceInstUsesWith(Outer, C);
678   }
679 
680   if (SPF1 == SPF2) {
681     if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
682       if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
683         const APInt &ACB = CB->getValue();
684         const APInt &ACC = CC->getValue();
685 
686         // MIN(MIN(A, 23), 97) -> MIN(A, 23)
687         // MAX(MAX(A, 97), 23) -> MAX(A, 97)
688         if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
689             (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
690             (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
691             (SPF1 == SPF_SMAX && ACB.sge(ACC)))
692           return replaceInstUsesWith(Outer, Inner);
693 
694         // MIN(MIN(A, 97), 23) -> MIN(A, 23)
695         // MAX(MAX(A, 23), 97) -> MAX(A, 97)
696         if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
697             (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
698             (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
699             (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
700           Outer.replaceUsesOfWith(Inner, A);
701           return &Outer;
702         }
703       }
704     }
705   }
706 
707   // ABS(ABS(X)) -> ABS(X)
708   // NABS(NABS(X)) -> NABS(X)
709   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
710     return replaceInstUsesWith(Outer, Inner);
711   }
712 
713   // ABS(NABS(X)) -> ABS(X)
714   // NABS(ABS(X)) -> NABS(X)
715   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
716       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
717     SelectInst *SI = cast<SelectInst>(Inner);
718     Value *NewSI =
719         Builder->CreateSelect(SI->getCondition(), SI->getFalseValue(),
720                               SI->getTrueValue(), SI->getName(), SI);
721     return replaceInstUsesWith(Outer, NewSI);
722   }
723 
724   auto IsFreeOrProfitableToInvert =
725       [&](Value *V, Value *&NotV, bool &ElidesXor) {
726     if (match(V, m_Not(m_Value(NotV)))) {
727       // If V has at most 2 uses then we can get rid of the xor operation
728       // entirely.
729       ElidesXor |= !V->hasNUsesOrMore(3);
730       return true;
731     }
732 
733     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
734       NotV = nullptr;
735       return true;
736     }
737 
738     return false;
739   };
740 
741   Value *NotA, *NotB, *NotC;
742   bool ElidesXor = false;
743 
744   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
745   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
746   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
747   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
748   //
749   // This transform is performance neutral if we can elide at least one xor from
750   // the set of three operands, since we'll be tacking on an xor at the very
751   // end.
752   if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
753       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
754       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
755     if (!NotA)
756       NotA = Builder->CreateNot(A);
757     if (!NotB)
758       NotB = Builder->CreateNot(B);
759     if (!NotC)
760       NotC = Builder->CreateNot(C);
761 
762     Value *NewInner = generateMinMaxSelectPattern(
763         Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
764     Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
765         Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
766     return replaceInstUsesWith(Outer, NewOuter);
767   }
768 
769   return nullptr;
770 }
771 
772 /// If one of the constants is zero (we know they can't both be) and we have an
773 /// icmp instruction with zero, and we have an 'and' with the non-constant value
774 /// and a power of two we can turn the select into a shift on the result of the
775 /// 'and'.
776 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
777                                 ConstantInt *FalseVal,
778                                 InstCombiner::BuilderTy *Builder) {
779   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
780   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
781     return nullptr;
782 
783   if (!match(IC->getOperand(1), m_Zero()))
784     return nullptr;
785 
786   ConstantInt *AndRHS;
787   Value *LHS = IC->getOperand(0);
788   if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
789     return nullptr;
790 
791   // If both select arms are non-zero see if we have a select of the form
792   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
793   // for 'x ? 2^n : 0' and fix the thing up at the end.
794   ConstantInt *Offset = nullptr;
795   if (!TrueVal->isZero() && !FalseVal->isZero()) {
796     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
797       Offset = FalseVal;
798     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
799       Offset = TrueVal;
800     else
801       return nullptr;
802 
803     // Adjust TrueVal and FalseVal to the offset.
804     TrueVal = ConstantInt::get(Builder->getContext(),
805                                TrueVal->getValue() - Offset->getValue());
806     FalseVal = ConstantInt::get(Builder->getContext(),
807                                 FalseVal->getValue() - Offset->getValue());
808   }
809 
810   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
811   if (!AndRHS->getValue().isPowerOf2() ||
812       (!TrueVal->getValue().isPowerOf2() &&
813        !FalseVal->getValue().isPowerOf2()))
814     return nullptr;
815 
816   // Determine which shift is needed to transform result of the 'and' into the
817   // desired result.
818   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
819   unsigned ValZeros = ValC->getValue().logBase2();
820   unsigned AndZeros = AndRHS->getValue().logBase2();
821 
822   // If types don't match we can still convert the select by introducing a zext
823   // or a trunc of the 'and'. The trunc case requires that all of the truncated
824   // bits are zero, we can figure that out by looking at the 'and' mask.
825   if (AndZeros >= ValC->getBitWidth())
826     return nullptr;
827 
828   Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
829   if (ValZeros > AndZeros)
830     V = Builder->CreateShl(V, ValZeros - AndZeros);
831   else if (ValZeros < AndZeros)
832     V = Builder->CreateLShr(V, AndZeros - ValZeros);
833 
834   // Okay, now we know that everything is set up, we just don't know whether we
835   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
836   bool ShouldNotVal = !TrueVal->isZero();
837   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
838   if (ShouldNotVal)
839     V = Builder->CreateXor(V, ValC);
840 
841   // Apply an offset if needed.
842   if (Offset)
843     V = Builder->CreateAdd(V, Offset);
844   return V;
845 }
846 
847 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))).
848 /// This is even legal for FP.
849 static Instruction *foldAddSubSelect(SelectInst &SI,
850                                      InstCombiner::BuilderTy &Builder) {
851   Value *CondVal = SI.getCondition();
852   Value *TrueVal = SI.getTrueValue();
853   Value *FalseVal = SI.getFalseValue();
854   auto *TI = dyn_cast<Instruction>(TrueVal);
855   auto *FI = dyn_cast<Instruction>(FalseVal);
856   if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse())
857     return nullptr;
858 
859   Instruction *AddOp = nullptr, *SubOp = nullptr;
860   if ((TI->getOpcode() == Instruction::Sub &&
861        FI->getOpcode() == Instruction::Add) ||
862       (TI->getOpcode() == Instruction::FSub &&
863        FI->getOpcode() == Instruction::FAdd)) {
864     AddOp = FI;
865     SubOp = TI;
866   } else if ((FI->getOpcode() == Instruction::Sub &&
867               TI->getOpcode() == Instruction::Add) ||
868              (FI->getOpcode() == Instruction::FSub &&
869               TI->getOpcode() == Instruction::FAdd)) {
870     AddOp = TI;
871     SubOp = FI;
872   }
873 
874   if (AddOp) {
875     Value *OtherAddOp = nullptr;
876     if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
877       OtherAddOp = AddOp->getOperand(1);
878     } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
879       OtherAddOp = AddOp->getOperand(0);
880     }
881 
882     if (OtherAddOp) {
883       // So at this point we know we have (Y -> OtherAddOp):
884       //        select C, (add X, Y), (sub X, Z)
885       Value *NegVal; // Compute -Z
886       if (SI.getType()->isFPOrFPVectorTy()) {
887         NegVal = Builder.CreateFNeg(SubOp->getOperand(1));
888         if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
889           FastMathFlags Flags = AddOp->getFastMathFlags();
890           Flags &= SubOp->getFastMathFlags();
891           NegInst->setFastMathFlags(Flags);
892         }
893       } else {
894         NegVal = Builder.CreateNeg(SubOp->getOperand(1));
895       }
896 
897       Value *NewTrueOp = OtherAddOp;
898       Value *NewFalseOp = NegVal;
899       if (AddOp != TI)
900         std::swap(NewTrueOp, NewFalseOp);
901       Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp,
902                                            SI.getName() + ".p", &SI);
903 
904       if (SI.getType()->isFPOrFPVectorTy()) {
905         Instruction *RI =
906             BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
907 
908         FastMathFlags Flags = AddOp->getFastMathFlags();
909         Flags &= SubOp->getFastMathFlags();
910         RI->setFastMathFlags(Flags);
911         return RI;
912       } else
913         return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
914     }
915   }
916   return nullptr;
917 }
918 
919 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) {
920   Instruction *ExtInst;
921   if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) &&
922       !match(Sel.getFalseValue(), m_Instruction(ExtInst)))
923     return nullptr;
924 
925   auto ExtOpcode = ExtInst->getOpcode();
926   if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt)
927     return nullptr;
928 
929   // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too.
930   Value *X = ExtInst->getOperand(0);
931   Type *SmallType = X->getType();
932   if (!SmallType->getScalarType()->isIntegerTy(1))
933     return nullptr;
934 
935   Constant *C;
936   if (!match(Sel.getTrueValue(), m_Constant(C)) &&
937       !match(Sel.getFalseValue(), m_Constant(C)))
938     return nullptr;
939 
940   // If the constant is the same after truncation to the smaller type and
941   // extension to the original type, we can narrow the select.
942   Value *Cond = Sel.getCondition();
943   Type *SelType = Sel.getType();
944   Constant *TruncC = ConstantExpr::getTrunc(C, SmallType);
945   Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType);
946   if (ExtC == C) {
947     Value *TruncCVal = cast<Value>(TruncC);
948     if (ExtInst == Sel.getFalseValue())
949       std::swap(X, TruncCVal);
950 
951     // select Cond, (ext X), C --> ext(select Cond, X, C')
952     // select Cond, C, (ext X) --> ext(select Cond, C', X)
953     Value *NewSel = Builder->CreateSelect(Cond, X, TruncCVal, "narrow", &Sel);
954     return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType);
955   }
956 
957   // If one arm of the select is the extend of the condition, replace that arm
958   // with the extension of the appropriate known bool value.
959   if (Cond == X) {
960     SelectInst *NewSel;
961     if (ExtInst == Sel.getTrueValue()) {
962       // select X, (sext X), C --> select X, -1, C
963       // select X, (zext X), C --> select X,  1, C
964       Constant *One = ConstantInt::getTrue(SmallType);
965       Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType);
966       NewSel = SelectInst::Create(Cond, AllOnesOrOne, C);
967     } else {
968       // select X, C, (sext X) --> select X, C, 0
969       // select X, C, (zext X) --> select X, C, 0
970       Constant *Zero = ConstantInt::getNullValue(SelType);
971       NewSel = SelectInst::Create(Cond, C, Zero);
972     }
973     NewSel->copyMetadata(Sel);
974     return NewSel;
975   }
976 
977   return nullptr;
978 }
979 
980 /// Try to transform a vector select with a constant condition vector into a
981 /// shuffle for easier combining with other shuffles and insert/extract.
982 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) {
983   Value *CondVal = SI.getCondition();
984   Constant *CondC;
985   if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC)))
986     return nullptr;
987 
988   unsigned NumElts = CondVal->getType()->getVectorNumElements();
989   SmallVector<Constant *, 16> Mask;
990   Mask.reserve(NumElts);
991   Type *Int32Ty = Type::getInt32Ty(CondVal->getContext());
992   for (unsigned i = 0; i != NumElts; ++i) {
993     Constant *Elt = CondC->getAggregateElement(i);
994     if (!Elt)
995       return nullptr;
996 
997     if (Elt->isOneValue()) {
998       // If the select condition element is true, choose from the 1st vector.
999       Mask.push_back(ConstantInt::get(Int32Ty, i));
1000     } else if (Elt->isNullValue()) {
1001       // If the select condition element is false, choose from the 2nd vector.
1002       Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts));
1003     } else if (isa<UndefValue>(Elt)) {
1004       // If the select condition element is undef, the shuffle mask is undef.
1005       Mask.push_back(UndefValue::get(Int32Ty));
1006     } else {
1007       // Bail out on a constant expression.
1008       return nullptr;
1009     }
1010   }
1011 
1012   return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(),
1013                                ConstantVector::get(Mask));
1014 }
1015 
1016 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
1017   Value *CondVal = SI.getCondition();
1018   Value *TrueVal = SI.getTrueValue();
1019   Value *FalseVal = SI.getFalseValue();
1020   Type *SelType = SI.getType();
1021 
1022   if (Value *V =
1023           SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, &TLI, &DT, &AC))
1024     return replaceInstUsesWith(SI, V);
1025 
1026   if (Instruction *I = canonicalizeSelectToShuffle(SI))
1027     return I;
1028 
1029   if (SelType->getScalarType()->isIntegerTy(1) &&
1030       TrueVal->getType() == CondVal->getType()) {
1031     if (match(TrueVal, m_One())) {
1032       // Change: A = select B, true, C --> A = or B, C
1033       return BinaryOperator::CreateOr(CondVal, FalseVal);
1034     }
1035     if (match(TrueVal, m_Zero())) {
1036       // Change: A = select B, false, C --> A = and !B, C
1037       Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1038       return BinaryOperator::CreateAnd(NotCond, FalseVal);
1039     }
1040     if (match(FalseVal, m_Zero())) {
1041       // Change: A = select B, C, false --> A = and B, C
1042       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1043     }
1044     if (match(FalseVal, m_One())) {
1045       // Change: A = select B, C, true --> A = or !B, C
1046       Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1047       return BinaryOperator::CreateOr(NotCond, TrueVal);
1048     }
1049 
1050     // select a, a, b  -> a | b
1051     // select a, b, a  -> a & b
1052     if (CondVal == TrueVal)
1053       return BinaryOperator::CreateOr(CondVal, FalseVal);
1054     if (CondVal == FalseVal)
1055       return BinaryOperator::CreateAnd(CondVal, TrueVal);
1056 
1057     // select a, ~a, b -> (~a) & b
1058     // select a, b, ~a -> (~a) | b
1059     if (match(TrueVal, m_Not(m_Specific(CondVal))))
1060       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
1061     if (match(FalseVal, m_Not(m_Specific(CondVal))))
1062       return BinaryOperator::CreateOr(TrueVal, FalseVal);
1063   }
1064 
1065   // Selecting between two integer or vector splat integer constants?
1066   //
1067   // Note that we don't handle a scalar select of vectors:
1068   // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0>
1069   // because that may need 3 instructions to splat the condition value:
1070   // extend, insertelement, shufflevector.
1071   if (CondVal->getType()->isVectorTy() == SelType->isVectorTy()) {
1072     // select C, 1, 0 -> zext C to int
1073     if (match(TrueVal, m_One()) && match(FalseVal, m_Zero()))
1074       return new ZExtInst(CondVal, SelType);
1075 
1076     // select C, -1, 0 -> sext C to int
1077     if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero()))
1078       return new SExtInst(CondVal, SelType);
1079 
1080     // select C, 0, 1 -> zext !C to int
1081     if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) {
1082       Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1083       return new ZExtInst(NotCond, SelType);
1084     }
1085 
1086     // select C, 0, -1 -> sext !C to int
1087     if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) {
1088       Value *NotCond = Builder->CreateNot(CondVal, "not." + CondVal->getName());
1089       return new SExtInst(NotCond, SelType);
1090     }
1091   }
1092 
1093   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
1094     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal))
1095       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
1096         return replaceInstUsesWith(SI, V);
1097 
1098   // See if we are selecting two values based on a comparison of the two values.
1099   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
1100     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
1101       // Transform (X == Y) ? X : Y  -> Y
1102       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1103         // This is not safe in general for floating point:
1104         // consider X== -0, Y== +0.
1105         // It becomes safe if either operand is a nonzero constant.
1106         ConstantFP *CFPt, *CFPf;
1107         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1108               !CFPt->getValueAPF().isZero()) ||
1109             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1110              !CFPf->getValueAPF().isZero()))
1111         return replaceInstUsesWith(SI, FalseVal);
1112       }
1113       // Transform (X une Y) ? X : Y  -> X
1114       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1115         // This is not safe in general for floating point:
1116         // consider X== -0, Y== +0.
1117         // It becomes safe if either operand is a nonzero constant.
1118         ConstantFP *CFPt, *CFPf;
1119         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1120               !CFPt->getValueAPF().isZero()) ||
1121             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1122              !CFPf->getValueAPF().isZero()))
1123         return replaceInstUsesWith(SI, TrueVal);
1124       }
1125 
1126       // Canonicalize to use ordered comparisons by swapping the select
1127       // operands.
1128       //
1129       // e.g.
1130       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
1131       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1132         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1133         IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1134         Builder->setFastMathFlags(FCI->getFastMathFlags());
1135         Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
1136                                              FCI->getName() + ".inv");
1137 
1138         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1139                                   SI.getName() + ".p");
1140       }
1141 
1142       // NOTE: if we wanted to, this is where to detect MIN/MAX
1143     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
1144       // Transform (X == Y) ? Y : X  -> X
1145       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
1146         // This is not safe in general for floating point:
1147         // consider X== -0, Y== +0.
1148         // It becomes safe if either operand is a nonzero constant.
1149         ConstantFP *CFPt, *CFPf;
1150         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1151               !CFPt->getValueAPF().isZero()) ||
1152             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1153              !CFPf->getValueAPF().isZero()))
1154           return replaceInstUsesWith(SI, FalseVal);
1155       }
1156       // Transform (X une Y) ? Y : X  -> Y
1157       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
1158         // This is not safe in general for floating point:
1159         // consider X== -0, Y== +0.
1160         // It becomes safe if either operand is a nonzero constant.
1161         ConstantFP *CFPt, *CFPf;
1162         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
1163               !CFPt->getValueAPF().isZero()) ||
1164             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
1165              !CFPf->getValueAPF().isZero()))
1166           return replaceInstUsesWith(SI, TrueVal);
1167       }
1168 
1169       // Canonicalize to use ordered comparisons by swapping the select
1170       // operands.
1171       //
1172       // e.g.
1173       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
1174       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
1175         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
1176         IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1177         Builder->setFastMathFlags(FCI->getFastMathFlags());
1178         Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
1179                                              FCI->getName() + ".inv");
1180 
1181         return SelectInst::Create(NewCond, FalseVal, TrueVal,
1182                                   SI.getName() + ".p");
1183       }
1184 
1185       // NOTE: if we wanted to, this is where to detect MIN/MAX
1186     }
1187     // NOTE: if we wanted to, this is where to detect ABS
1188   }
1189 
1190   // See if we are selecting two values based on a comparison of the two values.
1191   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
1192     if (Instruction *Result = foldSelectInstWithICmp(SI, ICI))
1193       return Result;
1194 
1195   if (Instruction *Add = foldAddSubSelect(SI, *Builder))
1196     return Add;
1197 
1198   // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
1199   auto *TI = dyn_cast<Instruction>(TrueVal);
1200   auto *FI = dyn_cast<Instruction>(FalseVal);
1201   if (TI && FI && TI->getOpcode() == FI->getOpcode())
1202     if (Instruction *IV = foldSelectOpOp(SI, TI, FI))
1203       return IV;
1204 
1205   if (Instruction *I = foldSelectExtConst(SI))
1206     return I;
1207 
1208   // See if we can fold the select into one of our operands.
1209   if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) {
1210     if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal))
1211       return FoldI;
1212 
1213     Value *LHS, *RHS, *LHS2, *RHS2;
1214     Instruction::CastOps CastOp;
1215     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
1216     auto SPF = SPR.Flavor;
1217 
1218     if (SelectPatternResult::isMinOrMax(SPF)) {
1219       // Canonicalize so that type casts are outside select patterns.
1220       if (LHS->getType()->getPrimitiveSizeInBits() !=
1221           SelType->getPrimitiveSizeInBits()) {
1222         CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
1223 
1224         Value *Cmp;
1225         if (CmpInst::isIntPredicate(Pred)) {
1226           Cmp = Builder->CreateICmp(Pred, LHS, RHS);
1227         } else {
1228           IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
1229           auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
1230           Builder->setFastMathFlags(FMF);
1231           Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
1232         }
1233 
1234         Value *NewSI = Builder->CreateCast(
1235             CastOp, Builder->CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI),
1236             SelType);
1237         return replaceInstUsesWith(SI, NewSI);
1238       }
1239     }
1240 
1241     if (SPF) {
1242       // MAX(MAX(a, b), a) -> MAX(a, b)
1243       // MIN(MIN(a, b), a) -> MIN(a, b)
1244       // MAX(MIN(a, b), a) -> a
1245       // MIN(MAX(a, b), a) -> a
1246       // ABS(ABS(a)) -> ABS(a)
1247       // NABS(NABS(a)) -> NABS(a)
1248       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
1249         if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
1250                                           SI, SPF, RHS))
1251           return R;
1252       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
1253         if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
1254                                           SI, SPF, LHS))
1255           return R;
1256     }
1257 
1258     // MAX(~a, ~b) -> ~MIN(a, b)
1259     if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
1260       if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
1261           IsFreeToInvert(RHS, RHS->hasNUses(2))) {
1262 
1263         // This transform adds a xor operation and that extra cost needs to be
1264         // justified.  We look for simplifications that will result from
1265         // applying this rule:
1266 
1267         bool Profitable =
1268             (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
1269             (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
1270             (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
1271 
1272         if (Profitable) {
1273           Value *NewLHS = Builder->CreateNot(LHS);
1274           Value *NewRHS = Builder->CreateNot(RHS);
1275           Value *NewCmp = SPF == SPF_SMAX
1276                               ? Builder->CreateICmpSLT(NewLHS, NewRHS)
1277                               : Builder->CreateICmpULT(NewLHS, NewRHS);
1278           Value *NewSI =
1279               Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
1280           return replaceInstUsesWith(SI, NewSI);
1281         }
1282       }
1283     }
1284 
1285     // TODO.
1286     // ABS(-X) -> ABS(X)
1287   }
1288 
1289   // See if we can fold the select into a phi node if the condition is a select.
1290   if (isa<PHINode>(SI.getCondition()))
1291     // The true/false values have to be live in the PHI predecessor's blocks.
1292     if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
1293         canSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
1294       if (Instruction *NV = FoldOpIntoPhi(SI))
1295         return NV;
1296 
1297   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
1298     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
1299       // select(C, select(C, a, b), c) -> select(C, a, c)
1300       if (TrueSI->getCondition() == CondVal) {
1301         if (SI.getTrueValue() == TrueSI->getTrueValue())
1302           return nullptr;
1303         SI.setOperand(1, TrueSI->getTrueValue());
1304         return &SI;
1305       }
1306       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
1307       // We choose this as normal form to enable folding on the And and shortening
1308       // paths for the values (this helps GetUnderlyingObjects() for example).
1309       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
1310         Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
1311         SI.setOperand(0, And);
1312         SI.setOperand(1, TrueSI->getTrueValue());
1313         return &SI;
1314       }
1315     }
1316   }
1317   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
1318     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
1319       // select(C, a, select(C, b, c)) -> select(C, a, c)
1320       if (FalseSI->getCondition() == CondVal) {
1321         if (SI.getFalseValue() == FalseSI->getFalseValue())
1322           return nullptr;
1323         SI.setOperand(2, FalseSI->getFalseValue());
1324         return &SI;
1325       }
1326       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
1327       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
1328         Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
1329         SI.setOperand(0, Or);
1330         SI.setOperand(2, FalseSI->getFalseValue());
1331         return &SI;
1332       }
1333     }
1334   }
1335 
1336   if (BinaryOperator::isNot(CondVal)) {
1337     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
1338     SI.setOperand(1, FalseVal);
1339     SI.setOperand(2, TrueVal);
1340     return &SI;
1341   }
1342 
1343   if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) {
1344     unsigned VWidth = VecTy->getNumElements();
1345     APInt UndefElts(VWidth, 0);
1346     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1347     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
1348       if (V != &SI)
1349         return replaceInstUsesWith(SI, V);
1350       return &SI;
1351     }
1352 
1353     if (isa<ConstantAggregateZero>(CondVal)) {
1354       return replaceInstUsesWith(SI, FalseVal);
1355     }
1356   }
1357 
1358   // See if we can determine the result of this select based on a dominating
1359   // condition.
1360   BasicBlock *Parent = SI.getParent();
1361   if (BasicBlock *Dom = Parent->getSinglePredecessor()) {
1362     auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator());
1363     if (PBI && PBI->isConditional() &&
1364         PBI->getSuccessor(0) != PBI->getSuccessor(1) &&
1365         (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) {
1366       bool CondIsFalse = PBI->getSuccessor(1) == Parent;
1367       Optional<bool> Implication = isImpliedCondition(
1368         PBI->getCondition(), SI.getCondition(), DL, CondIsFalse);
1369       if (Implication) {
1370         Value *V = *Implication ? TrueVal : FalseVal;
1371         return replaceInstUsesWith(SI, V);
1372       }
1373     }
1374   }
1375 
1376   return nullptr;
1377 }
1378