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