LLVM  mainline
InstCombineSelect.cpp
Go to the documentation of this file.
00001 //===- InstCombineSelect.cpp ----------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visitSelect function.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombineInternal.h"
00015 #include "llvm/Analysis/ConstantFolding.h"
00016 #include "llvm/Analysis/InstructionSimplify.h"
00017 #include "llvm/Analysis/ValueTracking.h"
00018 #include "llvm/IR/PatternMatch.h"
00019 using namespace llvm;
00020 using namespace PatternMatch;
00021 
00022 #define DEBUG_TYPE "instcombine"
00023 
00024 static SelectPatternFlavor
00025 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) {
00026   switch (SPF) {
00027   default:
00028     llvm_unreachable("unhandled!");
00029 
00030   case SPF_SMIN:
00031     return SPF_SMAX;
00032   case SPF_UMIN:
00033     return SPF_UMAX;
00034   case SPF_SMAX:
00035     return SPF_SMIN;
00036   case SPF_UMAX:
00037     return SPF_UMIN;
00038   }
00039 }
00040 
00041 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF,
00042                                                    bool Ordered=false) {
00043   switch (SPF) {
00044   default:
00045     llvm_unreachable("unhandled!");
00046 
00047   case SPF_SMIN:
00048     return ICmpInst::ICMP_SLT;
00049   case SPF_UMIN:
00050     return ICmpInst::ICMP_ULT;
00051   case SPF_SMAX:
00052     return ICmpInst::ICMP_SGT;
00053   case SPF_UMAX:
00054     return ICmpInst::ICMP_UGT;
00055   case SPF_FMINNUM:
00056     return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT;
00057   case SPF_FMAXNUM:
00058     return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT;
00059   }
00060 }
00061 
00062 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder,
00063                                           SelectPatternFlavor SPF, Value *A,
00064                                           Value *B) {
00065   CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF);
00066   assert(CmpInst::isIntPredicate(Pred));
00067   return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B);
00068 }
00069 
00070 /// We want to turn code that looks like this:
00071 ///   %C = or %A, %B
00072 ///   %D = select %cond, %C, %A
00073 /// into:
00074 ///   %C = select %cond, %B, 0
00075 ///   %D = or %A, %C
00076 ///
00077 /// Assuming that the specified instruction is an operand to the select, return
00078 /// a bitmask indicating which operands of this instruction are foldable if they
00079 /// equal the other incoming value of the select.
00080 ///
00081 static unsigned GetSelectFoldableOperands(Instruction *I) {
00082   switch (I->getOpcode()) {
00083   case Instruction::Add:
00084   case Instruction::Mul:
00085   case Instruction::And:
00086   case Instruction::Or:
00087   case Instruction::Xor:
00088     return 3;              // Can fold through either operand.
00089   case Instruction::Sub:   // Can only fold on the amount subtracted.
00090   case Instruction::Shl:   // Can only fold on the shift amount.
00091   case Instruction::LShr:
00092   case Instruction::AShr:
00093     return 1;
00094   default:
00095     return 0;              // Cannot fold
00096   }
00097 }
00098 
00099 /// For the same transformation as the previous function, return the identity
00100 /// constant that goes into the select.
00101 static Constant *GetSelectFoldableConstant(Instruction *I) {
00102   switch (I->getOpcode()) {
00103   default: llvm_unreachable("This cannot happen!");
00104   case Instruction::Add:
00105   case Instruction::Sub:
00106   case Instruction::Or:
00107   case Instruction::Xor:
00108   case Instruction::Shl:
00109   case Instruction::LShr:
00110   case Instruction::AShr:
00111     return Constant::getNullValue(I->getType());
00112   case Instruction::And:
00113     return Constant::getAllOnesValue(I->getType());
00114   case Instruction::Mul:
00115     return ConstantInt::get(I->getType(), 1);
00116   }
00117 }
00118 
00119 /// Here we have (select c, TI, FI), and we know that TI and FI
00120 /// have the same opcode and only one use each.  Try to simplify this.
00121 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
00122                                           Instruction *FI) {
00123   if (TI->getNumOperands() == 1) {
00124     // If this is a non-volatile load or a cast from the same type,
00125     // merge.
00126     if (TI->isCast()) {
00127       Type *FIOpndTy = FI->getOperand(0)->getType();
00128       if (TI->getOperand(0)->getType() != FIOpndTy)
00129         return nullptr;
00130       // The select condition may be a vector. We may only change the operand
00131       // type if the vector width remains the same (and matches the condition).
00132       Type *CondTy = SI.getCondition()->getType();
00133       if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() ||
00134           CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()))
00135         return nullptr;
00136     } else {
00137       return nullptr;  // unknown unary op.
00138     }
00139 
00140     // Fold this by inserting a select from the input values.
00141     Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0),
00142                                          FI->getOperand(0), SI.getName()+".v");
00143     return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
00144                             TI->getType());
00145   }
00146 
00147   // Only handle binary operators here.
00148   if (!isa<BinaryOperator>(TI))
00149     return nullptr;
00150 
00151   // Figure out if the operations have any operands in common.
00152   Value *MatchOp, *OtherOpT, *OtherOpF;
00153   bool MatchIsOpZero;
00154   if (TI->getOperand(0) == FI->getOperand(0)) {
00155     MatchOp  = TI->getOperand(0);
00156     OtherOpT = TI->getOperand(1);
00157     OtherOpF = FI->getOperand(1);
00158     MatchIsOpZero = true;
00159   } else if (TI->getOperand(1) == FI->getOperand(1)) {
00160     MatchOp  = TI->getOperand(1);
00161     OtherOpT = TI->getOperand(0);
00162     OtherOpF = FI->getOperand(0);
00163     MatchIsOpZero = false;
00164   } else if (!TI->isCommutative()) {
00165     return nullptr;
00166   } else if (TI->getOperand(0) == FI->getOperand(1)) {
00167     MatchOp  = TI->getOperand(0);
00168     OtherOpT = TI->getOperand(1);
00169     OtherOpF = FI->getOperand(0);
00170     MatchIsOpZero = true;
00171   } else if (TI->getOperand(1) == FI->getOperand(0)) {
00172     MatchOp  = TI->getOperand(1);
00173     OtherOpT = TI->getOperand(0);
00174     OtherOpF = FI->getOperand(1);
00175     MatchIsOpZero = true;
00176   } else {
00177     return nullptr;
00178   }
00179 
00180   // If we reach here, they do have operations in common.
00181   Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT,
00182                                        OtherOpF, SI.getName()+".v");
00183 
00184   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
00185     if (MatchIsOpZero)
00186       return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
00187     else
00188       return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
00189   }
00190   llvm_unreachable("Shouldn't get here");
00191 }
00192 
00193 static bool isSelect01(Constant *C1, Constant *C2) {
00194   ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
00195   if (!C1I)
00196     return false;
00197   ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
00198   if (!C2I)
00199     return false;
00200   if (!C1I->isZero() && !C2I->isZero()) // One side must be zero.
00201     return false;
00202   return C1I->isOne() || C1I->isAllOnesValue() ||
00203          C2I->isOne() || C2I->isAllOnesValue();
00204 }
00205 
00206 /// Try to fold the select into one of the operands to allow further
00207 /// optimization.
00208 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
00209                                             Value *FalseVal) {
00210   // See the comment above GetSelectFoldableOperands for a description of the
00211   // transformation we are doing here.
00212   if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
00213     if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
00214         !isa<Constant>(FalseVal)) {
00215       if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
00216         unsigned OpToFold = 0;
00217         if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
00218           OpToFold = 1;
00219         } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
00220           OpToFold = 2;
00221         }
00222 
00223         if (OpToFold) {
00224           Constant *C = GetSelectFoldableConstant(TVI);
00225           Value *OOp = TVI->getOperand(2-OpToFold);
00226           // Avoid creating select between 2 constants unless it's selecting
00227           // between 0, 1 and -1.
00228           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
00229             Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C);
00230             NewSel->takeName(TVI);
00231             BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI);
00232             BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(),
00233                                                         FalseVal, NewSel);
00234             if (isa<PossiblyExactOperator>(BO))
00235               BO->setIsExact(TVI_BO->isExact());
00236             if (isa<OverflowingBinaryOperator>(BO)) {
00237               BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap());
00238               BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap());
00239             }
00240             return BO;
00241           }
00242         }
00243       }
00244     }
00245   }
00246 
00247   if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
00248     if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
00249         !isa<Constant>(TrueVal)) {
00250       if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
00251         unsigned OpToFold = 0;
00252         if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
00253           OpToFold = 1;
00254         } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
00255           OpToFold = 2;
00256         }
00257 
00258         if (OpToFold) {
00259           Constant *C = GetSelectFoldableConstant(FVI);
00260           Value *OOp = FVI->getOperand(2-OpToFold);
00261           // Avoid creating select between 2 constants unless it's selecting
00262           // between 0, 1 and -1.
00263           if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
00264             Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp);
00265             NewSel->takeName(FVI);
00266             BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI);
00267             BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(),
00268                                                         TrueVal, NewSel);
00269             if (isa<PossiblyExactOperator>(BO))
00270               BO->setIsExact(FVI_BO->isExact());
00271             if (isa<OverflowingBinaryOperator>(BO)) {
00272               BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap());
00273               BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap());
00274             }
00275             return BO;
00276           }
00277         }
00278       }
00279     }
00280   }
00281 
00282   return nullptr;
00283 }
00284 
00285 /// We want to turn:
00286 ///   (select (icmp eq (and X, C1), 0), Y, (or Y, C2))
00287 /// into:
00288 ///   (or (shl (and X, C1), C3), y)
00289 /// iff:
00290 ///   C1 and C2 are both powers of 2
00291 /// where:
00292 ///   C3 = Log(C2) - Log(C1)
00293 ///
00294 /// This transform handles cases where:
00295 /// 1. The icmp predicate is inverted
00296 /// 2. The select operands are reversed
00297 /// 3. The magnitude of C2 and C1 are flipped
00298 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal,
00299                                   Value *FalseVal,
00300                                   InstCombiner::BuilderTy *Builder) {
00301   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
00302   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
00303     return nullptr;
00304 
00305   Value *CmpLHS = IC->getOperand(0);
00306   Value *CmpRHS = IC->getOperand(1);
00307 
00308   if (!match(CmpRHS, m_Zero()))
00309     return nullptr;
00310 
00311   Value *X;
00312   const APInt *C1;
00313   if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1))))
00314     return nullptr;
00315 
00316   const APInt *C2;
00317   bool OrOnTrueVal = false;
00318   bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2)));
00319   if (!OrOnFalseVal)
00320     OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2)));
00321 
00322   if (!OrOnFalseVal && !OrOnTrueVal)
00323     return nullptr;
00324 
00325   Value *V = CmpLHS;
00326   Value *Y = OrOnFalseVal ? TrueVal : FalseVal;
00327 
00328   unsigned C1Log = C1->logBase2();
00329   unsigned C2Log = C2->logBase2();
00330   if (C2Log > C1Log) {
00331     V = Builder->CreateZExtOrTrunc(V, Y->getType());
00332     V = Builder->CreateShl(V, C2Log - C1Log);
00333   } else if (C1Log > C2Log) {
00334     V = Builder->CreateLShr(V, C1Log - C2Log);
00335     V = Builder->CreateZExtOrTrunc(V, Y->getType());
00336   } else
00337     V = Builder->CreateZExtOrTrunc(V, Y->getType());
00338 
00339   ICmpInst::Predicate Pred = IC->getPredicate();
00340   if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) ||
00341       (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal))
00342     V = Builder->CreateXor(V, *C2);
00343 
00344   return Builder->CreateOr(V, Y);
00345 }
00346 
00347 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single
00348 /// call to cttz/ctlz with flag 'is_zero_undef' cleared.
00349 ///
00350 /// For example, we can fold the following code sequence:
00351 /// \code
00352 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true)
00353 ///   %1 = icmp ne i32 %x, 0
00354 ///   %2 = select i1 %1, i32 %0, i32 32
00355 /// \code
00356 /// 
00357 /// into:
00358 ///   %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false)
00359 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal,
00360                                   InstCombiner::BuilderTy *Builder) {
00361   ICmpInst::Predicate Pred = ICI->getPredicate();
00362   Value *CmpLHS = ICI->getOperand(0);
00363   Value *CmpRHS = ICI->getOperand(1);
00364 
00365   // Check if the condition value compares a value for equality against zero.
00366   if (!ICI->isEquality() || !match(CmpRHS, m_Zero()))
00367     return nullptr;
00368 
00369   Value *Count = FalseVal;
00370   Value *ValueOnZero = TrueVal;
00371   if (Pred == ICmpInst::ICMP_NE)
00372     std::swap(Count, ValueOnZero);
00373 
00374   // Skip zero extend/truncate.
00375   Value *V = nullptr;
00376   if (match(Count, m_ZExt(m_Value(V))) ||
00377       match(Count, m_Trunc(m_Value(V))))
00378     Count = V;
00379 
00380   // Check if the value propagated on zero is a constant number equal to the
00381   // sizeof in bits of 'Count'.
00382   unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits();
00383   if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits)))
00384     return nullptr;
00385 
00386   // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the
00387   // input to the cttz/ctlz is used as LHS for the compare instruction.
00388   if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) ||
00389       match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) {
00390     IntrinsicInst *II = cast<IntrinsicInst>(Count);
00391     IRBuilder<> Builder(II);
00392     // Explicitly clear the 'undef_on_zero' flag.
00393     IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone());
00394     Type *Ty = NewI->getArgOperand(1)->getType();
00395     NewI->setArgOperand(1, Constant::getNullValue(Ty));
00396     Builder.Insert(NewI);
00397     return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType());
00398   }
00399 
00400   return nullptr;
00401 }
00402 
00403 /// Visit a SelectInst that has an ICmpInst as its first operand.
00404 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
00405                                                    ICmpInst *ICI) {
00406   bool Changed = false;
00407   ICmpInst::Predicate Pred = ICI->getPredicate();
00408   Value *CmpLHS = ICI->getOperand(0);
00409   Value *CmpRHS = ICI->getOperand(1);
00410   Value *TrueVal = SI.getTrueValue();
00411   Value *FalseVal = SI.getFalseValue();
00412 
00413   // Check cases where the comparison is with a constant that
00414   // can be adjusted to fit the min/max idiom. We may move or edit ICI
00415   // here, so make sure the select is the only user.
00416   if (ICI->hasOneUse())
00417     if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
00418       switch (Pred) {
00419       default: break;
00420       case ICmpInst::ICMP_ULT:
00421       case ICmpInst::ICMP_SLT:
00422       case ICmpInst::ICMP_UGT:
00423       case ICmpInst::ICMP_SGT: {
00424         // These transformations only work for selects over integers.
00425         IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType());
00426         if (!SelectTy)
00427           break;
00428 
00429         Constant *AdjustedRHS;
00430         if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT)
00431           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1);
00432         else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT)
00433           AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1);
00434 
00435         // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
00436         // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
00437         if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
00438             (CmpLHS == FalseVal && AdjustedRHS == TrueVal))
00439           ; // Nothing to do here. Values match without any sign/zero extension.
00440 
00441         // Types do not match. Instead of calculating this with mixed types
00442         // promote all to the larger type. This enables scalar evolution to
00443         // analyze this expression.
00444         else if (CmpRHS->getType()->getScalarSizeInBits()
00445                  < SelectTy->getBitWidth()) {
00446           Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy);
00447 
00448           // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X
00449           // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X
00450           // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X
00451           // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X
00452           if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) &&
00453                 sextRHS == FalseVal) {
00454             CmpLHS = TrueVal;
00455             AdjustedRHS = sextRHS;
00456           } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) &&
00457                      sextRHS == TrueVal) {
00458             CmpLHS = FalseVal;
00459             AdjustedRHS = sextRHS;
00460           } else if (ICI->isUnsigned()) {
00461             Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy);
00462             // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X
00463             // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X
00464             // zext + signed compare cannot be changed:
00465             //    0xff <s 0x00, but 0x00ff >s 0x0000
00466             if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) &&
00467                 zextRHS == FalseVal) {
00468               CmpLHS = TrueVal;
00469               AdjustedRHS = zextRHS;
00470             } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) &&
00471                        zextRHS == TrueVal) {
00472               CmpLHS = FalseVal;
00473               AdjustedRHS = zextRHS;
00474             } else
00475               break;
00476           } else
00477             break;
00478         } else
00479           break;
00480 
00481         Pred = ICmpInst::getSwappedPredicate(Pred);
00482         CmpRHS = AdjustedRHS;
00483         std::swap(FalseVal, TrueVal);
00484         ICI->setPredicate(Pred);
00485         ICI->setOperand(0, CmpLHS);
00486         ICI->setOperand(1, CmpRHS);
00487         SI.setOperand(1, TrueVal);
00488         SI.setOperand(2, FalseVal);
00489 
00490         // Move ICI instruction right before the select instruction. Otherwise
00491         // the sext/zext value may be defined after the ICI instruction uses it.
00492         ICI->moveBefore(&SI);
00493 
00494         Changed = true;
00495         break;
00496       }
00497       }
00498     }
00499 
00500   // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
00501   // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
00502   // FIXME: Type and constness constraints could be lifted, but we have to
00503   //        watch code size carefully. We should consider xor instead of
00504   //        sub/add when we decide to do that.
00505   if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
00506     if (TrueVal->getType() == Ty) {
00507       if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
00508         ConstantInt *C1 = nullptr, *C2 = nullptr;
00509         if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
00510           C1 = dyn_cast<ConstantInt>(TrueVal);
00511           C2 = dyn_cast<ConstantInt>(FalseVal);
00512         } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
00513           C1 = dyn_cast<ConstantInt>(FalseVal);
00514           C2 = dyn_cast<ConstantInt>(TrueVal);
00515         }
00516         if (C1 && C2) {
00517           // This shift results in either -1 or 0.
00518           Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
00519 
00520           // Check if we can express the operation with a single or.
00521           if (C2->isAllOnesValue())
00522             return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
00523 
00524           Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
00525           return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
00526         }
00527       }
00528     }
00529   }
00530 
00531   // NOTE: if we wanted to, this is where to detect integer MIN/MAX
00532 
00533   if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) {
00534     if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) {
00535       // Transform (X == C) ? X : Y -> (X == C) ? C : Y
00536       SI.setOperand(1, CmpRHS);
00537       Changed = true;
00538     } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) {
00539       // Transform (X != C) ? Y : X -> (X != C) ? Y : C
00540       SI.setOperand(2, CmpRHS);
00541       Changed = true;
00542     }
00543   }
00544 
00545   {
00546     unsigned BitWidth = DL.getTypeSizeInBits(TrueVal->getType());
00547     APInt MinSignedValue = APInt::getSignBit(BitWidth);
00548     Value *X;
00549     const APInt *Y, *C;
00550     bool TrueWhenUnset;
00551     bool IsBitTest = false;
00552     if (ICmpInst::isEquality(Pred) &&
00553         match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) &&
00554         match(CmpRHS, m_Zero())) {
00555       IsBitTest = true;
00556       TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
00557     } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
00558       X = CmpLHS;
00559       Y = &MinSignedValue;
00560       IsBitTest = true;
00561       TrueWhenUnset = false;
00562     } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
00563       X = CmpLHS;
00564       Y = &MinSignedValue;
00565       IsBitTest = true;
00566       TrueWhenUnset = true;
00567     }
00568     if (IsBitTest) {
00569       Value *V = nullptr;
00570       // (X & Y) == 0 ? X : X ^ Y  --> X & ~Y
00571       if (TrueWhenUnset && TrueVal == X &&
00572           match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
00573         V = Builder->CreateAnd(X, ~(*Y));
00574       // (X & Y) != 0 ? X ^ Y : X  --> X & ~Y
00575       else if (!TrueWhenUnset && FalseVal == X &&
00576                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
00577         V = Builder->CreateAnd(X, ~(*Y));
00578       // (X & Y) == 0 ? X ^ Y : X  --> X | Y
00579       else if (TrueWhenUnset && FalseVal == X &&
00580                match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
00581         V = Builder->CreateOr(X, *Y);
00582       // (X & Y) != 0 ? X : X ^ Y  --> X | Y
00583       else if (!TrueWhenUnset && TrueVal == X &&
00584                match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C)
00585         V = Builder->CreateOr(X, *Y);
00586 
00587       if (V)
00588         return ReplaceInstUsesWith(SI, V);
00589     }
00590   }
00591 
00592   if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder))
00593     return ReplaceInstUsesWith(SI, V);
00594 
00595   if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder))
00596     return ReplaceInstUsesWith(SI, V);
00597 
00598   return Changed ? &SI : nullptr;
00599 }
00600 
00601 
00602 /// SI is a select whose condition is a PHI node (but the two may be in
00603 /// different blocks). See if the true/false values (V) are live in all of the
00604 /// predecessor blocks of the PHI. For example, cases like this can't be mapped:
00605 ///
00606 ///   X = phi [ C1, BB1], [C2, BB2]
00607 ///   Y = add
00608 ///   Z = select X, Y, 0
00609 ///
00610 /// because Y is not live in BB1/BB2.
00611 ///
00612 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
00613                                                    const SelectInst &SI) {
00614   // If the value is a non-instruction value like a constant or argument, it
00615   // can always be mapped.
00616   const Instruction *I = dyn_cast<Instruction>(V);
00617   if (!I) return true;
00618 
00619   // If V is a PHI node defined in the same block as the condition PHI, we can
00620   // map the arguments.
00621   const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
00622 
00623   if (const PHINode *VP = dyn_cast<PHINode>(I))
00624     if (VP->getParent() == CondPHI->getParent())
00625       return true;
00626 
00627   // Otherwise, if the PHI and select are defined in the same block and if V is
00628   // defined in a different block, then we can transform it.
00629   if (SI.getParent() == CondPHI->getParent() &&
00630       I->getParent() != CondPHI->getParent())
00631     return true;
00632 
00633   // Otherwise we have a 'hard' case and we can't tell without doing more
00634   // detailed dominator based analysis, punt.
00635   return false;
00636 }
00637 
00638 /// We have an SPF (e.g. a min or max) of an SPF of the form:
00639 ///   SPF2(SPF1(A, B), C)
00640 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
00641                                         SelectPatternFlavor SPF1,
00642                                         Value *A, Value *B,
00643                                         Instruction &Outer,
00644                                         SelectPatternFlavor SPF2, Value *C) {
00645   if (C == A || C == B) {
00646     // MAX(MAX(A, B), B) -> MAX(A, B)
00647     // MIN(MIN(a, b), a) -> MIN(a, b)
00648     if (SPF1 == SPF2)
00649       return ReplaceInstUsesWith(Outer, Inner);
00650 
00651     // MAX(MIN(a, b), a) -> a
00652     // MIN(MAX(a, b), a) -> a
00653     if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
00654         (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
00655         (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
00656         (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
00657       return ReplaceInstUsesWith(Outer, C);
00658   }
00659 
00660   if (SPF1 == SPF2) {
00661     if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) {
00662       if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) {
00663         APInt ACB = CB->getValue();
00664         APInt ACC = CC->getValue();
00665 
00666         // MIN(MIN(A, 23), 97) -> MIN(A, 23)
00667         // MAX(MAX(A, 97), 23) -> MAX(A, 97)
00668         if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) ||
00669             (SPF1 == SPF_SMIN && ACB.sle(ACC)) ||
00670             (SPF1 == SPF_UMAX && ACB.uge(ACC)) ||
00671             (SPF1 == SPF_SMAX && ACB.sge(ACC)))
00672           return ReplaceInstUsesWith(Outer, Inner);
00673 
00674         // MIN(MIN(A, 97), 23) -> MIN(A, 23)
00675         // MAX(MAX(A, 23), 97) -> MAX(A, 97)
00676         if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) ||
00677             (SPF1 == SPF_SMIN && ACB.sgt(ACC)) ||
00678             (SPF1 == SPF_UMAX && ACB.ult(ACC)) ||
00679             (SPF1 == SPF_SMAX && ACB.slt(ACC))) {
00680           Outer.replaceUsesOfWith(Inner, A);
00681           return &Outer;
00682         }
00683       }
00684     }
00685   }
00686 
00687   // ABS(ABS(X)) -> ABS(X)
00688   // NABS(NABS(X)) -> NABS(X)
00689   if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) {
00690     return ReplaceInstUsesWith(Outer, Inner);
00691   }
00692 
00693   // ABS(NABS(X)) -> ABS(X)
00694   // NABS(ABS(X)) -> NABS(X)
00695   if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) ||
00696       (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) {
00697     SelectInst *SI = cast<SelectInst>(Inner);
00698     Value *NewSI = Builder->CreateSelect(
00699         SI->getCondition(), SI->getFalseValue(), SI->getTrueValue());
00700     return ReplaceInstUsesWith(Outer, NewSI);
00701   }
00702 
00703   auto IsFreeOrProfitableToInvert =
00704       [&](Value *V, Value *&NotV, bool &ElidesXor) {
00705     if (match(V, m_Not(m_Value(NotV)))) {
00706       // If V has at most 2 uses then we can get rid of the xor operation
00707       // entirely.
00708       ElidesXor |= !V->hasNUsesOrMore(3);
00709       return true;
00710     }
00711 
00712     if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) {
00713       NotV = nullptr;
00714       return true;
00715     }
00716 
00717     return false;
00718   };
00719 
00720   Value *NotA, *NotB, *NotC;
00721   bool ElidesXor = false;
00722 
00723   // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C)
00724   // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C)
00725   // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C)
00726   // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C)
00727   //
00728   // This transform is performance neutral if we can elide at least one xor from
00729   // the set of three operands, since we'll be tacking on an xor at the very
00730   // end.
00731   if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) &&
00732       IsFreeOrProfitableToInvert(B, NotB, ElidesXor) &&
00733       IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) {
00734     if (!NotA)
00735       NotA = Builder->CreateNot(A);
00736     if (!NotB)
00737       NotB = Builder->CreateNot(B);
00738     if (!NotC)
00739       NotC = Builder->CreateNot(C);
00740 
00741     Value *NewInner = generateMinMaxSelectPattern(
00742         Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB);
00743     Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern(
00744         Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC));
00745     return ReplaceInstUsesWith(Outer, NewOuter);
00746   }
00747 
00748   return nullptr;
00749 }
00750 
00751 /// If one of the constants is zero (we know they can't both be) and we have an
00752 /// icmp instruction with zero, and we have an 'and' with the non-constant value
00753 /// and a power of two we can turn the select into a shift on the result of the
00754 /// 'and'.
00755 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal,
00756                                 ConstantInt *FalseVal,
00757                                 InstCombiner::BuilderTy *Builder) {
00758   const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition());
00759   if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy())
00760     return nullptr;
00761 
00762   if (!match(IC->getOperand(1), m_Zero()))
00763     return nullptr;
00764 
00765   ConstantInt *AndRHS;
00766   Value *LHS = IC->getOperand(0);
00767   if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS))))
00768     return nullptr;
00769 
00770   // If both select arms are non-zero see if we have a select of the form
00771   // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic
00772   // for 'x ? 2^n : 0' and fix the thing up at the end.
00773   ConstantInt *Offset = nullptr;
00774   if (!TrueVal->isZero() && !FalseVal->isZero()) {
00775     if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2())
00776       Offset = FalseVal;
00777     else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2())
00778       Offset = TrueVal;
00779     else
00780       return nullptr;
00781 
00782     // Adjust TrueVal and FalseVal to the offset.
00783     TrueVal = ConstantInt::get(Builder->getContext(),
00784                                TrueVal->getValue() - Offset->getValue());
00785     FalseVal = ConstantInt::get(Builder->getContext(),
00786                                 FalseVal->getValue() - Offset->getValue());
00787   }
00788 
00789   // Make sure the mask in the 'and' and one of the select arms is a power of 2.
00790   if (!AndRHS->getValue().isPowerOf2() ||
00791       (!TrueVal->getValue().isPowerOf2() &&
00792        !FalseVal->getValue().isPowerOf2()))
00793     return nullptr;
00794 
00795   // Determine which shift is needed to transform result of the 'and' into the
00796   // desired result.
00797   ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal;
00798   unsigned ValZeros = ValC->getValue().logBase2();
00799   unsigned AndZeros = AndRHS->getValue().logBase2();
00800 
00801   // If types don't match we can still convert the select by introducing a zext
00802   // or a trunc of the 'and'. The trunc case requires that all of the truncated
00803   // bits are zero, we can figure that out by looking at the 'and' mask.
00804   if (AndZeros >= ValC->getBitWidth())
00805     return nullptr;
00806 
00807   Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType());
00808   if (ValZeros > AndZeros)
00809     V = Builder->CreateShl(V, ValZeros - AndZeros);
00810   else if (ValZeros < AndZeros)
00811     V = Builder->CreateLShr(V, AndZeros - ValZeros);
00812 
00813   // Okay, now we know that everything is set up, we just don't know whether we
00814   // have a icmp_ne or icmp_eq and whether the true or false val is the zero.
00815   bool ShouldNotVal = !TrueVal->isZero();
00816   ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
00817   if (ShouldNotVal)
00818     V = Builder->CreateXor(V, ValC);
00819 
00820   // Apply an offset if needed.
00821   if (Offset)
00822     V = Builder->CreateAdd(V, Offset);
00823   return V;
00824 }
00825 
00826 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
00827   Value *CondVal = SI.getCondition();
00828   Value *TrueVal = SI.getTrueValue();
00829   Value *FalseVal = SI.getFalseValue();
00830 
00831   if (Value *V =
00832           SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC))
00833     return ReplaceInstUsesWith(SI, V);
00834 
00835   if (SI.getType()->isIntegerTy(1)) {
00836     if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
00837       if (C->getZExtValue()) {
00838         // Change: A = select B, true, C --> A = or B, C
00839         return BinaryOperator::CreateOr(CondVal, FalseVal);
00840       }
00841       // Change: A = select B, false, C --> A = and !B, C
00842       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00843       return BinaryOperator::CreateAnd(NotCond, FalseVal);
00844     }
00845     if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
00846       if (!C->getZExtValue()) {
00847         // Change: A = select B, C, false --> A = and B, C
00848         return BinaryOperator::CreateAnd(CondVal, TrueVal);
00849       }
00850       // Change: A = select B, C, true --> A = or !B, C
00851       Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00852       return BinaryOperator::CreateOr(NotCond, TrueVal);
00853     }
00854 
00855     // select a, b, a  -> a&b
00856     // select a, a, b  -> a|b
00857     if (CondVal == TrueVal)
00858       return BinaryOperator::CreateOr(CondVal, FalseVal);
00859     if (CondVal == FalseVal)
00860       return BinaryOperator::CreateAnd(CondVal, TrueVal);
00861 
00862     // select a, ~a, b -> (~a)&b
00863     // select a, b, ~a -> (~a)|b
00864     if (match(TrueVal, m_Not(m_Specific(CondVal))))
00865       return BinaryOperator::CreateAnd(TrueVal, FalseVal);
00866     if (match(FalseVal, m_Not(m_Specific(CondVal))))
00867       return BinaryOperator::CreateOr(TrueVal, FalseVal);
00868   }
00869 
00870   // Selecting between two integer constants?
00871   if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
00872     if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
00873       // select C, 1, 0 -> zext C to int
00874       if (FalseValC->isZero() && TrueValC->getValue() == 1)
00875         return new ZExtInst(CondVal, SI.getType());
00876 
00877       // select C, -1, 0 -> sext C to int
00878       if (FalseValC->isZero() && TrueValC->isAllOnesValue())
00879         return new SExtInst(CondVal, SI.getType());
00880 
00881       // select C, 0, 1 -> zext !C to int
00882       if (TrueValC->isZero() && FalseValC->getValue() == 1) {
00883         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00884         return new ZExtInst(NotCond, SI.getType());
00885       }
00886 
00887       // select C, 0, -1 -> sext !C to int
00888       if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
00889         Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
00890         return new SExtInst(NotCond, SI.getType());
00891       }
00892 
00893       if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder))
00894         return ReplaceInstUsesWith(SI, V);
00895     }
00896 
00897   // See if we are selecting two values based on a comparison of the two values.
00898   if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
00899     if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
00900       // Transform (X == Y) ? X : Y  -> Y
00901       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
00902         // This is not safe in general for floating point:
00903         // consider X== -0, Y== +0.
00904         // It becomes safe if either operand is a nonzero constant.
00905         ConstantFP *CFPt, *CFPf;
00906         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00907               !CFPt->getValueAPF().isZero()) ||
00908             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00909              !CFPf->getValueAPF().isZero()))
00910         return ReplaceInstUsesWith(SI, FalseVal);
00911       }
00912       // Transform (X une Y) ? X : Y  -> X
00913       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
00914         // This is not safe in general for floating point:
00915         // consider X== -0, Y== +0.
00916         // It becomes safe if either operand is a nonzero constant.
00917         ConstantFP *CFPt, *CFPf;
00918         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00919               !CFPt->getValueAPF().isZero()) ||
00920             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00921              !CFPf->getValueAPF().isZero()))
00922         return ReplaceInstUsesWith(SI, TrueVal);
00923       }
00924 
00925       // Canonicalize to use ordered comparisons by swapping the select
00926       // operands.
00927       //
00928       // e.g.
00929       // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X
00930       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
00931         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
00932         IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
00933         Builder->setFastMathFlags(FCI->getFastMathFlags());
00934         Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal,
00935                                              FCI->getName() + ".inv");
00936 
00937         return SelectInst::Create(NewCond, FalseVal, TrueVal,
00938                                   SI.getName() + ".p");
00939       }
00940 
00941       // NOTE: if we wanted to, this is where to detect MIN/MAX
00942     } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
00943       // Transform (X == Y) ? Y : X  -> X
00944       if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
00945         // This is not safe in general for floating point:
00946         // consider X== -0, Y== +0.
00947         // It becomes safe if either operand is a nonzero constant.
00948         ConstantFP *CFPt, *CFPf;
00949         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00950               !CFPt->getValueAPF().isZero()) ||
00951             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00952              !CFPf->getValueAPF().isZero()))
00953           return ReplaceInstUsesWith(SI, FalseVal);
00954       }
00955       // Transform (X une Y) ? Y : X  -> Y
00956       if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
00957         // This is not safe in general for floating point:
00958         // consider X== -0, Y== +0.
00959         // It becomes safe if either operand is a nonzero constant.
00960         ConstantFP *CFPt, *CFPf;
00961         if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
00962               !CFPt->getValueAPF().isZero()) ||
00963             ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
00964              !CFPf->getValueAPF().isZero()))
00965           return ReplaceInstUsesWith(SI, TrueVal);
00966       }
00967 
00968       // Canonicalize to use ordered comparisons by swapping the select
00969       // operands.
00970       //
00971       // e.g.
00972       // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y
00973       if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) {
00974         FCmpInst::Predicate InvPred = FCI->getInversePredicate();
00975         IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
00976         Builder->setFastMathFlags(FCI->getFastMathFlags());
00977         Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal,
00978                                              FCI->getName() + ".inv");
00979 
00980         return SelectInst::Create(NewCond, FalseVal, TrueVal,
00981                                   SI.getName() + ".p");
00982       }
00983 
00984       // NOTE: if we wanted to, this is where to detect MIN/MAX
00985     }
00986     // NOTE: if we wanted to, this is where to detect ABS
00987   }
00988 
00989   // See if we are selecting two values based on a comparison of the two values.
00990   if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
00991     if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
00992       return Result;
00993 
00994   if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
00995     if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
00996       if (TI->hasOneUse() && FI->hasOneUse()) {
00997         Instruction *AddOp = nullptr, *SubOp = nullptr;
00998 
00999         // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
01000         if (TI->getOpcode() == FI->getOpcode())
01001           if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
01002             return IV;
01003 
01004         // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
01005         // even legal for FP.
01006         if ((TI->getOpcode() == Instruction::Sub &&
01007              FI->getOpcode() == Instruction::Add) ||
01008             (TI->getOpcode() == Instruction::FSub &&
01009              FI->getOpcode() == Instruction::FAdd)) {
01010           AddOp = FI; SubOp = TI;
01011         } else if ((FI->getOpcode() == Instruction::Sub &&
01012                     TI->getOpcode() == Instruction::Add) ||
01013                    (FI->getOpcode() == Instruction::FSub &&
01014                     TI->getOpcode() == Instruction::FAdd)) {
01015           AddOp = TI; SubOp = FI;
01016         }
01017 
01018         if (AddOp) {
01019           Value *OtherAddOp = nullptr;
01020           if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
01021             OtherAddOp = AddOp->getOperand(1);
01022           } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
01023             OtherAddOp = AddOp->getOperand(0);
01024           }
01025 
01026           if (OtherAddOp) {
01027             // So at this point we know we have (Y -> OtherAddOp):
01028             //        select C, (add X, Y), (sub X, Z)
01029             Value *NegVal;  // Compute -Z
01030             if (SI.getType()->isFPOrFPVectorTy()) {
01031               NegVal = Builder->CreateFNeg(SubOp->getOperand(1));
01032               if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) {
01033                 FastMathFlags Flags = AddOp->getFastMathFlags();
01034                 Flags &= SubOp->getFastMathFlags();
01035                 NegInst->setFastMathFlags(Flags);
01036               }
01037             } else {
01038               NegVal = Builder->CreateNeg(SubOp->getOperand(1));
01039             }
01040 
01041             Value *NewTrueOp = OtherAddOp;
01042             Value *NewFalseOp = NegVal;
01043             if (AddOp != TI)
01044               std::swap(NewTrueOp, NewFalseOp);
01045             Value *NewSel =
01046               Builder->CreateSelect(CondVal, NewTrueOp,
01047                                     NewFalseOp, SI.getName() + ".p");
01048 
01049             if (SI.getType()->isFPOrFPVectorTy()) {
01050               Instruction *RI =
01051                 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel);
01052 
01053               FastMathFlags Flags = AddOp->getFastMathFlags();
01054               Flags &= SubOp->getFastMathFlags();
01055               RI->setFastMathFlags(Flags);
01056               return RI;
01057             } else
01058               return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
01059           }
01060         }
01061       }
01062 
01063   // See if we can fold the select into one of our operands.
01064   if (SI.getType()->isIntOrIntVectorTy() || SI.getType()->isFPOrFPVectorTy()) {
01065     if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
01066       return FoldI;
01067 
01068     Value *LHS, *RHS, *LHS2, *RHS2;
01069     Instruction::CastOps CastOp;
01070     SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp);
01071     auto SPF = SPR.Flavor;
01072 
01073     if (SelectPatternResult::isMinOrMax(SPF)) {
01074       // Canonicalize so that type casts are outside select patterns.
01075       if (LHS->getType()->getPrimitiveSizeInBits() !=
01076           SI.getType()->getPrimitiveSizeInBits()) {
01077         CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered);
01078 
01079         Value *Cmp;
01080         if (CmpInst::isIntPredicate(Pred)) {
01081           Cmp = Builder->CreateICmp(Pred, LHS, RHS);
01082         } else {
01083           IRBuilder<>::FastMathFlagGuard FMFG(*Builder);
01084           auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags();
01085           Builder->setFastMathFlags(FMF);
01086           Cmp = Builder->CreateFCmp(Pred, LHS, RHS);
01087         }
01088 
01089         Value *NewSI = Builder->CreateCast(CastOp,
01090                                            Builder->CreateSelect(Cmp, LHS, RHS),
01091                                            SI.getType());
01092         return ReplaceInstUsesWith(SI, NewSI);
01093       }
01094     }
01095 
01096     if (SPF) {
01097       // MAX(MAX(a, b), a) -> MAX(a, b)
01098       // MIN(MIN(a, b), a) -> MIN(a, b)
01099       // MAX(MIN(a, b), a) -> a
01100       // MIN(MAX(a, b), a) -> a
01101       // ABS(ABS(a)) -> ABS(a)
01102       // NABS(NABS(a)) -> NABS(a)
01103       if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor)
01104         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
01105                                           SI, SPF, RHS))
01106           return R;
01107       if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor)
01108         if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
01109                                           SI, SPF, LHS))
01110           return R;
01111     }
01112 
01113     // MAX(~a, ~b) -> ~MIN(a, b)
01114     if (SPF == SPF_SMAX || SPF == SPF_UMAX) {
01115       if (IsFreeToInvert(LHS, LHS->hasNUses(2)) &&
01116           IsFreeToInvert(RHS, RHS->hasNUses(2))) {
01117 
01118         // This transform adds a xor operation and that extra cost needs to be
01119         // justified.  We look for simplifications that will result from
01120         // applying this rule:
01121 
01122         bool Profitable =
01123             (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) ||
01124             (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) ||
01125             (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value())));
01126 
01127         if (Profitable) {
01128           Value *NewLHS = Builder->CreateNot(LHS);
01129           Value *NewRHS = Builder->CreateNot(RHS);
01130           Value *NewCmp = SPF == SPF_SMAX
01131                               ? Builder->CreateICmpSLT(NewLHS, NewRHS)
01132                               : Builder->CreateICmpULT(NewLHS, NewRHS);
01133           Value *NewSI =
01134               Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS));
01135           return ReplaceInstUsesWith(SI, NewSI);
01136         }
01137       }
01138     }
01139 
01140     // TODO.
01141     // ABS(-X) -> ABS(X)
01142   }
01143 
01144   // See if we can fold the select into a phi node if the condition is a select.
01145   if (isa<PHINode>(SI.getCondition()))
01146     // The true/false values have to be live in the PHI predecessor's blocks.
01147     if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
01148         CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
01149       if (Instruction *NV = FoldOpIntoPhi(SI))
01150         return NV;
01151 
01152   if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) {
01153     if (TrueSI->getCondition()->getType() == CondVal->getType()) {
01154       // select(C, select(C, a, b), c) -> select(C, a, c)
01155       if (TrueSI->getCondition() == CondVal) {
01156         if (SI.getTrueValue() == TrueSI->getTrueValue())
01157           return nullptr;
01158         SI.setOperand(1, TrueSI->getTrueValue());
01159         return &SI;
01160       }
01161       // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b)
01162       // We choose this as normal form to enable folding on the And and shortening
01163       // paths for the values (this helps GetUnderlyingObjects() for example).
01164       if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) {
01165         Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition());
01166         SI.setOperand(0, And);
01167         SI.setOperand(1, TrueSI->getTrueValue());
01168         return &SI;
01169       }
01170     }
01171   }
01172   if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) {
01173     if (FalseSI->getCondition()->getType() == CondVal->getType()) {
01174       // select(C, a, select(C, b, c)) -> select(C, a, c)
01175       if (FalseSI->getCondition() == CondVal) {
01176         if (SI.getFalseValue() == FalseSI->getFalseValue())
01177           return nullptr;
01178         SI.setOperand(2, FalseSI->getFalseValue());
01179         return &SI;
01180       }
01181       // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b)
01182       if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) {
01183         Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition());
01184         SI.setOperand(0, Or);
01185         SI.setOperand(2, FalseSI->getFalseValue());
01186         return &SI;
01187       }
01188     }
01189   }
01190 
01191   if (BinaryOperator::isNot(CondVal)) {
01192     SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
01193     SI.setOperand(1, FalseVal);
01194     SI.setOperand(2, TrueVal);
01195     return &SI;
01196   }
01197 
01198   if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) {
01199     unsigned VWidth = VecTy->getNumElements();
01200     APInt UndefElts(VWidth, 0);
01201     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
01202     if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) {
01203       if (V != &SI)
01204         return ReplaceInstUsesWith(SI, V);
01205       return &SI;
01206     }
01207 
01208     if (isa<ConstantAggregateZero>(CondVal)) {
01209       return ReplaceInstUsesWith(SI, FalseVal);
01210     }
01211   }
01212 
01213   return nullptr;
01214 }