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/Analysis/ConstantFolding.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/IR/PatternMatch.h" 18 using namespace llvm; 19 using namespace PatternMatch; 20 21 #define DEBUG_TYPE "instcombine" 22 23 /// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms, 24 /// returning the kind and providing the out parameter results if we 25 /// successfully match. 26 static SelectPatternFlavor 27 MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) { 28 SelectInst *SI = dyn_cast<SelectInst>(V); 29 if (!SI) return SPF_UNKNOWN; 30 31 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition()); 32 if (!ICI) return SPF_UNKNOWN; 33 34 ICmpInst::Predicate Pred = ICI->getPredicate(); 35 Value *CmpLHS = ICI->getOperand(0); 36 Value *CmpRHS = ICI->getOperand(1); 37 Value *TrueVal = SI->getTrueValue(); 38 Value *FalseVal = SI->getFalseValue(); 39 40 LHS = CmpLHS; 41 RHS = CmpRHS; 42 43 // (icmp X, Y) ? X : Y 44 if (TrueVal == CmpLHS && FalseVal == CmpRHS) { 45 switch (Pred) { 46 default: return SPF_UNKNOWN; // Equality. 47 case ICmpInst::ICMP_UGT: 48 case ICmpInst::ICMP_UGE: return SPF_UMAX; 49 case ICmpInst::ICMP_SGT: 50 case ICmpInst::ICMP_SGE: return SPF_SMAX; 51 case ICmpInst::ICMP_ULT: 52 case ICmpInst::ICMP_ULE: return SPF_UMIN; 53 case ICmpInst::ICMP_SLT: 54 case ICmpInst::ICMP_SLE: return SPF_SMIN; 55 } 56 } 57 58 // (icmp X, Y) ? Y : X 59 if (TrueVal == CmpRHS && FalseVal == CmpLHS) { 60 switch (Pred) { 61 default: return SPF_UNKNOWN; // Equality. 62 case ICmpInst::ICMP_UGT: 63 case ICmpInst::ICMP_UGE: return SPF_UMIN; 64 case ICmpInst::ICMP_SGT: 65 case ICmpInst::ICMP_SGE: return SPF_SMIN; 66 case ICmpInst::ICMP_ULT: 67 case ICmpInst::ICMP_ULE: return SPF_UMAX; 68 case ICmpInst::ICMP_SLT: 69 case ICmpInst::ICMP_SLE: return SPF_SMAX; 70 } 71 } 72 73 if (ConstantInt *C1 = dyn_cast<ConstantInt>(CmpRHS)) { 74 if ((CmpLHS == TrueVal && match(FalseVal, m_Neg(m_Specific(CmpLHS)))) || 75 (CmpLHS == FalseVal && match(TrueVal, m_Neg(m_Specific(CmpLHS))))) { 76 77 // ABS(X) ==> (X >s 0) ? X : -X and (X >s -1) ? X : -X 78 // NABS(X) ==> (X >s 0) ? -X : X and (X >s -1) ? -X : X 79 if (Pred == ICmpInst::ICMP_SGT && (C1->isZero() || C1->isMinusOne())) { 80 return (CmpLHS == TrueVal) ? SPF_ABS : SPF_NABS; 81 } 82 83 // ABS(X) ==> (X <s 0) ? -X : X and (X <s 1) ? -X : X 84 // NABS(X) ==> (X <s 0) ? X : -X and (X <s 1) ? X : -X 85 if (Pred == ICmpInst::ICMP_SLT && (C1->isZero() || C1->isOne())) { 86 return (CmpLHS == FalseVal) ? SPF_ABS : SPF_NABS; 87 } 88 } 89 } 90 91 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5) 92 93 return SPF_UNKNOWN; 94 } 95 96 97 /// GetSelectFoldableOperands - We want to turn code that looks like this: 98 /// %C = or %A, %B 99 /// %D = select %cond, %C, %A 100 /// into: 101 /// %C = select %cond, %B, 0 102 /// %D = or %A, %C 103 /// 104 /// Assuming that the specified instruction is an operand to the select, return 105 /// a bitmask indicating which operands of this instruction are foldable if they 106 /// equal the other incoming value of the select. 107 /// 108 static unsigned GetSelectFoldableOperands(Instruction *I) { 109 switch (I->getOpcode()) { 110 case Instruction::Add: 111 case Instruction::Mul: 112 case Instruction::And: 113 case Instruction::Or: 114 case Instruction::Xor: 115 return 3; // Can fold through either operand. 116 case Instruction::Sub: // Can only fold on the amount subtracted. 117 case Instruction::Shl: // Can only fold on the shift amount. 118 case Instruction::LShr: 119 case Instruction::AShr: 120 return 1; 121 default: 122 return 0; // Cannot fold 123 } 124 } 125 126 /// GetSelectFoldableConstant - For the same transformation as the previous 127 /// function, return the identity constant that goes into the select. 128 static Constant *GetSelectFoldableConstant(Instruction *I) { 129 switch (I->getOpcode()) { 130 default: llvm_unreachable("This cannot happen!"); 131 case Instruction::Add: 132 case Instruction::Sub: 133 case Instruction::Or: 134 case Instruction::Xor: 135 case Instruction::Shl: 136 case Instruction::LShr: 137 case Instruction::AShr: 138 return Constant::getNullValue(I->getType()); 139 case Instruction::And: 140 return Constant::getAllOnesValue(I->getType()); 141 case Instruction::Mul: 142 return ConstantInt::get(I->getType(), 1); 143 } 144 } 145 146 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI 147 /// have the same opcode and only one use each. Try to simplify this. 148 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI, 149 Instruction *FI) { 150 if (TI->getNumOperands() == 1) { 151 // If this is a non-volatile load or a cast from the same type, 152 // merge. 153 if (TI->isCast()) { 154 Type *FIOpndTy = FI->getOperand(0)->getType(); 155 if (TI->getOperand(0)->getType() != FIOpndTy) 156 return nullptr; 157 // The select condition may be a vector. We may only change the operand 158 // type if the vector width remains the same (and matches the condition). 159 Type *CondTy = SI.getCondition()->getType(); 160 if (CondTy->isVectorTy() && (!FIOpndTy->isVectorTy() || 161 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())) 162 return nullptr; 163 } else { 164 return nullptr; // unknown unary op. 165 } 166 167 // Fold this by inserting a select from the input values. 168 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0), 169 FI->getOperand(0), SI.getName()+".v"); 170 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 171 TI->getType()); 172 } 173 174 // Only handle binary operators here. 175 if (!isa<BinaryOperator>(TI)) 176 return nullptr; 177 178 // Figure out if the operations have any operands in common. 179 Value *MatchOp, *OtherOpT, *OtherOpF; 180 bool MatchIsOpZero; 181 if (TI->getOperand(0) == FI->getOperand(0)) { 182 MatchOp = TI->getOperand(0); 183 OtherOpT = TI->getOperand(1); 184 OtherOpF = FI->getOperand(1); 185 MatchIsOpZero = true; 186 } else if (TI->getOperand(1) == FI->getOperand(1)) { 187 MatchOp = TI->getOperand(1); 188 OtherOpT = TI->getOperand(0); 189 OtherOpF = FI->getOperand(0); 190 MatchIsOpZero = false; 191 } else if (!TI->isCommutative()) { 192 return nullptr; 193 } else if (TI->getOperand(0) == FI->getOperand(1)) { 194 MatchOp = TI->getOperand(0); 195 OtherOpT = TI->getOperand(1); 196 OtherOpF = FI->getOperand(0); 197 MatchIsOpZero = true; 198 } else if (TI->getOperand(1) == FI->getOperand(0)) { 199 MatchOp = TI->getOperand(1); 200 OtherOpT = TI->getOperand(0); 201 OtherOpF = FI->getOperand(1); 202 MatchIsOpZero = true; 203 } else { 204 return nullptr; 205 } 206 207 // If we reach here, they do have operations in common. 208 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, 209 OtherOpF, SI.getName()+".v"); 210 211 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) { 212 if (MatchIsOpZero) 213 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI); 214 else 215 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp); 216 } 217 llvm_unreachable("Shouldn't get here"); 218 } 219 220 static bool isSelect01(Constant *C1, Constant *C2) { 221 ConstantInt *C1I = dyn_cast<ConstantInt>(C1); 222 if (!C1I) 223 return false; 224 ConstantInt *C2I = dyn_cast<ConstantInt>(C2); 225 if (!C2I) 226 return false; 227 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero. 228 return false; 229 return C1I->isOne() || C1I->isAllOnesValue() || 230 C2I->isOne() || C2I->isAllOnesValue(); 231 } 232 233 /// FoldSelectIntoOp - Try fold the select into one of the operands to 234 /// facilitate further optimization. 235 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal, 236 Value *FalseVal) { 237 // See the comment above GetSelectFoldableOperands for a description of the 238 // transformation we are doing here. 239 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) { 240 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 && 241 !isa<Constant>(FalseVal)) { 242 if (unsigned SFO = GetSelectFoldableOperands(TVI)) { 243 unsigned OpToFold = 0; 244 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 245 OpToFold = 1; 246 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 247 OpToFold = 2; 248 } 249 250 if (OpToFold) { 251 Constant *C = GetSelectFoldableConstant(TVI); 252 Value *OOp = TVI->getOperand(2-OpToFold); 253 // Avoid creating select between 2 constants unless it's selecting 254 // between 0, 1 and -1. 255 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 256 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C); 257 NewSel->takeName(TVI); 258 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI); 259 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(), 260 FalseVal, NewSel); 261 if (isa<PossiblyExactOperator>(BO)) 262 BO->setIsExact(TVI_BO->isExact()); 263 if (isa<OverflowingBinaryOperator>(BO)) { 264 BO->setHasNoUnsignedWrap(TVI_BO->hasNoUnsignedWrap()); 265 BO->setHasNoSignedWrap(TVI_BO->hasNoSignedWrap()); 266 } 267 return BO; 268 } 269 } 270 } 271 } 272 } 273 274 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) { 275 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 && 276 !isa<Constant>(TrueVal)) { 277 if (unsigned SFO = GetSelectFoldableOperands(FVI)) { 278 unsigned OpToFold = 0; 279 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 280 OpToFold = 1; 281 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 282 OpToFold = 2; 283 } 284 285 if (OpToFold) { 286 Constant *C = GetSelectFoldableConstant(FVI); 287 Value *OOp = FVI->getOperand(2-OpToFold); 288 // Avoid creating select between 2 constants unless it's selecting 289 // between 0, 1 and -1. 290 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 291 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp); 292 NewSel->takeName(FVI); 293 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI); 294 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(), 295 TrueVal, NewSel); 296 if (isa<PossiblyExactOperator>(BO)) 297 BO->setIsExact(FVI_BO->isExact()); 298 if (isa<OverflowingBinaryOperator>(BO)) { 299 BO->setHasNoUnsignedWrap(FVI_BO->hasNoUnsignedWrap()); 300 BO->setHasNoSignedWrap(FVI_BO->hasNoSignedWrap()); 301 } 302 return BO; 303 } 304 } 305 } 306 } 307 } 308 309 return nullptr; 310 } 311 312 /// SimplifyWithOpReplaced - See if V simplifies when its operand Op is 313 /// replaced with RepOp. 314 static Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 315 const DataLayout *TD, 316 const TargetLibraryInfo *TLI, 317 DominatorTree *DT, 318 AssumptionTracker *AT) { 319 // Trivial replacement. 320 if (V == Op) 321 return RepOp; 322 323 Instruction *I = dyn_cast<Instruction>(V); 324 if (!I) 325 return nullptr; 326 327 // If this is a binary operator, try to simplify it with the replaced op. 328 if (BinaryOperator *B = dyn_cast<BinaryOperator>(I)) { 329 if (B->getOperand(0) == Op) 330 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), TD, TLI); 331 if (B->getOperand(1) == Op) 332 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, TD, TLI); 333 } 334 335 // Same for CmpInsts. 336 if (CmpInst *C = dyn_cast<CmpInst>(I)) { 337 if (C->getOperand(0) == Op) 338 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), TD, 339 TLI, DT, AT); 340 if (C->getOperand(1) == Op) 341 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, TD, 342 TLI, DT, AT); 343 } 344 345 // TODO: We could hand off more cases to instsimplify here. 346 347 // If all operands are constant after substituting Op for RepOp then we can 348 // constant fold the instruction. 349 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) { 350 // Build a list of all constant operands. 351 SmallVector<Constant*, 8> ConstOps; 352 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) { 353 if (I->getOperand(i) == Op) 354 ConstOps.push_back(CRepOp); 355 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i))) 356 ConstOps.push_back(COp); 357 else 358 break; 359 } 360 361 // All operands were constants, fold it. 362 if (ConstOps.size() == I->getNumOperands()) { 363 if (CmpInst *C = dyn_cast<CmpInst>(I)) 364 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0], 365 ConstOps[1], TD, TLI); 366 367 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 368 if (!LI->isVolatile()) 369 return ConstantFoldLoadFromConstPtr(ConstOps[0], TD); 370 371 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), 372 ConstOps, TD, TLI); 373 } 374 } 375 376 return nullptr; 377 } 378 379 /// foldSelectICmpAndOr - We want to turn: 380 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) 381 /// into: 382 /// (or (shl (and X, C1), C3), y) 383 /// iff: 384 /// C1 and C2 are both powers of 2 385 /// where: 386 /// C3 = Log(C2) - Log(C1) 387 /// 388 /// This transform handles cases where: 389 /// 1. The icmp predicate is inverted 390 /// 2. The select operands are reversed 391 /// 3. The magnitude of C2 and C1 are flipped 392 /// 393 /// This also tries to turn 394 /// --- Single bit tests: 395 /// if ((x & C) == 0) x |= C to x |= C 396 /// if ((x & C) != 0) x ^= C to x &= ~C 397 /// if ((x & C) == 0) x ^= C to x |= C 398 /// if ((x & C) != 0) x &= ~C to x &= ~C 399 /// if ((x & C) == 0) x &= ~C to nothing 400 static Value *foldSelectICmpAndOr(SelectInst &SI, Value *TrueVal, 401 Value *FalseVal, 402 InstCombiner::BuilderTy *Builder) { 403 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition()); 404 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy()) 405 return nullptr; 406 407 Value *CmpLHS = IC->getOperand(0); 408 Value *CmpRHS = IC->getOperand(1); 409 410 if (!match(CmpRHS, m_Zero())) 411 return nullptr; 412 413 Value *X; 414 const APInt *C1; 415 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1)))) 416 return nullptr; 417 418 const APInt *C2; 419 if (match(TrueVal, m_Specific(X))) { 420 // if ((X & C) != 0) X ^= C becomes X &= ~C 421 if (match(FalseVal, m_Xor(m_Specific(X), m_APInt(C2))) && C1 == C2) 422 return Builder->CreateAnd(X, ~(*C1)); 423 // if ((X & C) != 0) X &= ~C becomes X &= ~C 424 if (match(FalseVal, m_And(m_Specific(X), m_APInt(C2))) && *C1 == ~(*C2)) 425 return FalseVal; 426 } else if (match(FalseVal, m_Specific(X))) { 427 // if ((X & C) == 0) X ^= C becomes X |= C 428 if (match(TrueVal, m_Xor(m_Specific(X), m_APInt(C2))) && C1 == C2) 429 return Builder->CreateOr(X, *C1); 430 // if ((X & C) == 0) X &= ~C becomes nothing 431 if (match(TrueVal, m_And(m_Specific(X), m_APInt(C2))) && *C1 == ~(*C2)) 432 return X; 433 // if ((X & C) == 0) X |= C becomes X |= C 434 if (match(TrueVal, m_Or(m_Specific(X), m_APInt(C2))) && C1 == C2) 435 return TrueVal; 436 } 437 438 bool OrOnTrueVal = false; 439 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2))); 440 if (!OrOnFalseVal) 441 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2))); 442 443 if (!OrOnFalseVal && !OrOnTrueVal) 444 return nullptr; 445 446 Value *V = CmpLHS; 447 Value *Y = OrOnFalseVal ? TrueVal : FalseVal; 448 449 unsigned C1Log = C1->logBase2(); 450 unsigned C2Log = C2->logBase2(); 451 if (C2Log > C1Log) { 452 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 453 V = Builder->CreateShl(V, C2Log - C1Log); 454 } else if (C1Log > C2Log) { 455 V = Builder->CreateLShr(V, C1Log - C2Log); 456 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 457 } else 458 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 459 460 ICmpInst::Predicate Pred = IC->getPredicate(); 461 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) || 462 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal)) 463 V = Builder->CreateXor(V, *C2); 464 465 return Builder->CreateOr(V, Y); 466 } 467 468 /// visitSelectInstWithICmp - Visit a SelectInst that has an 469 /// ICmpInst as its first operand. 470 /// 471 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI, 472 ICmpInst *ICI) { 473 bool Changed = false; 474 ICmpInst::Predicate Pred = ICI->getPredicate(); 475 Value *CmpLHS = ICI->getOperand(0); 476 Value *CmpRHS = ICI->getOperand(1); 477 Value *TrueVal = SI.getTrueValue(); 478 Value *FalseVal = SI.getFalseValue(); 479 480 // Check cases where the comparison is with a constant that 481 // can be adjusted to fit the min/max idiom. We may move or edit ICI 482 // here, so make sure the select is the only user. 483 if (ICI->hasOneUse()) 484 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) { 485 // X < MIN ? T : F --> F 486 if ((Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_ULT) 487 && CI->isMinValue(Pred == ICmpInst::ICMP_SLT)) 488 return ReplaceInstUsesWith(SI, FalseVal); 489 // X > MAX ? T : F --> F 490 else if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_UGT) 491 && CI->isMaxValue(Pred == ICmpInst::ICMP_SGT)) 492 return ReplaceInstUsesWith(SI, FalseVal); 493 switch (Pred) { 494 default: break; 495 case ICmpInst::ICMP_ULT: 496 case ICmpInst::ICMP_SLT: 497 case ICmpInst::ICMP_UGT: 498 case ICmpInst::ICMP_SGT: { 499 // These transformations only work for selects over integers. 500 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType()); 501 if (!SelectTy) 502 break; 503 504 Constant *AdjustedRHS; 505 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 506 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1); 507 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 508 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1); 509 510 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 511 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 512 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 513 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) 514 ; // Nothing to do here. Values match without any sign/zero extension. 515 516 // Types do not match. Instead of calculating this with mixed types 517 // promote all to the larger type. This enables scalar evolution to 518 // analyze this expression. 519 else if (CmpRHS->getType()->getScalarSizeInBits() 520 < SelectTy->getBitWidth()) { 521 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy); 522 523 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 524 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 525 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 526 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 527 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && 528 sextRHS == FalseVal) { 529 CmpLHS = TrueVal; 530 AdjustedRHS = sextRHS; 531 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 532 sextRHS == TrueVal) { 533 CmpLHS = FalseVal; 534 AdjustedRHS = sextRHS; 535 } else if (ICI->isUnsigned()) { 536 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy); 537 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 538 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 539 // zext + signed compare cannot be changed: 540 // 0xff <s 0x00, but 0x00ff >s 0x0000 541 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && 542 zextRHS == FalseVal) { 543 CmpLHS = TrueVal; 544 AdjustedRHS = zextRHS; 545 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 546 zextRHS == TrueVal) { 547 CmpLHS = FalseVal; 548 AdjustedRHS = zextRHS; 549 } else 550 break; 551 } else 552 break; 553 } else 554 break; 555 556 Pred = ICmpInst::getSwappedPredicate(Pred); 557 CmpRHS = AdjustedRHS; 558 std::swap(FalseVal, TrueVal); 559 ICI->setPredicate(Pred); 560 ICI->setOperand(0, CmpLHS); 561 ICI->setOperand(1, CmpRHS); 562 SI.setOperand(1, TrueVal); 563 SI.setOperand(2, FalseVal); 564 565 // Move ICI instruction right before the select instruction. Otherwise 566 // the sext/zext value may be defined after the ICI instruction uses it. 567 ICI->moveBefore(&SI); 568 569 Changed = true; 570 break; 571 } 572 } 573 } 574 575 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1 576 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1 577 // FIXME: Type and constness constraints could be lifted, but we have to 578 // watch code size carefully. We should consider xor instead of 579 // sub/add when we decide to do that. 580 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) { 581 if (TrueVal->getType() == Ty) { 582 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) { 583 ConstantInt *C1 = nullptr, *C2 = nullptr; 584 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) { 585 C1 = dyn_cast<ConstantInt>(TrueVal); 586 C2 = dyn_cast<ConstantInt>(FalseVal); 587 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) { 588 C1 = dyn_cast<ConstantInt>(FalseVal); 589 C2 = dyn_cast<ConstantInt>(TrueVal); 590 } 591 if (C1 && C2) { 592 // This shift results in either -1 or 0. 593 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1); 594 595 // Check if we can express the operation with a single or. 596 if (C2->isAllOnesValue()) 597 return ReplaceInstUsesWith(SI, Builder->CreateOr(AShr, C1)); 598 599 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue()); 600 return ReplaceInstUsesWith(SI, Builder->CreateAdd(And, C1)); 601 } 602 } 603 } 604 } 605 606 // If we have an equality comparison then we know the value in one of the 607 // arms of the select. See if substituting this value into the arm and 608 // simplifying the result yields the same value as the other arm. 609 if (Pred == ICmpInst::ICMP_EQ) { 610 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI, 611 DT, AT) == TrueVal || 612 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI, 613 DT, AT) == TrueVal) 614 return ReplaceInstUsesWith(SI, FalseVal); 615 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI, 616 DT, AT) == FalseVal || 617 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI, 618 DT, AT) == FalseVal) 619 return ReplaceInstUsesWith(SI, FalseVal); 620 } else if (Pred == ICmpInst::ICMP_NE) { 621 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, DL, TLI, 622 DT, AT) == FalseVal || 623 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, DL, TLI, 624 DT, AT) == FalseVal) 625 return ReplaceInstUsesWith(SI, TrueVal); 626 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, DL, TLI, 627 DT, AT) == TrueVal || 628 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, DL, TLI, 629 DT, AT) == TrueVal) 630 return ReplaceInstUsesWith(SI, TrueVal); 631 } 632 633 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 634 635 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 636 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 637 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 638 SI.setOperand(1, CmpRHS); 639 Changed = true; 640 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 641 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 642 SI.setOperand(2, CmpRHS); 643 Changed = true; 644 } 645 } 646 647 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder)) 648 return ReplaceInstUsesWith(SI, V); 649 650 return Changed ? &SI : nullptr; 651 } 652 653 654 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a 655 /// PHI node (but the two may be in different blocks). See if the true/false 656 /// values (V) are live in all of the predecessor blocks of the PHI. For 657 /// example, cases like this cannot be mapped: 658 /// 659 /// X = phi [ C1, BB1], [C2, BB2] 660 /// Y = add 661 /// Z = select X, Y, 0 662 /// 663 /// because Y is not live in BB1/BB2. 664 /// 665 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V, 666 const SelectInst &SI) { 667 // If the value is a non-instruction value like a constant or argument, it 668 // can always be mapped. 669 const Instruction *I = dyn_cast<Instruction>(V); 670 if (!I) return true; 671 672 // If V is a PHI node defined in the same block as the condition PHI, we can 673 // map the arguments. 674 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 675 676 if (const PHINode *VP = dyn_cast<PHINode>(I)) 677 if (VP->getParent() == CondPHI->getParent()) 678 return true; 679 680 // Otherwise, if the PHI and select are defined in the same block and if V is 681 // defined in a different block, then we can transform it. 682 if (SI.getParent() == CondPHI->getParent() && 683 I->getParent() != CondPHI->getParent()) 684 return true; 685 686 // Otherwise we have a 'hard' case and we can't tell without doing more 687 // detailed dominator based analysis, punt. 688 return false; 689 } 690 691 /// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form: 692 /// SPF2(SPF1(A, B), C) 693 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner, 694 SelectPatternFlavor SPF1, 695 Value *A, Value *B, 696 Instruction &Outer, 697 SelectPatternFlavor SPF2, Value *C) { 698 if (C == A || C == B) { 699 // MAX(MAX(A, B), B) -> MAX(A, B) 700 // MIN(MIN(a, b), a) -> MIN(a, b) 701 if (SPF1 == SPF2) 702 return ReplaceInstUsesWith(Outer, Inner); 703 704 // MAX(MIN(a, b), a) -> a 705 // MIN(MAX(a, b), a) -> a 706 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 707 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 708 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 709 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 710 return ReplaceInstUsesWith(Outer, C); 711 } 712 713 if (SPF1 == SPF2) { 714 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) { 715 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) { 716 APInt ACB = CB->getValue(); 717 APInt ACC = CC->getValue(); 718 719 // MIN(MIN(A, 23), 97) -> MIN(A, 23) 720 // MAX(MAX(A, 97), 23) -> MAX(A, 97) 721 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) || 722 (SPF1 == SPF_SMIN && ACB.sle(ACC)) || 723 (SPF1 == SPF_UMAX && ACB.uge(ACC)) || 724 (SPF1 == SPF_SMAX && ACB.sge(ACC))) 725 return ReplaceInstUsesWith(Outer, Inner); 726 727 // MIN(MIN(A, 97), 23) -> MIN(A, 23) 728 // MAX(MAX(A, 23), 97) -> MAX(A, 97) 729 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) || 730 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) || 731 (SPF1 == SPF_UMAX && ACB.ult(ACC)) || 732 (SPF1 == SPF_SMAX && ACB.slt(ACC))) { 733 Outer.replaceUsesOfWith(Inner, A); 734 return &Outer; 735 } 736 } 737 } 738 } 739 740 // ABS(ABS(X)) -> ABS(X) 741 // NABS(NABS(X)) -> NABS(X) 742 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) { 743 return ReplaceInstUsesWith(Outer, Inner); 744 } 745 746 // ABS(NABS(X)) -> ABS(X) 747 // NABS(ABS(X)) -> NABS(X) 748 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) || 749 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) { 750 SelectInst *SI = cast<SelectInst>(Inner); 751 Value *NewSI = Builder->CreateSelect( 752 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue()); 753 return ReplaceInstUsesWith(Outer, NewSI); 754 } 755 return nullptr; 756 } 757 758 /// foldSelectICmpAnd - If one of the constants is zero (we know they can't 759 /// both be) and we have an icmp instruction with zero, and we have an 'and' 760 /// with the non-constant value and a power of two we can turn the select 761 /// into a shift on the result of the 'and'. 762 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal, 763 ConstantInt *FalseVal, 764 InstCombiner::BuilderTy *Builder) { 765 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition()); 766 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy()) 767 return nullptr; 768 769 if (!match(IC->getOperand(1), m_Zero())) 770 return nullptr; 771 772 ConstantInt *AndRHS; 773 Value *LHS = IC->getOperand(0); 774 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS)))) 775 return nullptr; 776 777 // If both select arms are non-zero see if we have a select of the form 778 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic 779 // for 'x ? 2^n : 0' and fix the thing up at the end. 780 ConstantInt *Offset = nullptr; 781 if (!TrueVal->isZero() && !FalseVal->isZero()) { 782 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2()) 783 Offset = FalseVal; 784 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2()) 785 Offset = TrueVal; 786 else 787 return nullptr; 788 789 // Adjust TrueVal and FalseVal to the offset. 790 TrueVal = ConstantInt::get(Builder->getContext(), 791 TrueVal->getValue() - Offset->getValue()); 792 FalseVal = ConstantInt::get(Builder->getContext(), 793 FalseVal->getValue() - Offset->getValue()); 794 } 795 796 // Make sure the mask in the 'and' and one of the select arms is a power of 2. 797 if (!AndRHS->getValue().isPowerOf2() || 798 (!TrueVal->getValue().isPowerOf2() && 799 !FalseVal->getValue().isPowerOf2())) 800 return nullptr; 801 802 // Determine which shift is needed to transform result of the 'and' into the 803 // desired result. 804 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal; 805 unsigned ValZeros = ValC->getValue().logBase2(); 806 unsigned AndZeros = AndRHS->getValue().logBase2(); 807 808 // If types don't match we can still convert the select by introducing a zext 809 // or a trunc of the 'and'. The trunc case requires that all of the truncated 810 // bits are zero, we can figure that out by looking at the 'and' mask. 811 if (AndZeros >= ValC->getBitWidth()) 812 return nullptr; 813 814 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType()); 815 if (ValZeros > AndZeros) 816 V = Builder->CreateShl(V, ValZeros - AndZeros); 817 else if (ValZeros < AndZeros) 818 V = Builder->CreateLShr(V, AndZeros - ValZeros); 819 820 // Okay, now we know that everything is set up, we just don't know whether we 821 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 822 bool ShouldNotVal = !TrueVal->isZero(); 823 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE; 824 if (ShouldNotVal) 825 V = Builder->CreateXor(V, ValC); 826 827 // Apply an offset if needed. 828 if (Offset) 829 V = Builder->CreateAdd(V, Offset); 830 return V; 831 } 832 833 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 834 Value *CondVal = SI.getCondition(); 835 Value *TrueVal = SI.getTrueValue(); 836 Value *FalseVal = SI.getFalseValue(); 837 838 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, 839 DT, AT)) 840 return ReplaceInstUsesWith(SI, V); 841 842 if (SI.getType()->isIntegerTy(1)) { 843 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) { 844 if (C->getZExtValue()) { 845 // Change: A = select B, true, C --> A = or B, C 846 return BinaryOperator::CreateOr(CondVal, FalseVal); 847 } 848 // Change: A = select B, false, C --> A = and !B, C 849 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 850 return BinaryOperator::CreateAnd(NotCond, FalseVal); 851 } 852 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) { 853 if (C->getZExtValue() == false) { 854 // Change: A = select B, C, false --> A = and B, C 855 return BinaryOperator::CreateAnd(CondVal, TrueVal); 856 } 857 // Change: A = select B, C, true --> A = or !B, C 858 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 859 return BinaryOperator::CreateOr(NotCond, TrueVal); 860 } 861 862 // select a, b, a -> a&b 863 // select a, a, b -> a|b 864 if (CondVal == TrueVal) 865 return BinaryOperator::CreateOr(CondVal, FalseVal); 866 if (CondVal == FalseVal) 867 return BinaryOperator::CreateAnd(CondVal, TrueVal); 868 869 // select a, ~a, b -> (~a)&b 870 // select a, b, ~a -> (~a)|b 871 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 872 return BinaryOperator::CreateAnd(TrueVal, FalseVal); 873 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 874 return BinaryOperator::CreateOr(TrueVal, FalseVal); 875 } 876 877 // Selecting between two integer constants? 878 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal)) 879 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) { 880 // select C, 1, 0 -> zext C to int 881 if (FalseValC->isZero() && TrueValC->getValue() == 1) 882 return new ZExtInst(CondVal, SI.getType()); 883 884 // select C, -1, 0 -> sext C to int 885 if (FalseValC->isZero() && TrueValC->isAllOnesValue()) 886 return new SExtInst(CondVal, SI.getType()); 887 888 // select C, 0, 1 -> zext !C to int 889 if (TrueValC->isZero() && FalseValC->getValue() == 1) { 890 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 891 return new ZExtInst(NotCond, SI.getType()); 892 } 893 894 // select C, 0, -1 -> sext !C to int 895 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) { 896 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 897 return new SExtInst(NotCond, SI.getType()); 898 } 899 900 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder)) 901 return ReplaceInstUsesWith(SI, V); 902 } 903 904 // See if we are selecting two values based on a comparison of the two values. 905 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 906 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) { 907 // Transform (X == Y) ? X : Y -> Y 908 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 909 // This is not safe in general for floating point: 910 // consider X== -0, Y== +0. 911 // It becomes safe if either operand is a nonzero constant. 912 ConstantFP *CFPt, *CFPf; 913 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 914 !CFPt->getValueAPF().isZero()) || 915 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 916 !CFPf->getValueAPF().isZero())) 917 return ReplaceInstUsesWith(SI, FalseVal); 918 } 919 // Transform (X une Y) ? X : Y -> X 920 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 921 // This is not safe in general for floating point: 922 // consider X== -0, Y== +0. 923 // It becomes safe if either operand is a nonzero constant. 924 ConstantFP *CFPt, *CFPf; 925 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 926 !CFPt->getValueAPF().isZero()) || 927 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 928 !CFPf->getValueAPF().isZero())) 929 return ReplaceInstUsesWith(SI, TrueVal); 930 } 931 // NOTE: if we wanted to, this is where to detect MIN/MAX 932 933 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){ 934 // Transform (X == Y) ? Y : X -> X 935 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 936 // This is not safe in general for floating point: 937 // consider X== -0, Y== +0. 938 // It becomes safe if either operand is a nonzero constant. 939 ConstantFP *CFPt, *CFPf; 940 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 941 !CFPt->getValueAPF().isZero()) || 942 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 943 !CFPf->getValueAPF().isZero())) 944 return ReplaceInstUsesWith(SI, FalseVal); 945 } 946 // Transform (X une Y) ? Y : X -> Y 947 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 948 // This is not safe in general for floating point: 949 // consider X== -0, Y== +0. 950 // It becomes safe if either operand is a nonzero constant. 951 ConstantFP *CFPt, *CFPf; 952 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 953 !CFPt->getValueAPF().isZero()) || 954 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 955 !CFPf->getValueAPF().isZero())) 956 return ReplaceInstUsesWith(SI, TrueVal); 957 } 958 // NOTE: if we wanted to, this is where to detect MIN/MAX 959 } 960 // NOTE: if we wanted to, this is where to detect ABS 961 } 962 963 // See if we are selecting two values based on a comparison of the two values. 964 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 965 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI)) 966 return Result; 967 968 if (Instruction *TI = dyn_cast<Instruction>(TrueVal)) 969 if (Instruction *FI = dyn_cast<Instruction>(FalseVal)) 970 if (TI->hasOneUse() && FI->hasOneUse()) { 971 Instruction *AddOp = nullptr, *SubOp = nullptr; 972 973 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 974 if (TI->getOpcode() == FI->getOpcode()) 975 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI)) 976 return IV; 977 978 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is 979 // even legal for FP. 980 if ((TI->getOpcode() == Instruction::Sub && 981 FI->getOpcode() == Instruction::Add) || 982 (TI->getOpcode() == Instruction::FSub && 983 FI->getOpcode() == Instruction::FAdd)) { 984 AddOp = FI; SubOp = TI; 985 } else if ((FI->getOpcode() == Instruction::Sub && 986 TI->getOpcode() == Instruction::Add) || 987 (FI->getOpcode() == Instruction::FSub && 988 TI->getOpcode() == Instruction::FAdd)) { 989 AddOp = TI; SubOp = FI; 990 } 991 992 if (AddOp) { 993 Value *OtherAddOp = nullptr; 994 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 995 OtherAddOp = AddOp->getOperand(1); 996 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 997 OtherAddOp = AddOp->getOperand(0); 998 } 999 1000 if (OtherAddOp) { 1001 // So at this point we know we have (Y -> OtherAddOp): 1002 // select C, (add X, Y), (sub X, Z) 1003 Value *NegVal; // Compute -Z 1004 if (SI.getType()->isFPOrFPVectorTy()) { 1005 NegVal = Builder->CreateFNeg(SubOp->getOperand(1)); 1006 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 1007 FastMathFlags Flags = AddOp->getFastMathFlags(); 1008 Flags &= SubOp->getFastMathFlags(); 1009 NegInst->setFastMathFlags(Flags); 1010 } 1011 } else { 1012 NegVal = Builder->CreateNeg(SubOp->getOperand(1)); 1013 } 1014 1015 Value *NewTrueOp = OtherAddOp; 1016 Value *NewFalseOp = NegVal; 1017 if (AddOp != TI) 1018 std::swap(NewTrueOp, NewFalseOp); 1019 Value *NewSel = 1020 Builder->CreateSelect(CondVal, NewTrueOp, 1021 NewFalseOp, SI.getName() + ".p"); 1022 1023 if (SI.getType()->isFPOrFPVectorTy()) { 1024 Instruction *RI = 1025 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 1026 1027 FastMathFlags Flags = AddOp->getFastMathFlags(); 1028 Flags &= SubOp->getFastMathFlags(); 1029 RI->setFastMathFlags(Flags); 1030 return RI; 1031 } else 1032 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 1033 } 1034 } 1035 } 1036 1037 // See if we can fold the select into one of our operands. 1038 if (SI.getType()->isIntegerTy()) { 1039 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal)) 1040 return FoldI; 1041 1042 // MAX(MAX(a, b), a) -> MAX(a, b) 1043 // MIN(MIN(a, b), a) -> MIN(a, b) 1044 // MAX(MIN(a, b), a) -> a 1045 // MIN(MAX(a, b), a) -> a 1046 Value *LHS, *RHS, *LHS2, *RHS2; 1047 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) { 1048 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2)) 1049 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 1050 SI, SPF, RHS)) 1051 return R; 1052 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2)) 1053 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2, 1054 SI, SPF, LHS)) 1055 return R; 1056 } 1057 1058 // TODO. 1059 // ABS(-X) -> ABS(X) 1060 } 1061 1062 // See if we can fold the select into a phi node if the condition is a select. 1063 if (isa<PHINode>(SI.getCondition())) 1064 // The true/false values have to be live in the PHI predecessor's blocks. 1065 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 1066 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 1067 if (Instruction *NV = FoldOpIntoPhi(SI)) 1068 return NV; 1069 1070 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 1071 if (TrueSI->getCondition() == CondVal) { 1072 if (SI.getTrueValue() == TrueSI->getTrueValue()) 1073 return nullptr; 1074 SI.setOperand(1, TrueSI->getTrueValue()); 1075 return &SI; 1076 } 1077 } 1078 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 1079 if (FalseSI->getCondition() == CondVal) { 1080 if (SI.getFalseValue() == FalseSI->getFalseValue()) 1081 return nullptr; 1082 SI.setOperand(2, FalseSI->getFalseValue()); 1083 return &SI; 1084 } 1085 } 1086 1087 if (BinaryOperator::isNot(CondVal)) { 1088 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal)); 1089 SI.setOperand(1, FalseVal); 1090 SI.setOperand(2, TrueVal); 1091 return &SI; 1092 } 1093 1094 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) { 1095 unsigned VWidth = VecTy->getNumElements(); 1096 APInt UndefElts(VWidth, 0); 1097 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1098 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) { 1099 if (V != &SI) 1100 return ReplaceInstUsesWith(SI, V); 1101 return &SI; 1102 } 1103 1104 if (isa<ConstantAggregateZero>(CondVal)) { 1105 return ReplaceInstUsesWith(SI, FalseVal); 1106 } 1107 } 1108 1109 return nullptr; 1110 } 1111