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