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