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