InstCombineSelect.cpp revision 40bf5e7a6811bf31b6853d2c71c08feed871419b
13c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//===- InstCombineSelect.cpp ----------------------------------------------===//
23c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//
33c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//                     The LLVM Compiler Infrastructure
43c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//
53c3b7f90a863af43fa63043d396553ecf205351cJohn McCall// This file is distributed under the University of Illinois Open Source
63c3b7f90a863af43fa63043d396553ecf205351cJohn McCall// License. See LICENSE.TXT for details.
73c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//
83c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//===----------------------------------------------------------------------===//
93c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//
103c3b7f90a863af43fa63043d396553ecf205351cJohn McCall// This file implements the visitSelect function.
113c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//
123c3b7f90a863af43fa63043d396553ecf205351cJohn McCall//===----------------------------------------------------------------------===//
133c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
143c3b7f90a863af43fa63043d396553ecf205351cJohn McCall#include "InstCombine.h"
153c3b7f90a863af43fa63043d396553ecf205351cJohn McCall#include "llvm/Support/PatternMatch.h"
163c3b7f90a863af43fa63043d396553ecf205351cJohn McCall#include "llvm/Analysis/InstructionSimplify.h"
173c3b7f90a863af43fa63043d396553ecf205351cJohn McCallusing namespace llvm;
183c3b7f90a863af43fa63043d396553ecf205351cJohn McCallusing namespace PatternMatch;
193c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
203c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
213c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// returning the kind and providing the out parameter results if we
223c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// successfully match.
233c3b7f90a863af43fa63043d396553ecf205351cJohn McCallstatic SelectPatternFlavor
243c3b7f90a863af43fa63043d396553ecf205351cJohn McCallMatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
253c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  SelectInst *SI = dyn_cast<SelectInst>(V);
263c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (SI == 0) return SPF_UNKNOWN;
273c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
283c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
293c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (ICI == 0) return SPF_UNKNOWN;
303c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
313c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  LHS = ICI->getOperand(0);
323c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  RHS = ICI->getOperand(1);
333c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
343c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // (icmp X, Y) ? X : Y
353c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (SI->getTrueValue() == ICI->getOperand(0) &&
363c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      SI->getFalseValue() == ICI->getOperand(1)) {
373c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    switch (ICI->getPredicate()) {
383c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    default: return SPF_UNKNOWN; // Equality.
393c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    case ICmpInst::ICMP_UGT:
403c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    case ICmpInst::ICMP_UGE: return SPF_UMAX;
413c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    case ICmpInst::ICMP_SGT:
423c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    case ICmpInst::ICMP_SGE: return SPF_SMAX;
433c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    case ICmpInst::ICMP_ULT:
44aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer    case ICmpInst::ICMP_ULE: return SPF_UMIN;
45aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer    case ICmpInst::ICMP_SLT:
46aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer    case ICmpInst::ICMP_SLE: return SPF_SMIN;
473c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    }
483c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
49aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer
50aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer  // (icmp X, Y) ? Y : X
51aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer  if (SI->getTrueValue() == ICI->getOperand(1) &&
52aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer      SI->getFalseValue() == ICI->getOperand(0)) {
53aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer    switch (ICI->getPredicate()) {
54aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer      default: return SPF_UNKNOWN; // Equality.
55aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer      case ICmpInst::ICMP_UGT:
56aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer      case ICmpInst::ICMP_UGE: return SPF_UMIN;
57aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer      case ICmpInst::ICMP_SGT:
58aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer      case ICmpInst::ICMP_SGE: return SPF_SMIN;
59aa9807a85959ffbdc5d9f649d7b24b9b2056d2cdBenjamin Kramer      case ICmpInst::ICMP_ULT:
603c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      case ICmpInst::ICMP_ULE: return SPF_UMAX;
613c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      case ICmpInst::ICMP_SLT:
623c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      case ICmpInst::ICMP_SLE: return SPF_SMAX;
633c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    }
643c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
653c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
663c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // TODO: (X > 4) ? X : 5   -->  (X >= 5) ? X : 5  -->  MAX(X, 5)
673c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
683c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  return SPF_UNKNOWN;
693c3b7f90a863af43fa63043d396553ecf205351cJohn McCall}
703c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
713c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
723c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// GetSelectFoldableOperands - We want to turn code that looks like this:
733c3b7f90a863af43fa63043d396553ecf205351cJohn McCall///   %C = or %A, %B
743c3b7f90a863af43fa63043d396553ecf205351cJohn McCall///   %D = select %cond, %C, %A
753c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// into:
763c3b7f90a863af43fa63043d396553ecf205351cJohn McCall///   %C = select %cond, %B, 0
773c3b7f90a863af43fa63043d396553ecf205351cJohn McCall///   %D = or %A, %C
783c3b7f90a863af43fa63043d396553ecf205351cJohn McCall///
793c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// Assuming that the specified instruction is an operand to the select, return
803c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// a bitmask indicating which operands of this instruction are foldable if they
813c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// equal the other incoming value of the select.
823c3b7f90a863af43fa63043d396553ecf205351cJohn McCall///
833c3b7f90a863af43fa63043d396553ecf205351cJohn McCallstatic unsigned GetSelectFoldableOperands(Instruction *I) {
843c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  switch (I->getOpcode()) {
853c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Add:
863c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Mul:
873c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::And:
883c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Or:
893c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Xor:
903c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return 3;              // Can fold through either operand.
913c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Sub:   // Can only fold on the amount subtracted.
923c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Shl:   // Can only fold on the shift amount.
933c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::LShr:
943c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::AShr:
953c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return 1;
963c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  default:
973c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return 0;              // Cannot fold
983c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
993c3b7f90a863af43fa63043d396553ecf205351cJohn McCall}
1003c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1013c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// GetSelectFoldableConstant - For the same transformation as the previous
1023c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// function, return the identity constant that goes into the select.
1033c3b7f90a863af43fa63043d396553ecf205351cJohn McCallstatic Constant *GetSelectFoldableConstant(Instruction *I) {
1043c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  switch (I->getOpcode()) {
1053c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  default: llvm_unreachable("This cannot happen!");
1063c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Add:
1073c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Sub:
1083c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Or:
1093c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Xor:
1103c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Shl:
1113c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::LShr:
1123c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::AShr:
1133c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return Constant::getNullValue(I->getType());
1143c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::And:
1153c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return Constant::getAllOnesValue(I->getType());
1163c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  case Instruction::Mul:
1173c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return ConstantInt::get(I->getType(), 1);
1183c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
1193c3b7f90a863af43fa63043d396553ecf205351cJohn McCall}
1203c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1213c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
1223c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// have the same opcode and only one use each.  Try to simplify this.
1233c3b7f90a863af43fa63043d396553ecf205351cJohn McCallInstruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
1243c3b7f90a863af43fa63043d396553ecf205351cJohn McCall                                          Instruction *FI) {
1253c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (TI->getNumOperands() == 1) {
1263c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    // If this is a non-volatile load or a cast from the same type,
1273c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    // merge.
1283c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    if (TI->isCast()) {
1293c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
1303c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        return 0;
1313c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    } else {
1323c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      return 0;  // unknown unary op.
1333c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    }
1343c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1353c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    // Fold this by inserting a select from the input values.
1363c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
1373c3b7f90a863af43fa63043d396553ecf205351cJohn McCall                                          FI->getOperand(0), SI.getName()+".v");
1383c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    InsertNewInstBefore(NewSI, SI);
1393c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
1403c3b7f90a863af43fa63043d396553ecf205351cJohn McCall                            TI->getType());
1413c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
1423c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1433c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // Only handle binary operators here.
1443c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (!isa<BinaryOperator>(TI))
1453c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return 0;
1463c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1473c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // Figure out if the operations have any operands in common.
1483c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  Value *MatchOp, *OtherOpT, *OtherOpF;
1493c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  bool MatchIsOpZero;
1503c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (TI->getOperand(0) == FI->getOperand(0)) {
1513c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchOp  = TI->getOperand(0);
1523c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpT = TI->getOperand(1);
1533c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpF = FI->getOperand(1);
1543c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchIsOpZero = true;
1553c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  } else if (TI->getOperand(1) == FI->getOperand(1)) {
1563c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchOp  = TI->getOperand(1);
1573c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpT = TI->getOperand(0);
1583c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpF = FI->getOperand(0);
1593c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchIsOpZero = false;
1603c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  } else if (!TI->isCommutative()) {
1613c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return 0;
1623c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  } else if (TI->getOperand(0) == FI->getOperand(1)) {
1633c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchOp  = TI->getOperand(0);
1643c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpT = TI->getOperand(1);
1653c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpF = FI->getOperand(0);
1663c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchIsOpZero = true;
1673c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  } else if (TI->getOperand(1) == FI->getOperand(0)) {
1683c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchOp  = TI->getOperand(1);
1693c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpT = TI->getOperand(0);
1703c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    OtherOpF = FI->getOperand(1);
1713c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    MatchIsOpZero = true;
1723c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  } else {
1733c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return 0;
1743c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
1753c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1763c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // If we reach here, they do have operations in common.
1773c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
1783c3b7f90a863af43fa63043d396553ecf205351cJohn McCall                                         OtherOpF, SI.getName()+".v");
1793c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  InsertNewInstBefore(NewSI, SI);
1803c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1813c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
1823c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    if (MatchIsOpZero)
1833c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
1843c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    else
1853c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
1863c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
1873c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  llvm_unreachable("Shouldn't get here");
1883c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  return 0;
1893c3b7f90a863af43fa63043d396553ecf205351cJohn McCall}
1903c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
1913c3b7f90a863af43fa63043d396553ecf205351cJohn McCallstatic bool isSelect01(Constant *C1, Constant *C2) {
1923c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
1933c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (!C1I)
1943c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return false;
1953c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
1963c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (!C2I)
1973c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    return false;
1983c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
1993c3b7f90a863af43fa63043d396553ecf205351cJohn McCall}
2003c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
2013c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// FoldSelectIntoOp - Try fold the select into one of the operands to
2023c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// facilitate further optimization.
2033c3b7f90a863af43fa63043d396553ecf205351cJohn McCallInstruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
2043c3b7f90a863af43fa63043d396553ecf205351cJohn McCall                                            Value *FalseVal) {
2053c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // See the comment above GetSelectFoldableOperands for a description of the
2063c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // transformation we are doing here.
2073c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
2083c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
2093c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        !isa<Constant>(FalseVal)) {
2103c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
2113c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        unsigned OpToFold = 0;
2123c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
2133c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          OpToFold = 1;
2143c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        } else  if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
2153c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          OpToFold = 2;
2163c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        }
2173c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
2183c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if (OpToFold) {
2193c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Constant *C = GetSelectFoldableConstant(TVI);
2203c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Value *OOp = TVI->getOperand(2-OpToFold);
2213c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          // Avoid creating select between 2 constants unless it's selecting
2223c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          // between 0 and 1.
2233c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
2243c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
2253c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            InsertNewInstBefore(NewSel, SI);
2263c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            NewSel->takeName(TVI);
2273c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
2283c3b7f90a863af43fa63043d396553ecf205351cJohn McCall              return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
2293c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            llvm_unreachable("Unknown instruction!!");
2303c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          }
2313c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        }
2323c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      }
2333c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    }
2343c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
2353c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
2363c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
2373c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
2383c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        !isa<Constant>(TrueVal)) {
2393c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
2403c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        unsigned OpToFold = 0;
2413c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
2423c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          OpToFold = 1;
2433c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        } else  if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
2443c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          OpToFold = 2;
2453c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        }
2463c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
2473c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if (OpToFold) {
2483c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Constant *C = GetSelectFoldableConstant(FVI);
2493c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Value *OOp = FVI->getOperand(2-OpToFold);
2503c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          // Avoid creating select between 2 constants unless it's selecting
2513c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          // between 0 and 1.
2523c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
2533c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
2543c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            InsertNewInstBefore(NewSel, SI);
2553c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            NewSel->takeName(FVI);
2563c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
2573c3b7f90a863af43fa63043d396553ecf205351cJohn McCall              return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
2583c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            llvm_unreachable("Unknown instruction!!");
2593c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          }
2603c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        }
2613c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      }
2623c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    }
2633c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  }
2643c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
2653c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  return 0;
2663c3b7f90a863af43fa63043d396553ecf205351cJohn McCall}
2673c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
2683c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// visitSelectInstWithICmp - Visit a SelectInst that has an
2693c3b7f90a863af43fa63043d396553ecf205351cJohn McCall/// ICmpInst as its first operand.
2703c3b7f90a863af43fa63043d396553ecf205351cJohn McCall///
2713c3b7f90a863af43fa63043d396553ecf205351cJohn McCallInstruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
2723c3b7f90a863af43fa63043d396553ecf205351cJohn McCall                                                   ICmpInst *ICI) {
2733c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  bool Changed = false;
2743c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  ICmpInst::Predicate Pred = ICI->getPredicate();
2753c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  Value *CmpLHS = ICI->getOperand(0);
2763c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  Value *CmpRHS = ICI->getOperand(1);
2773c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  Value *TrueVal = SI.getTrueValue();
2783c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  Value *FalseVal = SI.getFalseValue();
2793c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
2803c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // Check cases where the comparison is with a constant that
2813c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // can be adjusted to fit the min/max idiom. We may edit ICI in
2823c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // place here, so make sure the select is the only user.
2833c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (ICI->hasOneUse())
2843c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
2853c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      switch (Pred) {
2863c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      default: break;
2873c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      case ICmpInst::ICMP_ULT:
2883c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      case ICmpInst::ICMP_SLT: {
2893c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        // X < MIN ? T : F  -->  F
2903c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
2913c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          return ReplaceInstUsesWith(SI, FalseVal);
2923c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        // X < C ? X : C-1  -->  X > C-1 ? C-1 : X
2933c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        Constant *AdjustedRHS =
2943c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          ConstantInt::get(CI->getContext(), CI->getValue()-1);
2953c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
2963c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
2973c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Pred = ICmpInst::getSwappedPredicate(Pred);
2983c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          CmpRHS = AdjustedRHS;
2993c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          std::swap(FalseVal, TrueVal);
3003c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          ICI->setPredicate(Pred);
3013c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          ICI->setOperand(1, CmpRHS);
3023c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          SI.setOperand(1, TrueVal);
3033c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          SI.setOperand(2, FalseVal);
3043c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Changed = true;
3053c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        }
3063c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        break;
3073c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      }
3083c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      case ICmpInst::ICMP_UGT:
3093c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      case ICmpInst::ICMP_SGT: {
3103c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        // X > MAX ? T : F  -->  F
3113c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
3123c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          return ReplaceInstUsesWith(SI, FalseVal);
3133c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        // X > C ? X : C+1  -->  X < C+1 ? C+1 : X
3143c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        Constant *AdjustedRHS =
3153c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          ConstantInt::get(CI->getContext(), CI->getValue()+1);
3163c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
3173c3b7f90a863af43fa63043d396553ecf205351cJohn McCall            (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
3183c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Pred = ICmpInst::getSwappedPredicate(Pred);
3193c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          CmpRHS = AdjustedRHS;
3203c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          std::swap(FalseVal, TrueVal);
3213c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          ICI->setPredicate(Pred);
3223c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          ICI->setOperand(1, CmpRHS);
3233c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          SI.setOperand(1, TrueVal);
3243c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          SI.setOperand(2, FalseVal);
3253c3b7f90a863af43fa63043d396553ecf205351cJohn McCall          Changed = true;
3263c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        }
3273c3b7f90a863af43fa63043d396553ecf205351cJohn McCall        break;
3283c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      }
3293c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      }
3303c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    }
3313c3b7f90a863af43fa63043d396553ecf205351cJohn McCall
3323c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1
3333c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // and       (X <s  0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1
3343c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  // FIXME: Type and constness constraints could be lifted, but we have to
3353c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  //        watch code size carefully. We should consider xor instead of
3363c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  //        sub/add when we decide to do that.
3373c3b7f90a863af43fa63043d396553ecf205351cJohn McCall  if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) {
3383c3b7f90a863af43fa63043d396553ecf205351cJohn McCall    if (TrueVal->getType() == Ty) {
3393c3b7f90a863af43fa63043d396553ecf205351cJohn McCall      if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) {
340        ConstantInt *C1 = NULL, *C2 = NULL;
341        if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) {
342          C1 = dyn_cast<ConstantInt>(TrueVal);
343          C2 = dyn_cast<ConstantInt>(FalseVal);
344        } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) {
345          C1 = dyn_cast<ConstantInt>(FalseVal);
346          C2 = dyn_cast<ConstantInt>(TrueVal);
347        }
348        if (C1 && C2) {
349          // This shift results in either -1 or 0.
350          Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1);
351
352          // Check if we can express the operation with a single or.
353          if (C2->isAllOnesValue())
354            return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1));
355
356          Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue());
357          return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1));
358        }
359      }
360    }
361  }
362
363  if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
364    // Transform (X == Y) ? X : Y  -> Y
365    if (Pred == ICmpInst::ICMP_EQ)
366      return ReplaceInstUsesWith(SI, FalseVal);
367    // Transform (X != Y) ? X : Y  -> X
368    if (Pred == ICmpInst::ICMP_NE)
369      return ReplaceInstUsesWith(SI, TrueVal);
370    /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
371
372  } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
373    // Transform (X == Y) ? Y : X  -> X
374    if (Pred == ICmpInst::ICMP_EQ)
375      return ReplaceInstUsesWith(SI, FalseVal);
376    // Transform (X != Y) ? Y : X  -> Y
377    if (Pred == ICmpInst::ICMP_NE)
378      return ReplaceInstUsesWith(SI, TrueVal);
379    /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
380  }
381  return Changed ? &SI : 0;
382}
383
384
385/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
386/// PHI node (but the two may be in different blocks).  See if the true/false
387/// values (V) are live in all of the predecessor blocks of the PHI.  For
388/// example, cases like this cannot be mapped:
389///
390///   X = phi [ C1, BB1], [C2, BB2]
391///   Y = add
392///   Z = select X, Y, 0
393///
394/// because Y is not live in BB1/BB2.
395///
396static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
397                                                   const SelectInst &SI) {
398  // If the value is a non-instruction value like a constant or argument, it
399  // can always be mapped.
400  const Instruction *I = dyn_cast<Instruction>(V);
401  if (I == 0) return true;
402
403  // If V is a PHI node defined in the same block as the condition PHI, we can
404  // map the arguments.
405  const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
406
407  if (const PHINode *VP = dyn_cast<PHINode>(I))
408    if (VP->getParent() == CondPHI->getParent())
409      return true;
410
411  // Otherwise, if the PHI and select are defined in the same block and if V is
412  // defined in a different block, then we can transform it.
413  if (SI.getParent() == CondPHI->getParent() &&
414      I->getParent() != CondPHI->getParent())
415    return true;
416
417  // Otherwise we have a 'hard' case and we can't tell without doing more
418  // detailed dominator based analysis, punt.
419  return false;
420}
421
422/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
423///   SPF2(SPF1(A, B), C)
424Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
425                                        SelectPatternFlavor SPF1,
426                                        Value *A, Value *B,
427                                        Instruction &Outer,
428                                        SelectPatternFlavor SPF2, Value *C) {
429  if (C == A || C == B) {
430    // MAX(MAX(A, B), B) -> MAX(A, B)
431    // MIN(MIN(a, b), a) -> MIN(a, b)
432    if (SPF1 == SPF2)
433      return ReplaceInstUsesWith(Outer, Inner);
434
435    // MAX(MIN(a, b), a) -> a
436    // MIN(MAX(a, b), a) -> a
437    if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
438        (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
439        (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
440        (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
441      return ReplaceInstUsesWith(Outer, C);
442  }
443
444  // TODO: MIN(MIN(A, 23), 97)
445  return 0;
446}
447
448
449
450
451Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
452  Value *CondVal = SI.getCondition();
453  Value *TrueVal = SI.getTrueValue();
454  Value *FalseVal = SI.getFalseValue();
455
456  if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD))
457    return ReplaceInstUsesWith(SI, V);
458
459  if (SI.getType()->isIntegerTy(1)) {
460    if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
461      if (C->getZExtValue()) {
462        // Change: A = select B, true, C --> A = or B, C
463        return BinaryOperator::CreateOr(CondVal, FalseVal);
464      }
465      // Change: A = select B, false, C --> A = and !B, C
466      Value *NotCond =
467        InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
468                                           "not."+CondVal->getName()), SI);
469      return BinaryOperator::CreateAnd(NotCond, FalseVal);
470    } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
471      if (C->getZExtValue() == false) {
472        // Change: A = select B, C, false --> A = and B, C
473        return BinaryOperator::CreateAnd(CondVal, TrueVal);
474      }
475      // Change: A = select B, C, true --> A = or !B, C
476      Value *NotCond =
477        InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
478                                           "not."+CondVal->getName()), SI);
479      return BinaryOperator::CreateOr(NotCond, TrueVal);
480    }
481
482    // select a, b, a  -> a&b
483    // select a, a, b  -> a|b
484    if (CondVal == TrueVal)
485      return BinaryOperator::CreateOr(CondVal, FalseVal);
486    else if (CondVal == FalseVal)
487      return BinaryOperator::CreateAnd(CondVal, TrueVal);
488  }
489
490  // Selecting between two integer constants?
491  if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
492    if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
493      // select C, 1, 0 -> zext C to int
494      if (FalseValC->isZero() && TrueValC->getValue() == 1)
495        return new ZExtInst(CondVal, SI.getType());
496
497      // select C, -1, 0 -> sext C to int
498      if (FalseValC->isZero() && TrueValC->isAllOnesValue())
499        return new SExtInst(CondVal, SI.getType());
500
501      // select C, 0, 1 -> zext !C to int
502      if (TrueValC->isZero() && FalseValC->getValue() == 1) {
503        Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
504        return new ZExtInst(NotCond, SI.getType());
505      }
506
507      // select C, 0, -1 -> sext !C to int
508      if (TrueValC->isZero() && FalseValC->isAllOnesValue()) {
509        Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName());
510        return new SExtInst(NotCond, SI.getType());
511      }
512
513      if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
514        // If one of the constants is zero (we know they can't both be) and we
515        // have an icmp instruction with zero, and we have an 'and' with the
516        // non-constant value, eliminate this whole mess.  This corresponds to
517        // cases like this: ((X & 27) ? 27 : 0)
518        if (TrueValC->isZero() || FalseValC->isZero())
519          if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
520              cast<Constant>(IC->getOperand(1))->isNullValue())
521            if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
522              if (ICA->getOpcode() == Instruction::And &&
523                  isa<ConstantInt>(ICA->getOperand(1)) &&
524                  (ICA->getOperand(1) == TrueValC ||
525                   ICA->getOperand(1) == FalseValC) &&
526               cast<ConstantInt>(ICA->getOperand(1))->getValue().isPowerOf2()) {
527                // Okay, now we know that everything is set up, we just don't
528                // know whether we have a icmp_ne or icmp_eq and whether the
529                // true or false val is the zero.
530                bool ShouldNotVal = !TrueValC->isZero();
531                ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
532                Value *V = ICA;
533                if (ShouldNotVal)
534                  V = Builder->CreateXor(V, ICA->getOperand(1));
535                return ReplaceInstUsesWith(SI, V);
536              }
537      }
538    }
539
540  // See if we are selecting two values based on a comparison of the two values.
541  if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
542    if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
543      // Transform (X == Y) ? X : Y  -> Y
544      if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
545        // This is not safe in general for floating point:
546        // consider X== -0, Y== +0.
547        // It becomes safe if either operand is a nonzero constant.
548        ConstantFP *CFPt, *CFPf;
549        if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
550              !CFPt->getValueAPF().isZero()) ||
551            ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
552             !CFPf->getValueAPF().isZero()))
553        return ReplaceInstUsesWith(SI, FalseVal);
554      }
555      // Transform (X une Y) ? X : Y  -> X
556      if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
557        // This is not safe in general for floating point:
558        // consider X== -0, Y== +0.
559        // It becomes safe if either operand is a nonzero constant.
560        ConstantFP *CFPt, *CFPf;
561        if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
562              !CFPt->getValueAPF().isZero()) ||
563            ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
564             !CFPf->getValueAPF().isZero()))
565        return ReplaceInstUsesWith(SI, TrueVal);
566      }
567      // NOTE: if we wanted to, this is where to detect MIN/MAX
568
569    } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
570      // Transform (X == Y) ? Y : X  -> X
571      if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
572        // This is not safe in general for floating point:
573        // consider X== -0, Y== +0.
574        // It becomes safe if either operand is a nonzero constant.
575        ConstantFP *CFPt, *CFPf;
576        if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
577              !CFPt->getValueAPF().isZero()) ||
578            ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
579             !CFPf->getValueAPF().isZero()))
580          return ReplaceInstUsesWith(SI, FalseVal);
581      }
582      // Transform (X une Y) ? Y : X  -> Y
583      if (FCI->getPredicate() == FCmpInst::FCMP_UNE) {
584        // This is not safe in general for floating point:
585        // consider X== -0, Y== +0.
586        // It becomes safe if either operand is a nonzero constant.
587        ConstantFP *CFPt, *CFPf;
588        if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
589              !CFPt->getValueAPF().isZero()) ||
590            ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
591             !CFPf->getValueAPF().isZero()))
592          return ReplaceInstUsesWith(SI, TrueVal);
593      }
594      // NOTE: if we wanted to, this is where to detect MIN/MAX
595    }
596    // NOTE: if we wanted to, this is where to detect ABS
597  }
598
599  // See if we are selecting two values based on a comparison of the two values.
600  if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
601    if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
602      return Result;
603
604  if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
605    if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
606      if (TI->hasOneUse() && FI->hasOneUse()) {
607        Instruction *AddOp = 0, *SubOp = 0;
608
609        // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
610        if (TI->getOpcode() == FI->getOpcode())
611          if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
612            return IV;
613
614        // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))).  This is
615        // even legal for FP.
616        if ((TI->getOpcode() == Instruction::Sub &&
617             FI->getOpcode() == Instruction::Add) ||
618            (TI->getOpcode() == Instruction::FSub &&
619             FI->getOpcode() == Instruction::FAdd)) {
620          AddOp = FI; SubOp = TI;
621        } else if ((FI->getOpcode() == Instruction::Sub &&
622                    TI->getOpcode() == Instruction::Add) ||
623                   (FI->getOpcode() == Instruction::FSub &&
624                    TI->getOpcode() == Instruction::FAdd)) {
625          AddOp = TI; SubOp = FI;
626        }
627
628        if (AddOp) {
629          Value *OtherAddOp = 0;
630          if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
631            OtherAddOp = AddOp->getOperand(1);
632          } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
633            OtherAddOp = AddOp->getOperand(0);
634          }
635
636          if (OtherAddOp) {
637            // So at this point we know we have (Y -> OtherAddOp):
638            //        select C, (add X, Y), (sub X, Z)
639            Value *NegVal;  // Compute -Z
640            if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
641              NegVal = ConstantExpr::getNeg(C);
642            } else {
643              NegVal = InsertNewInstBefore(
644                    BinaryOperator::CreateNeg(SubOp->getOperand(1),
645                                              "tmp"), SI);
646            }
647
648            Value *NewTrueOp = OtherAddOp;
649            Value *NewFalseOp = NegVal;
650            if (AddOp != TI)
651              std::swap(NewTrueOp, NewFalseOp);
652            Instruction *NewSel =
653              SelectInst::Create(CondVal, NewTrueOp,
654                                 NewFalseOp, SI.getName() + ".p");
655
656            NewSel = InsertNewInstBefore(NewSel, SI);
657            return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
658          }
659        }
660      }
661
662  // See if we can fold the select into one of our operands.
663  if (SI.getType()->isIntegerTy()) {
664    if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
665      return FoldI;
666
667    // MAX(MAX(a, b), a) -> MAX(a, b)
668    // MIN(MIN(a, b), a) -> MIN(a, b)
669    // MAX(MIN(a, b), a) -> a
670    // MIN(MAX(a, b), a) -> a
671    Value *LHS, *RHS, *LHS2, *RHS2;
672    if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
673      if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
674        if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
675                                          SI, SPF, RHS))
676          return R;
677      if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
678        if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
679                                          SI, SPF, LHS))
680          return R;
681    }
682
683    // TODO.
684    // ABS(-X) -> ABS(X)
685    // ABS(ABS(X)) -> ABS(X)
686  }
687
688  // See if we can fold the select into a phi node if the condition is a select.
689  if (isa<PHINode>(SI.getCondition()))
690    // The true/false values have to be live in the PHI predecessor's blocks.
691    if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
692        CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
693      if (Instruction *NV = FoldOpIntoPhi(SI))
694        return NV;
695
696  if (BinaryOperator::isNot(CondVal)) {
697    SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
698    SI.setOperand(1, FalseVal);
699    SI.setOperand(2, TrueVal);
700    return &SI;
701  }
702
703  return 0;
704}
705