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