LLVM API Documentation

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