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