InstCombineSelect.cpp revision 976e7e1cc8282a965cf20ab54a7dce9165d87ea9
1//===- InstCombineSelect.cpp ----------------------------------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the visitSelect function. 11// 12//===----------------------------------------------------------------------===// 13 14#include "InstCombine.h" 15#include "llvm/Support/PatternMatch.h" 16#include "llvm/Analysis/InstructionSimplify.h" 17using namespace llvm; 18using namespace PatternMatch; 19 20/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms, 21/// returning the kind and providing the out parameter results if we 22/// successfully match. 23static SelectPatternFlavor 24MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) { 25 SelectInst *SI = dyn_cast<SelectInst>(V); 26 if (SI == 0) return SPF_UNKNOWN; 27 28 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition()); 29 if (ICI == 0) return SPF_UNKNOWN; 30 31 LHS = ICI->getOperand(0); 32 RHS = ICI->getOperand(1); 33 34 // (icmp X, Y) ? X : Y 35 if (SI->getTrueValue() == ICI->getOperand(0) && 36 SI->getFalseValue() == ICI->getOperand(1)) { 37 switch (ICI->getPredicate()) { 38 default: return SPF_UNKNOWN; // Equality. 39 case ICmpInst::ICMP_UGT: 40 case ICmpInst::ICMP_UGE: return SPF_UMAX; 41 case ICmpInst::ICMP_SGT: 42 case ICmpInst::ICMP_SGE: return SPF_SMAX; 43 case ICmpInst::ICMP_ULT: 44 case ICmpInst::ICMP_ULE: return SPF_UMIN; 45 case ICmpInst::ICMP_SLT: 46 case ICmpInst::ICMP_SLE: return SPF_SMIN; 47 } 48 } 49 50 // (icmp X, Y) ? Y : X 51 if (SI->getTrueValue() == ICI->getOperand(1) && 52 SI->getFalseValue() == ICI->getOperand(0)) { 53 switch (ICI->getPredicate()) { 54 default: return SPF_UNKNOWN; // Equality. 55 case ICmpInst::ICMP_UGT: 56 case ICmpInst::ICMP_UGE: return SPF_UMIN; 57 case ICmpInst::ICMP_SGT: 58 case ICmpInst::ICMP_SGE: return SPF_SMIN; 59 case ICmpInst::ICMP_ULT: 60 case ICmpInst::ICMP_ULE: return SPF_UMAX; 61 case ICmpInst::ICMP_SLT: 62 case ICmpInst::ICMP_SLE: return SPF_SMAX; 63 } 64 } 65 66 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5) 67 68 return SPF_UNKNOWN; 69} 70 71 72/// GetSelectFoldableOperands - We want to turn code that looks like this: 73/// %C = or %A, %B 74/// %D = select %cond, %C, %A 75/// into: 76/// %C = select %cond, %B, 0 77/// %D = or %A, %C 78/// 79/// Assuming that the specified instruction is an operand to the select, return 80/// a bitmask indicating which operands of this instruction are foldable if they 81/// equal the other incoming value of the select. 82/// 83static unsigned GetSelectFoldableOperands(Instruction *I) { 84 switch (I->getOpcode()) { 85 case Instruction::Add: 86 case Instruction::Mul: 87 case Instruction::And: 88 case Instruction::Or: 89 case Instruction::Xor: 90 return 3; // Can fold through either operand. 91 case Instruction::Sub: // Can only fold on the amount subtracted. 92 case Instruction::Shl: // Can only fold on the shift amount. 93 case Instruction::LShr: 94 case Instruction::AShr: 95 return 1; 96 default: 97 return 0; // Cannot fold 98 } 99} 100 101/// GetSelectFoldableConstant - For the same transformation as the previous 102/// function, return the identity constant that goes into the select. 103static Constant *GetSelectFoldableConstant(Instruction *I) { 104 switch (I->getOpcode()) { 105 default: llvm_unreachable("This cannot happen!"); 106 case Instruction::Add: 107 case Instruction::Sub: 108 case Instruction::Or: 109 case Instruction::Xor: 110 case Instruction::Shl: 111 case Instruction::LShr: 112 case Instruction::AShr: 113 return Constant::getNullValue(I->getType()); 114 case Instruction::And: 115 return Constant::getAllOnesValue(I->getType()); 116 case Instruction::Mul: 117 return ConstantInt::get(I->getType(), 1); 118 } 119} 120 121/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI 122/// have the same opcode and only one use each. Try to simplify this. 123Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI, 124 Instruction *FI) { 125 if (TI->getNumOperands() == 1) { 126 // If this is a non-volatile load or a cast from the same type, 127 // merge. 128 if (TI->isCast()) { 129 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType()) 130 return 0; 131 } else { 132 return 0; // unknown unary op. 133 } 134 135 // Fold this by inserting a select from the input values. 136 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0), 137 FI->getOperand(0), SI.getName()+".v"); 138 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 139 TI->getType()); 140 } 141 142 // Only handle binary operators here. 143 if (!isa<BinaryOperator>(TI)) 144 return 0; 145 146 // Figure out if the operations have any operands in common. 147 Value *MatchOp, *OtherOpT, *OtherOpF; 148 bool MatchIsOpZero; 149 if (TI->getOperand(0) == FI->getOperand(0)) { 150 MatchOp = TI->getOperand(0); 151 OtherOpT = TI->getOperand(1); 152 OtherOpF = FI->getOperand(1); 153 MatchIsOpZero = true; 154 } else if (TI->getOperand(1) == FI->getOperand(1)) { 155 MatchOp = TI->getOperand(1); 156 OtherOpT = TI->getOperand(0); 157 OtherOpF = FI->getOperand(0); 158 MatchIsOpZero = false; 159 } else if (!TI->isCommutative()) { 160 return 0; 161 } else if (TI->getOperand(0) == FI->getOperand(1)) { 162 MatchOp = TI->getOperand(0); 163 OtherOpT = TI->getOperand(1); 164 OtherOpF = FI->getOperand(0); 165 MatchIsOpZero = true; 166 } else if (TI->getOperand(1) == FI->getOperand(0)) { 167 MatchOp = TI->getOperand(1); 168 OtherOpT = TI->getOperand(0); 169 OtherOpF = FI->getOperand(1); 170 MatchIsOpZero = true; 171 } else { 172 return 0; 173 } 174 175 // If we reach here, they do have operations in common. 176 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, 177 OtherOpF, SI.getName()+".v"); 178 179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) { 180 if (MatchIsOpZero) 181 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI); 182 else 183 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp); 184 } 185 llvm_unreachable("Shouldn't get here"); 186 return 0; 187} 188 189static bool isSelect01(Constant *C1, Constant *C2) { 190 ConstantInt *C1I = dyn_cast<ConstantInt>(C1); 191 if (!C1I) 192 return false; 193 ConstantInt *C2I = dyn_cast<ConstantInt>(C2); 194 if (!C2I) 195 return false; 196 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero. 197 return false; 198 return C1I->isOne() || C1I->isAllOnesValue() || 199 C2I->isOne() || C2I->isAllOnesValue(); 200} 201 202/// FoldSelectIntoOp - Try fold the select into one of the operands to 203/// facilitate further optimization. 204Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal, 205 Value *FalseVal) { 206 // See the comment above GetSelectFoldableOperands for a description of the 207 // transformation we are doing here. 208 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) { 209 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 && 210 !isa<Constant>(FalseVal)) { 211 if (unsigned SFO = GetSelectFoldableOperands(TVI)) { 212 unsigned OpToFold = 0; 213 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 214 OpToFold = 1; 215 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 216 OpToFold = 2; 217 } 218 219 if (OpToFold) { 220 Constant *C = GetSelectFoldableConstant(TVI); 221 Value *OOp = TVI->getOperand(2-OpToFold); 222 // Avoid creating select between 2 constants unless it's selecting 223 // between 0, 1 and -1. 224 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 225 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C); 226 NewSel->takeName(TVI); 227 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI); 228 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(), 229 FalseVal, NewSel); 230 if (isa<PossiblyExactOperator>(BO)) 231 BO->setIsExact(TVI_BO->isExact()); 232 if (isa<OverflowingBinaryOperator>(BO)) { 233 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap()); 234 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap()); 235 } 236 return BO; 237 } 238 } 239 } 240 } 241 } 242 243 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) { 244 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 && 245 !isa<Constant>(TrueVal)) { 246 if (unsigned SFO = GetSelectFoldableOperands(FVI)) { 247 unsigned OpToFold = 0; 248 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 249 OpToFold = 1; 250 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 251 OpToFold = 2; 252 } 253 254 if (OpToFold) { 255 Constant *C = GetSelectFoldableConstant(FVI); 256 Value *OOp = FVI->getOperand(2-OpToFold); 257 // Avoid creating select between 2 constants unless it's selecting 258 // between 0, 1 and -1. 259 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 260 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp); 261 NewSel->takeName(FVI); 262 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI); 263 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(), 264 TrueVal, NewSel); 265 if (isa<PossiblyExactOperator>(BO)) 266 BO->setIsExact(FVI_BO->isExact()); 267 if (isa<OverflowingBinaryOperator>(BO)) { 268 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap()); 269 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap()); 270 } 271 return BO; 272 } 273 } 274 } 275 } 276 } 277 278 return 0; 279} 280 281/// visitSelectInstWithICmp - Visit a SelectInst that has an 282/// ICmpInst as its first operand. 283/// 284Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI, 285 ICmpInst *ICI) { 286 bool Changed = false; 287 ICmpInst::Predicate Pred = ICI->getPredicate(); 288 Value *CmpLHS = ICI->getOperand(0); 289 Value *CmpRHS = ICI->getOperand(1); 290 Value *TrueVal = SI.getTrueValue(); 291 Value *FalseVal = SI.getFalseValue(); 292 293 // Check cases where the comparison is with a constant that 294 // can be adjusted to fit the min/max idiom. We may move or edit ICI 295 // here, so make sure the select is the only user. 296 if (ICI->hasOneUse()) 297 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) { 298 // X < MIN ? T : F --> F 299 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) 300 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT)) 301 return ReplaceInstUsesWith(SI, FalseVal); 302 // X > MAX ? T : F --> F 303 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT) 304 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT)) 305 return ReplaceInstUsesWith(SI, FalseVal); 306 switch (Pred) { 307 default: break; 308 case ICmpInst::ICMP_ULT: 309 case ICmpInst::ICMP_SLT: 310 case ICmpInst::ICMP_UGT: 311 case ICmpInst::ICMP_SGT: { 312 // These transformations only work for selects over integers. 313 const IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType()); 314 if (!SelectTy) 315 break; 316 317 Constant *AdjustedRHS; 318 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 319 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1); 320 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 321 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1); 322 323 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 324 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 325 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 326 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) 327 ; // Nothing to do here. Values match without any sign/zero extension. 328 329 // Types do not match. Instead of calculating this with mixed types 330 // promote all to the larger type. This enables scalar evolution to 331 // analyze this expression. 332 else if (CmpRHS->getType()->getScalarSizeInBits() 333 < SelectTy->getBitWidth()) { 334 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy); 335 336 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 337 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 338 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 339 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 340 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && 341 sextRHS == FalseVal) { 342 CmpLHS = TrueVal; 343 AdjustedRHS = sextRHS; 344 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 345 sextRHS == TrueVal) { 346 CmpLHS = FalseVal; 347 AdjustedRHS = sextRHS; 348 } else if (ICI->isUnsigned()) { 349 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy); 350 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 351 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 352 // zext + signed compare cannot be changed: 353 // 0xff <s 0x00, but 0x00ff >s 0x0000 354 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && 355 zextRHS == FalseVal) { 356 CmpLHS = TrueVal; 357 AdjustedRHS = zextRHS; 358 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 359 zextRHS == TrueVal) { 360 CmpLHS = FalseVal; 361 AdjustedRHS = zextRHS; 362 } else 363 break; 364 } else 365 break; 366 } else 367 break; 368 369 Pred = ICmpInst::getSwappedPredicate(Pred); 370 CmpRHS = AdjustedRHS; 371 std::swap(FalseVal, TrueVal); 372 ICI->setPredicate(Pred); 373 ICI->setOperand(0, CmpLHS); 374 ICI->setOperand(1, CmpRHS); 375 SI.setOperand(1, TrueVal); 376 SI.setOperand(2, FalseVal); 377 378 // Move ICI instruction right before the select instruction. Otherwise 379 // the sext/zext value may be defined after the ICI instruction uses it. 380 ICI->moveBefore(&SI); 381 382 Changed = true; 383 break; 384 } 385 } 386 } 387 388 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1 389 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1 390 // FIXME: Type and constness constraints could be lifted, but we have to 391 // watch code size carefully. We should consider xor instead of 392 // sub/add when we decide to do that. 393 if (const IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) { 394 if (TrueVal->getType() == Ty) { 395 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) { 396 ConstantInt *C1 = NULL, *C2 = NULL; 397 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) { 398 C1 = dyn_cast<ConstantInt>(TrueVal); 399 C2 = dyn_cast<ConstantInt>(FalseVal); 400 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) { 401 C1 = dyn_cast<ConstantInt>(FalseVal); 402 C2 = dyn_cast<ConstantInt>(TrueVal); 403 } 404 if (C1 && C2) { 405 // This shift results in either -1 or 0. 406 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1); 407 408 // Check if we can express the operation with a single or. 409 if (C2->isAllOnesValue()) 410 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1)); 411 412 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue()); 413 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1)); 414 } 415 } 416 } 417 } 418 419 if (CmpLHS == TrueVal && CmpRHS == FalseVal) { 420 // Transform (X == Y) ? X : Y -> Y 421 if (Pred == ICmpInst::ICMP_EQ) 422 return ReplaceInstUsesWith(SI, FalseVal); 423 // Transform (X != Y) ? X : Y -> X 424 if (Pred == ICmpInst::ICMP_NE) 425 return ReplaceInstUsesWith(SI, TrueVal); 426 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX 427 428 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) { 429 // Transform (X == Y) ? Y : X -> X 430 if (Pred == ICmpInst::ICMP_EQ) 431 return ReplaceInstUsesWith(SI, FalseVal); 432 // Transform (X != Y) ? Y : X -> Y 433 if (Pred == ICmpInst::ICMP_NE) 434 return ReplaceInstUsesWith(SI, TrueVal); 435 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX 436 } 437 438 if (isa<Constant>(CmpRHS)) { 439 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 440 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 441 SI.setOperand(1, CmpRHS); 442 Changed = true; 443 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 444 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 445 SI.setOperand(2, CmpRHS); 446 Changed = true; 447 } 448 } 449 450 return Changed ? &SI : 0; 451} 452 453 454/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a 455/// PHI node (but the two may be in different blocks). See if the true/false 456/// values (V) are live in all of the predecessor blocks of the PHI. For 457/// example, cases like this cannot be mapped: 458/// 459/// X = phi [ C1, BB1], [C2, BB2] 460/// Y = add 461/// Z = select X, Y, 0 462/// 463/// because Y is not live in BB1/BB2. 464/// 465static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V, 466 const SelectInst &SI) { 467 // If the value is a non-instruction value like a constant or argument, it 468 // can always be mapped. 469 const Instruction *I = dyn_cast<Instruction>(V); 470 if (I == 0) return true; 471 472 // If V is a PHI node defined in the same block as the condition PHI, we can 473 // map the arguments. 474 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 475 476 if (const PHINode *VP = dyn_cast<PHINode>(I)) 477 if (VP->getParent() == CondPHI->getParent()) 478 return true; 479 480 // Otherwise, if the PHI and select are defined in the same block and if V is 481 // defined in a different block, then we can transform it. 482 if (SI.getParent() == CondPHI->getParent() && 483 I->getParent() != CondPHI->getParent()) 484 return true; 485 486 // Otherwise we have a 'hard' case and we can't tell without doing more 487 // detailed dominator based analysis, punt. 488 return false; 489} 490 491/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form: 492/// SPF2(SPF1(A, B), C) 493Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner, 494 SelectPatternFlavor SPF1, 495 Value *A, Value *B, 496 Instruction &Outer, 497 SelectPatternFlavor SPF2, Value *C) { 498 if (C == A || C == B) { 499 // MAX(MAX(A, B), B) -> MAX(A, B) 500 // MIN(MIN(a, b), a) -> MIN(a, b) 501 if (SPF1 == SPF2) 502 return ReplaceInstUsesWith(Outer, Inner); 503 504 // MAX(MIN(a, b), a) -> a 505 // MIN(MAX(a, b), a) -> a 506 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 507 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 508 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 509 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 510 return ReplaceInstUsesWith(Outer, C); 511 } 512 513 // TODO: MIN(MIN(A, 23), 97) 514 return 0; 515} 516 517 518/// foldSelectICmpAnd - If one of the constants is zero (we know they can't 519/// both be) and we have an icmp instruction with zero, and we have an 'and' 520/// with the non-constant value and a power of two we can turn the select 521/// into a shift on the result of the 'and'. 522static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal, 523 ConstantInt *FalseVal, 524 InstCombiner::BuilderTy *Builder) { 525 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition()); 526 if (!IC || !IC->isEquality()) 527 return 0; 528 529 if (!match(IC->getOperand(1), m_Zero())) 530 return 0; 531 532 ConstantInt *AndRHS; 533 Value *LHS = IC->getOperand(0); 534 if (LHS->getType() != SI.getType() || 535 !match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS)))) 536 return 0; 537 538 // If both select arms are non-zero see if we have a select of the form 539 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic 540 // for 'x ? 2^n : 0' and fix the thing up at the end. 541 ConstantInt *Offset = 0; 542 if (!TrueVal->isZero() && !FalseVal->isZero()) { 543 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2()) 544 Offset = FalseVal; 545 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2()) 546 Offset = TrueVal; 547 else 548 return 0; 549 550 // Adjust TrueVal and FalseVal to the offset. 551 TrueVal = ConstantInt::get(Builder->getContext(), 552 TrueVal->getValue() - Offset->getValue()); 553 FalseVal = ConstantInt::get(Builder->getContext(), 554 FalseVal->getValue() - Offset->getValue()); 555 } 556 557 // Make sure the mask in the 'and' and one of the select arms is a power of 2. 558 if (!AndRHS->getValue().isPowerOf2() || 559 (!TrueVal->getValue().isPowerOf2() && 560 !FalseVal->getValue().isPowerOf2())) 561 return 0; 562 563 // Determine which shift is needed to transform result of the 'and' into the 564 // desired result. 565 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal; 566 unsigned ValZeros = ValC->getValue().logBase2(); 567 unsigned AndZeros = AndRHS->getValue().logBase2(); 568 569 Value *V = LHS; 570 if (ValZeros > AndZeros) 571 V = Builder->CreateShl(V, ValZeros - AndZeros); 572 else if (ValZeros < AndZeros) 573 V = Builder->CreateLShr(V, AndZeros - ValZeros); 574 575 // Okay, now we know that everything is set up, we just don't know whether we 576 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 577 bool ShouldNotVal = !TrueVal->isZero(); 578 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE; 579 if (ShouldNotVal) 580 V = Builder->CreateXor(V, ValC); 581 582 // Apply an offset if needed. 583 if (Offset) 584 V = Builder->CreateAdd(V, Offset); 585 return V; 586} 587 588Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 589 Value *CondVal = SI.getCondition(); 590 Value *TrueVal = SI.getTrueValue(); 591 Value *FalseVal = SI.getFalseValue(); 592 593 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, TD)) 594 return ReplaceInstUsesWith(SI, V); 595 596 if (SI.getType()->isIntegerTy(1)) { 597 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) { 598 if (C->getZExtValue()) { 599 // Change: A = select B, true, C --> A = or B, C 600 return BinaryOperator::CreateOr(CondVal, FalseVal); 601 } 602 // Change: A = select B, false, C --> A = and !B, C 603 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 604 return BinaryOperator::CreateAnd(NotCond, FalseVal); 605 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) { 606 if (C->getZExtValue() == false) { 607 // Change: A = select B, C, false --> A = and B, C 608 return BinaryOperator::CreateAnd(CondVal, TrueVal); 609 } 610 // Change: A = select B, C, true --> A = or !B, C 611 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 612 return BinaryOperator::CreateOr(NotCond, TrueVal); 613 } 614 615 // select a, b, a -> a&b 616 // select a, a, b -> a|b 617 if (CondVal == TrueVal) 618 return BinaryOperator::CreateOr(CondVal, FalseVal); 619 else if (CondVal == FalseVal) 620 return BinaryOperator::CreateAnd(CondVal, TrueVal); 621 } 622 623 // Selecting between two integer constants? 624 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal)) 625 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) { 626 // select C, 1, 0 -> zext C to int 627 if (FalseValC->isZero() && TrueValC->getValue() == 1) 628 return new ZExtInst(CondVal, SI.getType()); 629 630 // select C, -1, 0 -> sext C to int 631 if (FalseValC->isZero() && TrueValC->isAllOnesValue()) 632 return new SExtInst(CondVal, SI.getType()); 633 634 // select C, 0, 1 -> zext !C to int 635 if (TrueValC->isZero() && FalseValC->getValue() == 1) { 636 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 637 return new ZExtInst(NotCond, SI.getType()); 638 } 639 640 // select C, 0, -1 -> sext !C to int 641 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) { 642 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 643 return new SExtInst(NotCond, SI.getType()); 644 } 645 646 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder)) 647 return ReplaceInstUsesWith(SI, V); 648 } 649 650 // See if we are selecting two values based on a comparison of the two values. 651 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 652 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) { 653 // Transform (X == Y) ? X : Y -> Y 654 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 655 // This is not safe in general for floating point: 656 // consider X== -0, Y== +0. 657 // It becomes safe if either operand is a nonzero constant. 658 ConstantFP *CFPt, *CFPf; 659 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 660 !CFPt->getValueAPF().isZero()) || 661 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 662 !CFPf->getValueAPF().isZero())) 663 return ReplaceInstUsesWith(SI, FalseVal); 664 } 665 // Transform (X une Y) ? X : Y -> X 666 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 667 // This is not safe in general for floating point: 668 // consider X== -0, Y== +0. 669 // It becomes safe if either operand is a nonzero constant. 670 ConstantFP *CFPt, *CFPf; 671 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 672 !CFPt->getValueAPF().isZero()) || 673 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 674 !CFPf->getValueAPF().isZero())) 675 return ReplaceInstUsesWith(SI, TrueVal); 676 } 677 // NOTE: if we wanted to, this is where to detect MIN/MAX 678 679 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){ 680 // Transform (X == Y) ? Y : X -> X 681 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 682 // This is not safe in general for floating point: 683 // consider X== -0, Y== +0. 684 // It becomes safe if either operand is a nonzero constant. 685 ConstantFP *CFPt, *CFPf; 686 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 687 !CFPt->getValueAPF().isZero()) || 688 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 689 !CFPf->getValueAPF().isZero())) 690 return ReplaceInstUsesWith(SI, FalseVal); 691 } 692 // Transform (X une Y) ? Y : X -> Y 693 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 694 // This is not safe in general for floating point: 695 // consider X== -0, Y== +0. 696 // It becomes safe if either operand is a nonzero constant. 697 ConstantFP *CFPt, *CFPf; 698 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 699 !CFPt->getValueAPF().isZero()) || 700 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 701 !CFPf->getValueAPF().isZero())) 702 return ReplaceInstUsesWith(SI, TrueVal); 703 } 704 // NOTE: if we wanted to, this is where to detect MIN/MAX 705 } 706 // NOTE: if we wanted to, this is where to detect ABS 707 } 708 709 // See if we are selecting two values based on a comparison of the two values. 710 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 711 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI)) 712 return Result; 713 714 if (Instruction *TI = dyn_cast<Instruction>(TrueVal)) 715 if (Instruction *FI = dyn_cast<Instruction>(FalseVal)) 716 if (TI->hasOneUse() && FI->hasOneUse()) { 717 Instruction *AddOp = 0, *SubOp = 0; 718 719 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 720 if (TI->getOpcode() == FI->getOpcode()) 721 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI)) 722 return IV; 723 724 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is 725 // even legal for FP. 726 if ((TI->getOpcode() == Instruction::Sub && 727 FI->getOpcode() == Instruction::Add) || 728 (TI->getOpcode() == Instruction::FSub && 729 FI->getOpcode() == Instruction::FAdd)) { 730 AddOp = FI; SubOp = TI; 731 } else if ((FI->getOpcode() == Instruction::Sub && 732 TI->getOpcode() == Instruction::Add) || 733 (FI->getOpcode() == Instruction::FSub && 734 TI->getOpcode() == Instruction::FAdd)) { 735 AddOp = TI; SubOp = FI; 736 } 737 738 if (AddOp) { 739 Value *OtherAddOp = 0; 740 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 741 OtherAddOp = AddOp->getOperand(1); 742 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 743 OtherAddOp = AddOp->getOperand(0); 744 } 745 746 if (OtherAddOp) { 747 // So at this point we know we have (Y -> OtherAddOp): 748 // select C, (add X, Y), (sub X, Z) 749 Value *NegVal; // Compute -Z 750 if (SI.getType()->isFloatingPointTy()) { 751 NegVal = Builder->CreateFNeg(SubOp->getOperand(1)); 752 } else { 753 NegVal = Builder->CreateNeg(SubOp->getOperand(1)); 754 } 755 756 Value *NewTrueOp = OtherAddOp; 757 Value *NewFalseOp = NegVal; 758 if (AddOp != TI) 759 std::swap(NewTrueOp, NewFalseOp); 760 Value *NewSel = 761 Builder->CreateSelect(CondVal, NewTrueOp, 762 NewFalseOp, SI.getName() + ".p"); 763 764 if (SI.getType()->isFloatingPointTy()) 765 return BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 766 else 767 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 768 } 769 } 770 } 771 772 // See if we can fold the select into one of our operands. 773 if (SI.getType()->isIntegerTy()) { 774 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal)) 775 return FoldI; 776 777 // MAX(MAX(a, b), a) -> MAX(a, b) 778 // MIN(MIN(a, b), a) -> MIN(a, b) 779 // MAX(MIN(a, b), a) -> a 780 // MIN(MAX(a, b), a) -> a 781 Value *LHS, *RHS, *LHS2, *RHS2; 782 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) { 783 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2)) 784 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 785 SI, SPF, RHS)) 786 return R; 787 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2)) 788 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2, 789 SI, SPF, LHS)) 790 return R; 791 } 792 793 // TODO. 794 // ABS(-X) -> ABS(X) 795 // ABS(ABS(X)) -> ABS(X) 796 } 797 798 // See if we can fold the select into a phi node if the condition is a select. 799 if (isa<PHINode>(SI.getCondition())) 800 // The true/false values have to be live in the PHI predecessor's blocks. 801 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 802 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 803 if (Instruction *NV = FoldOpIntoPhi(SI)) 804 return NV; 805 806 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 807 if (TrueSI->getCondition() == CondVal) { 808 SI.setOperand(1, TrueSI->getTrueValue()); 809 return &SI; 810 } 811 } 812 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 813 if (FalseSI->getCondition() == CondVal) { 814 SI.setOperand(2, FalseSI->getFalseValue()); 815 return &SI; 816 } 817 } 818 819 if (BinaryOperator::isNot(CondVal)) { 820 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal)); 821 SI.setOperand(1, FalseVal); 822 SI.setOperand(2, TrueVal); 823 return &SI; 824 } 825 826 return 0; 827} 828