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 "InstCombineInternal.h" 15 #include "llvm/ADT/APInt.h" 16 #include "llvm/ADT/Optional.h" 17 #include "llvm/ADT/STLExtras.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/Analysis/AssumptionCache.h" 20 #include "llvm/Analysis/CmpInstAnalysis.h" 21 #include "llvm/Analysis/InstructionSimplify.h" 22 #include "llvm/Analysis/ValueTracking.h" 23 #include "llvm/IR/BasicBlock.h" 24 #include "llvm/IR/Constant.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/DerivedTypes.h" 27 #include "llvm/IR/IRBuilder.h" 28 #include "llvm/IR/InstrTypes.h" 29 #include "llvm/IR/Instruction.h" 30 #include "llvm/IR/Instructions.h" 31 #include "llvm/IR/IntrinsicInst.h" 32 #include "llvm/IR/Intrinsics.h" 33 #include "llvm/IR/Operator.h" 34 #include "llvm/IR/PatternMatch.h" 35 #include "llvm/IR/Type.h" 36 #include "llvm/IR/User.h" 37 #include "llvm/IR/Value.h" 38 #include "llvm/Support/Casting.h" 39 #include "llvm/Support/ErrorHandling.h" 40 #include "llvm/Support/KnownBits.h" 41 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 42 #include <cassert> 43 #include <utility> 44 45 using namespace llvm; 46 using namespace PatternMatch; 47 48 #define DEBUG_TYPE "instcombine" 49 50 static Value *createMinMax(InstCombiner::BuilderTy &Builder, 51 SelectPatternFlavor SPF, Value *A, Value *B) { 52 CmpInst::Predicate Pred = getMinMaxPred(SPF); 53 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate"); 54 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B); 55 } 56 57 /// If one of the constants is zero (we know they can't both be) and we have an 58 /// icmp instruction with zero, and we have an 'and' with the non-constant value 59 /// and a power of two we can turn the select into a shift on the result of the 60 /// 'and'. 61 /// This folds: 62 /// select (icmp eq (and X, C1)), C2, C3 63 /// iff C1 is a power 2 and the difference between C2 and C3 is a power of 2. 64 /// To something like: 65 /// (shr (and (X, C1)), (log2(C1) - log2(C2-C3))) + C3 66 /// Or: 67 /// (shl (and (X, C1)), (log2(C2-C3) - log2(C1))) + C3 68 /// With some variations depending if C3 is larger than C2, or the shift 69 /// isn't needed, or the bit widths don't match. 70 static Value *foldSelectICmpAnd(Type *SelType, const ICmpInst *IC, 71 APInt TrueVal, APInt FalseVal, 72 InstCombiner::BuilderTy &Builder) { 73 assert(SelType->isIntOrIntVectorTy() && "Not an integer select?"); 74 75 // If this is a vector select, we need a vector compare. 76 if (SelType->isVectorTy() != IC->getType()->isVectorTy()) 77 return nullptr; 78 79 Value *V; 80 APInt AndMask; 81 bool CreateAnd = false; 82 ICmpInst::Predicate Pred = IC->getPredicate(); 83 if (ICmpInst::isEquality(Pred)) { 84 if (!match(IC->getOperand(1), m_Zero())) 85 return nullptr; 86 87 V = IC->getOperand(0); 88 89 const APInt *AndRHS; 90 if (!match(V, m_And(m_Value(), m_Power2(AndRHS)))) 91 return nullptr; 92 93 AndMask = *AndRHS; 94 } else if (decomposeBitTestICmp(IC->getOperand(0), IC->getOperand(1), 95 Pred, V, AndMask)) { 96 assert(ICmpInst::isEquality(Pred) && "Not equality test?"); 97 98 if (!AndMask.isPowerOf2()) 99 return nullptr; 100 101 CreateAnd = true; 102 } else { 103 return nullptr; 104 } 105 106 // If both select arms are non-zero see if we have a select of the form 107 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic 108 // for 'x ? 2^n : 0' and fix the thing up at the end. 109 APInt Offset(TrueVal.getBitWidth(), 0); 110 if (!TrueVal.isNullValue() && !FalseVal.isNullValue()) { 111 if ((TrueVal - FalseVal).isPowerOf2()) 112 Offset = FalseVal; 113 else if ((FalseVal - TrueVal).isPowerOf2()) 114 Offset = TrueVal; 115 else 116 return nullptr; 117 118 // Adjust TrueVal and FalseVal to the offset. 119 TrueVal -= Offset; 120 FalseVal -= Offset; 121 } 122 123 // Make sure one of the select arms is a power of 2. 124 if (!TrueVal.isPowerOf2() && !FalseVal.isPowerOf2()) 125 return nullptr; 126 127 // Determine which shift is needed to transform result of the 'and' into the 128 // desired result. 129 const APInt &ValC = !TrueVal.isNullValue() ? TrueVal : FalseVal; 130 unsigned ValZeros = ValC.logBase2(); 131 unsigned AndZeros = AndMask.logBase2(); 132 133 if (CreateAnd) { 134 // Insert the AND instruction on the input to the truncate. 135 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask)); 136 } 137 138 // If types don't match we can still convert the select by introducing a zext 139 // or a trunc of the 'and'. 140 if (ValZeros > AndZeros) { 141 V = Builder.CreateZExtOrTrunc(V, SelType); 142 V = Builder.CreateShl(V, ValZeros - AndZeros); 143 } else if (ValZeros < AndZeros) { 144 V = Builder.CreateLShr(V, AndZeros - ValZeros); 145 V = Builder.CreateZExtOrTrunc(V, SelType); 146 } else 147 V = Builder.CreateZExtOrTrunc(V, SelType); 148 149 // Okay, now we know that everything is set up, we just don't know whether we 150 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 151 bool ShouldNotVal = !TrueVal.isNullValue(); 152 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE; 153 if (ShouldNotVal) 154 V = Builder.CreateXor(V, ValC); 155 156 // Apply an offset if needed. 157 if (!Offset.isNullValue()) 158 V = Builder.CreateAdd(V, ConstantInt::get(V->getType(), Offset)); 159 return V; 160 } 161 162 /// We want to turn code that looks like this: 163 /// %C = or %A, %B 164 /// %D = select %cond, %C, %A 165 /// into: 166 /// %C = select %cond, %B, 0 167 /// %D = or %A, %C 168 /// 169 /// Assuming that the specified instruction is an operand to the select, return 170 /// a bitmask indicating which operands of this instruction are foldable if they 171 /// equal the other incoming value of the select. 172 static unsigned getSelectFoldableOperands(BinaryOperator *I) { 173 switch (I->getOpcode()) { 174 case Instruction::Add: 175 case Instruction::Mul: 176 case Instruction::And: 177 case Instruction::Or: 178 case Instruction::Xor: 179 return 3; // Can fold through either operand. 180 case Instruction::Sub: // Can only fold on the amount subtracted. 181 case Instruction::Shl: // Can only fold on the shift amount. 182 case Instruction::LShr: 183 case Instruction::AShr: 184 return 1; 185 default: 186 return 0; // Cannot fold 187 } 188 } 189 190 /// For the same transformation as the previous function, return the identity 191 /// constant that goes into the select. 192 static APInt getSelectFoldableConstant(BinaryOperator *I) { 193 switch (I->getOpcode()) { 194 default: llvm_unreachable("This cannot happen!"); 195 case Instruction::Add: 196 case Instruction::Sub: 197 case Instruction::Or: 198 case Instruction::Xor: 199 case Instruction::Shl: 200 case Instruction::LShr: 201 case Instruction::AShr: 202 return APInt::getNullValue(I->getType()->getScalarSizeInBits()); 203 case Instruction::And: 204 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits()); 205 case Instruction::Mul: 206 return APInt(I->getType()->getScalarSizeInBits(), 1); 207 } 208 } 209 210 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode. 211 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI, 212 Instruction *FI) { 213 // Don't break up min/max patterns. The hasOneUse checks below prevent that 214 // for most cases, but vector min/max with bitcasts can be transformed. If the 215 // one-use restrictions are eased for other patterns, we still don't want to 216 // obfuscate min/max. 217 if ((match(&SI, m_SMin(m_Value(), m_Value())) || 218 match(&SI, m_SMax(m_Value(), m_Value())) || 219 match(&SI, m_UMin(m_Value(), m_Value())) || 220 match(&SI, m_UMax(m_Value(), m_Value())))) 221 return nullptr; 222 223 // If this is a cast from the same type, merge. 224 if (TI->getNumOperands() == 1 && TI->isCast()) { 225 Type *FIOpndTy = FI->getOperand(0)->getType(); 226 if (TI->getOperand(0)->getType() != FIOpndTy) 227 return nullptr; 228 229 // The select condition may be a vector. We may only change the operand 230 // type if the vector width remains the same (and matches the condition). 231 Type *CondTy = SI.getCondition()->getType(); 232 if (CondTy->isVectorTy()) { 233 if (!FIOpndTy->isVectorTy()) 234 return nullptr; 235 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()) 236 return nullptr; 237 238 // TODO: If the backend knew how to deal with casts better, we could 239 // remove this limitation. For now, there's too much potential to create 240 // worse codegen by promoting the select ahead of size-altering casts 241 // (PR28160). 242 // 243 // Note that ValueTracking's matchSelectPattern() looks through casts 244 // without checking 'hasOneUse' when it matches min/max patterns, so this 245 // transform may end up happening anyway. 246 if (TI->getOpcode() != Instruction::BitCast && 247 (!TI->hasOneUse() || !FI->hasOneUse())) 248 return nullptr; 249 } else if (!TI->hasOneUse() || !FI->hasOneUse()) { 250 // TODO: The one-use restrictions for a scalar select could be eased if 251 // the fold of a select in visitLoadInst() was enhanced to match a pattern 252 // that includes a cast. 253 return nullptr; 254 } 255 256 // Fold this by inserting a select from the input values. 257 Value *NewSI = 258 Builder.CreateSelect(SI.getCondition(), TI->getOperand(0), 259 FI->getOperand(0), SI.getName() + ".v", &SI); 260 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 261 TI->getType()); 262 } 263 264 // Only handle binary operators (including two-operand getelementptr) with 265 // one-use here. As with the cast case above, it may be possible to relax the 266 // one-use constraint, but that needs be examined carefully since it may not 267 // reduce the total number of instructions. 268 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 || 269 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) || 270 !TI->hasOneUse() || !FI->hasOneUse()) 271 return nullptr; 272 273 // Figure out if the operations have any operands in common. 274 Value *MatchOp, *OtherOpT, *OtherOpF; 275 bool MatchIsOpZero; 276 if (TI->getOperand(0) == FI->getOperand(0)) { 277 MatchOp = TI->getOperand(0); 278 OtherOpT = TI->getOperand(1); 279 OtherOpF = FI->getOperand(1); 280 MatchIsOpZero = true; 281 } else if (TI->getOperand(1) == FI->getOperand(1)) { 282 MatchOp = TI->getOperand(1); 283 OtherOpT = TI->getOperand(0); 284 OtherOpF = FI->getOperand(0); 285 MatchIsOpZero = false; 286 } else if (!TI->isCommutative()) { 287 return nullptr; 288 } else if (TI->getOperand(0) == FI->getOperand(1)) { 289 MatchOp = TI->getOperand(0); 290 OtherOpT = TI->getOperand(1); 291 OtherOpF = FI->getOperand(0); 292 MatchIsOpZero = true; 293 } else if (TI->getOperand(1) == FI->getOperand(0)) { 294 MatchOp = TI->getOperand(1); 295 OtherOpT = TI->getOperand(0); 296 OtherOpF = FI->getOperand(1); 297 MatchIsOpZero = true; 298 } else { 299 return nullptr; 300 } 301 302 // If we reach here, they do have operations in common. 303 Value *NewSI = Builder.CreateSelect(SI.getCondition(), OtherOpT, OtherOpF, 304 SI.getName() + ".v", &SI); 305 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI; 306 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp; 307 if (auto *BO = dyn_cast<BinaryOperator>(TI)) { 308 return BinaryOperator::Create(BO->getOpcode(), Op0, Op1); 309 } 310 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) { 311 auto *FGEP = cast<GetElementPtrInst>(FI); 312 Type *ElementType = TGEP->getResultElementType(); 313 return TGEP->isInBounds() && FGEP->isInBounds() 314 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1}) 315 : GetElementPtrInst::Create(ElementType, Op0, {Op1}); 316 } 317 llvm_unreachable("Expected BinaryOperator or GEP"); 318 return nullptr; 319 } 320 321 static bool isSelect01(const APInt &C1I, const APInt &C2I) { 322 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero. 323 return false; 324 return C1I.isOneValue() || C1I.isAllOnesValue() || 325 C2I.isOneValue() || C2I.isAllOnesValue(); 326 } 327 328 /// Try to fold the select into one of the operands to allow further 329 /// optimization. 330 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal, 331 Value *FalseVal) { 332 // See the comment above GetSelectFoldableOperands for a description of the 333 // transformation we are doing here. 334 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) { 335 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) { 336 if (unsigned SFO = getSelectFoldableOperands(TVI)) { 337 unsigned OpToFold = 0; 338 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 339 OpToFold = 1; 340 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 341 OpToFold = 2; 342 } 343 344 if (OpToFold) { 345 APInt CI = getSelectFoldableConstant(TVI); 346 Value *OOp = TVI->getOperand(2-OpToFold); 347 // Avoid creating select between 2 constants unless it's selecting 348 // between 0, 1 and -1. 349 const APInt *OOpC; 350 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 351 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) { 352 Value *C = ConstantInt::get(OOp->getType(), CI); 353 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C); 354 NewSel->takeName(TVI); 355 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(), 356 FalseVal, NewSel); 357 BO->copyIRFlags(TVI); 358 return BO; 359 } 360 } 361 } 362 } 363 } 364 365 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) { 366 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) { 367 if (unsigned SFO = getSelectFoldableOperands(FVI)) { 368 unsigned OpToFold = 0; 369 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 370 OpToFold = 1; 371 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 372 OpToFold = 2; 373 } 374 375 if (OpToFold) { 376 APInt CI = getSelectFoldableConstant(FVI); 377 Value *OOp = FVI->getOperand(2-OpToFold); 378 // Avoid creating select between 2 constants unless it's selecting 379 // between 0, 1 and -1. 380 const APInt *OOpC; 381 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 382 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) { 383 Value *C = ConstantInt::get(OOp->getType(), CI); 384 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp); 385 NewSel->takeName(FVI); 386 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(), 387 TrueVal, NewSel); 388 BO->copyIRFlags(FVI); 389 return BO; 390 } 391 } 392 } 393 } 394 } 395 396 return nullptr; 397 } 398 399 /// We want to turn: 400 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) 401 /// into: 402 /// (or (shl (and X, C1), C3), Y) 403 /// iff: 404 /// C1 and C2 are both powers of 2 405 /// where: 406 /// C3 = Log(C2) - Log(C1) 407 /// 408 /// This transform handles cases where: 409 /// 1. The icmp predicate is inverted 410 /// 2. The select operands are reversed 411 /// 3. The magnitude of C2 and C1 are flipped 412 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal, 413 Value *FalseVal, 414 InstCombiner::BuilderTy &Builder) { 415 // Only handle integer compares. Also, if this is a vector select, we need a 416 // vector compare. 417 if (!TrueVal->getType()->isIntOrIntVectorTy() || 418 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy()) 419 return nullptr; 420 421 Value *CmpLHS = IC->getOperand(0); 422 Value *CmpRHS = IC->getOperand(1); 423 424 Value *V; 425 unsigned C1Log; 426 bool IsEqualZero; 427 bool NeedAnd = false; 428 if (IC->isEquality()) { 429 if (!match(CmpRHS, m_Zero())) 430 return nullptr; 431 432 const APInt *C1; 433 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1)))) 434 return nullptr; 435 436 V = CmpLHS; 437 C1Log = C1->logBase2(); 438 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ; 439 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT || 440 IC->getPredicate() == ICmpInst::ICMP_SGT) { 441 // We also need to recognize (icmp slt (trunc (X)), 0) and 442 // (icmp sgt (trunc (X)), -1). 443 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT; 444 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) || 445 (!IsEqualZero && !match(CmpRHS, m_Zero()))) 446 return nullptr; 447 448 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V))))) 449 return nullptr; 450 451 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1; 452 NeedAnd = true; 453 } else { 454 return nullptr; 455 } 456 457 const APInt *C2; 458 bool OrOnTrueVal = false; 459 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2))); 460 if (!OrOnFalseVal) 461 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2))); 462 463 if (!OrOnFalseVal && !OrOnTrueVal) 464 return nullptr; 465 466 Value *Y = OrOnFalseVal ? TrueVal : FalseVal; 467 468 unsigned C2Log = C2->logBase2(); 469 470 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal); 471 bool NeedShift = C1Log != C2Log; 472 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() != 473 V->getType()->getScalarSizeInBits(); 474 475 // Make sure we don't create more instructions than we save. 476 Value *Or = OrOnFalseVal ? FalseVal : TrueVal; 477 if ((NeedShift + NeedXor + NeedZExtTrunc) > 478 (IC->hasOneUse() + Or->hasOneUse())) 479 return nullptr; 480 481 if (NeedAnd) { 482 // Insert the AND instruction on the input to the truncate. 483 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log); 484 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1)); 485 } 486 487 if (C2Log > C1Log) { 488 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 489 V = Builder.CreateShl(V, C2Log - C1Log); 490 } else if (C1Log > C2Log) { 491 V = Builder.CreateLShr(V, C1Log - C2Log); 492 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 493 } else 494 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 495 496 if (NeedXor) 497 V = Builder.CreateXor(V, *C2); 498 499 return Builder.CreateOr(V, Y); 500 } 501 502 /// Transform patterns such as: (a > b) ? a - b : 0 503 /// into: ((a > b) ? a : b) - b) 504 /// This produces a canonical max pattern that is more easily recognized by the 505 /// backend and converted into saturated subtraction instructions if those 506 /// exist. 507 /// There are 8 commuted/swapped variants of this pattern. 508 /// TODO: Also support a - UMIN(a,b) patterns. 509 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI, 510 const Value *TrueVal, 511 const Value *FalseVal, 512 InstCombiner::BuilderTy &Builder) { 513 ICmpInst::Predicate Pred = ICI->getPredicate(); 514 if (!ICmpInst::isUnsigned(Pred)) 515 return nullptr; 516 517 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0 518 if (match(TrueVal, m_Zero())) { 519 Pred = ICmpInst::getInversePredicate(Pred); 520 std::swap(TrueVal, FalseVal); 521 } 522 if (!match(FalseVal, m_Zero())) 523 return nullptr; 524 525 Value *A = ICI->getOperand(0); 526 Value *B = ICI->getOperand(1); 527 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) { 528 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0 529 std::swap(A, B); 530 Pred = ICmpInst::getSwappedPredicate(Pred); 531 } 532 533 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) && 534 "Unexpected isUnsigned predicate!"); 535 536 // Account for swapped form of subtraction: ((a > b) ? b - a : 0). 537 bool IsNegative = false; 538 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A)))) 539 IsNegative = true; 540 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B)))) 541 return nullptr; 542 543 // If sub is used anywhere else, we wouldn't be able to eliminate it 544 // afterwards. 545 if (!TrueVal->hasOneUse()) 546 return nullptr; 547 548 // All checks passed, convert to canonical unsigned saturated subtraction 549 // form: sub(max()). 550 // (a > b) ? a - b : 0 -> ((a > b) ? a : b) - b) 551 Value *Max = Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B); 552 return IsNegative ? Builder.CreateSub(B, Max) : Builder.CreateSub(Max, B); 553 } 554 555 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single 556 /// call to cttz/ctlz with flag 'is_zero_undef' cleared. 557 /// 558 /// For example, we can fold the following code sequence: 559 /// \code 560 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true) 561 /// %1 = icmp ne i32 %x, 0 562 /// %2 = select i1 %1, i32 %0, i32 32 563 /// \code 564 /// 565 /// into: 566 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false) 567 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal, 568 InstCombiner::BuilderTy &Builder) { 569 ICmpInst::Predicate Pred = ICI->getPredicate(); 570 Value *CmpLHS = ICI->getOperand(0); 571 Value *CmpRHS = ICI->getOperand(1); 572 573 // Check if the condition value compares a value for equality against zero. 574 if (!ICI->isEquality() || !match(CmpRHS, m_Zero())) 575 return nullptr; 576 577 Value *Count = FalseVal; 578 Value *ValueOnZero = TrueVal; 579 if (Pred == ICmpInst::ICMP_NE) 580 std::swap(Count, ValueOnZero); 581 582 // Skip zero extend/truncate. 583 Value *V = nullptr; 584 if (match(Count, m_ZExt(m_Value(V))) || 585 match(Count, m_Trunc(m_Value(V)))) 586 Count = V; 587 588 // Check if the value propagated on zero is a constant number equal to the 589 // sizeof in bits of 'Count'. 590 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits(); 591 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits))) 592 return nullptr; 593 594 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the 595 // input to the cttz/ctlz is used as LHS for the compare instruction. 596 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) || 597 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) { 598 IntrinsicInst *II = cast<IntrinsicInst>(Count); 599 // Explicitly clear the 'undef_on_zero' flag. 600 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone()); 601 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext())); 602 Builder.Insert(NewI); 603 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType()); 604 } 605 606 return nullptr; 607 } 608 609 /// Return true if we find and adjust an icmp+select pattern where the compare 610 /// is with a constant that can be incremented or decremented to match the 611 /// minimum or maximum idiom. 612 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) { 613 ICmpInst::Predicate Pred = Cmp.getPredicate(); 614 Value *CmpLHS = Cmp.getOperand(0); 615 Value *CmpRHS = Cmp.getOperand(1); 616 Value *TrueVal = Sel.getTrueValue(); 617 Value *FalseVal = Sel.getFalseValue(); 618 619 // We may move or edit the compare, so make sure the select is the only user. 620 const APInt *CmpC; 621 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC))) 622 return false; 623 624 // These transforms only work for selects of integers or vector selects of 625 // integer vectors. 626 Type *SelTy = Sel.getType(); 627 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType()); 628 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy()) 629 return false; 630 631 Constant *AdjustedRHS; 632 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 633 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1); 634 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 635 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1); 636 else 637 return false; 638 639 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 640 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 641 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 642 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) { 643 ; // Nothing to do here. Values match without any sign/zero extension. 644 } 645 // Types do not match. Instead of calculating this with mixed types, promote 646 // all to the larger type. This enables scalar evolution to analyze this 647 // expression. 648 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) { 649 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy); 650 651 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 652 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 653 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 654 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 655 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) { 656 CmpLHS = TrueVal; 657 AdjustedRHS = SextRHS; 658 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 659 SextRHS == TrueVal) { 660 CmpLHS = FalseVal; 661 AdjustedRHS = SextRHS; 662 } else if (Cmp.isUnsigned()) { 663 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy); 664 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 665 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 666 // zext + signed compare cannot be changed: 667 // 0xff <s 0x00, but 0x00ff >s 0x0000 668 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) { 669 CmpLHS = TrueVal; 670 AdjustedRHS = ZextRHS; 671 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 672 ZextRHS == TrueVal) { 673 CmpLHS = FalseVal; 674 AdjustedRHS = ZextRHS; 675 } else { 676 return false; 677 } 678 } else { 679 return false; 680 } 681 } else { 682 return false; 683 } 684 685 Pred = ICmpInst::getSwappedPredicate(Pred); 686 CmpRHS = AdjustedRHS; 687 std::swap(FalseVal, TrueVal); 688 Cmp.setPredicate(Pred); 689 Cmp.setOperand(0, CmpLHS); 690 Cmp.setOperand(1, CmpRHS); 691 Sel.setOperand(1, TrueVal); 692 Sel.setOperand(2, FalseVal); 693 Sel.swapProfMetadata(); 694 695 // Move the compare instruction right before the select instruction. Otherwise 696 // the sext/zext value may be defined after the compare instruction uses it. 697 Cmp.moveBefore(&Sel); 698 699 return true; 700 } 701 702 /// If this is an integer min/max (icmp + select) with a constant operand, 703 /// create the canonical icmp for the min/max operation and canonicalize the 704 /// constant to the 'false' operand of the select: 705 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2 706 /// Note: if C1 != C2, this will change the icmp constant to the existing 707 /// constant operand of the select. 708 static Instruction * 709 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp, 710 InstCombiner::BuilderTy &Builder) { 711 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1))) 712 return nullptr; 713 714 // Canonicalize the compare predicate based on whether we have min or max. 715 Value *LHS, *RHS; 716 ICmpInst::Predicate NewPred; 717 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS); 718 switch (SPR.Flavor) { 719 case SPF_SMIN: NewPred = ICmpInst::ICMP_SLT; break; 720 case SPF_UMIN: NewPred = ICmpInst::ICMP_ULT; break; 721 case SPF_SMAX: NewPred = ICmpInst::ICMP_SGT; break; 722 case SPF_UMAX: NewPred = ICmpInst::ICMP_UGT; break; 723 default: return nullptr; 724 } 725 726 // Is this already canonical? 727 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS && 728 Cmp.getPredicate() == NewPred) 729 return nullptr; 730 731 // Create the canonical compare and plug it into the select. 732 Sel.setCondition(Builder.CreateICmp(NewPred, LHS, RHS)); 733 734 // If the select operands did not change, we're done. 735 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS) 736 return &Sel; 737 738 // If we are swapping the select operands, swap the metadata too. 739 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS && 740 "Unexpected results from matchSelectPattern"); 741 Sel.setTrueValue(LHS); 742 Sel.setFalseValue(RHS); 743 Sel.swapProfMetadata(); 744 return &Sel; 745 } 746 747 /// Visit a SelectInst that has an ICmpInst as its first operand. 748 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI, 749 ICmpInst *ICI) { 750 Value *TrueVal = SI.getTrueValue(); 751 Value *FalseVal = SI.getFalseValue(); 752 753 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder)) 754 return NewSel; 755 756 bool Changed = adjustMinMax(SI, *ICI); 757 758 ICmpInst::Predicate Pred = ICI->getPredicate(); 759 Value *CmpLHS = ICI->getOperand(0); 760 Value *CmpRHS = ICI->getOperand(1); 761 762 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1 763 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1 764 // FIXME: Type and constness constraints could be lifted, but we have to 765 // watch code size carefully. We should consider xor instead of 766 // sub/add when we decide to do that. 767 // TODO: Merge this with foldSelectICmpAnd somehow. 768 if (CmpLHS->getType()->isIntOrIntVectorTy() && 769 CmpLHS->getType() == TrueVal->getType()) { 770 const APInt *C1, *C2; 771 if (match(TrueVal, m_APInt(C1)) && match(FalseVal, m_APInt(C2))) { 772 ICmpInst::Predicate Pred = ICI->getPredicate(); 773 Value *X; 774 APInt Mask; 775 if (decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask, false)) { 776 if (Mask.isSignMask()) { 777 assert(X == CmpLHS && "Expected to use the compare input directly"); 778 assert(ICmpInst::isEquality(Pred) && "Expected equality predicate"); 779 780 if (Pred == ICmpInst::ICMP_NE) 781 std::swap(C1, C2); 782 783 // This shift results in either -1 or 0. 784 Value *AShr = Builder.CreateAShr(X, Mask.getBitWidth() - 1); 785 786 // Check if we can express the operation with a single or. 787 if (C2->isAllOnesValue()) 788 return replaceInstUsesWith(SI, Builder.CreateOr(AShr, *C1)); 789 790 Value *And = Builder.CreateAnd(AShr, *C2 - *C1); 791 return replaceInstUsesWith(SI, Builder.CreateAdd(And, 792 ConstantInt::get(And->getType(), *C1))); 793 } 794 } 795 } 796 } 797 798 { 799 const APInt *TrueValC, *FalseValC; 800 if (match(TrueVal, m_APInt(TrueValC)) && 801 match(FalseVal, m_APInt(FalseValC))) 802 if (Value *V = foldSelectICmpAnd(SI.getType(), ICI, *TrueValC, 803 *FalseValC, Builder)) 804 return replaceInstUsesWith(SI, V); 805 } 806 807 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 808 809 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 810 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 811 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 812 SI.setOperand(1, CmpRHS); 813 Changed = true; 814 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 815 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 816 SI.setOperand(2, CmpRHS); 817 Changed = true; 818 } 819 } 820 821 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring 822 // decomposeBitTestICmp() might help. 823 { 824 unsigned BitWidth = 825 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType()); 826 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth); 827 Value *X; 828 const APInt *Y, *C; 829 bool TrueWhenUnset; 830 bool IsBitTest = false; 831 if (ICmpInst::isEquality(Pred) && 832 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) && 833 match(CmpRHS, m_Zero())) { 834 IsBitTest = true; 835 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ; 836 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) { 837 X = CmpLHS; 838 Y = &MinSignedValue; 839 IsBitTest = true; 840 TrueWhenUnset = false; 841 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) { 842 X = CmpLHS; 843 Y = &MinSignedValue; 844 IsBitTest = true; 845 TrueWhenUnset = true; 846 } 847 if (IsBitTest) { 848 Value *V = nullptr; 849 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y 850 if (TrueWhenUnset && TrueVal == X && 851 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 852 V = Builder.CreateAnd(X, ~(*Y)); 853 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y 854 else if (!TrueWhenUnset && FalseVal == X && 855 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 856 V = Builder.CreateAnd(X, ~(*Y)); 857 // (X & Y) == 0 ? X ^ Y : X --> X | Y 858 else if (TrueWhenUnset && FalseVal == X && 859 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 860 V = Builder.CreateOr(X, *Y); 861 // (X & Y) != 0 ? X : X ^ Y --> X | Y 862 else if (!TrueWhenUnset && TrueVal == X && 863 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 864 V = Builder.CreateOr(X, *Y); 865 866 if (V) 867 return replaceInstUsesWith(SI, V); 868 } 869 } 870 871 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder)) 872 return replaceInstUsesWith(SI, V); 873 874 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder)) 875 return replaceInstUsesWith(SI, V); 876 877 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder)) 878 return replaceInstUsesWith(SI, V); 879 880 return Changed ? &SI : nullptr; 881 } 882 883 /// SI is a select whose condition is a PHI node (but the two may be in 884 /// different blocks). See if the true/false values (V) are live in all of the 885 /// predecessor blocks of the PHI. For example, cases like this can't be mapped: 886 /// 887 /// X = phi [ C1, BB1], [C2, BB2] 888 /// Y = add 889 /// Z = select X, Y, 0 890 /// 891 /// because Y is not live in BB1/BB2. 892 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V, 893 const SelectInst &SI) { 894 // If the value is a non-instruction value like a constant or argument, it 895 // can always be mapped. 896 const Instruction *I = dyn_cast<Instruction>(V); 897 if (!I) return true; 898 899 // If V is a PHI node defined in the same block as the condition PHI, we can 900 // map the arguments. 901 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 902 903 if (const PHINode *VP = dyn_cast<PHINode>(I)) 904 if (VP->getParent() == CondPHI->getParent()) 905 return true; 906 907 // Otherwise, if the PHI and select are defined in the same block and if V is 908 // defined in a different block, then we can transform it. 909 if (SI.getParent() == CondPHI->getParent() && 910 I->getParent() != CondPHI->getParent()) 911 return true; 912 913 // Otherwise we have a 'hard' case and we can't tell without doing more 914 // detailed dominator based analysis, punt. 915 return false; 916 } 917 918 /// We have an SPF (e.g. a min or max) of an SPF of the form: 919 /// SPF2(SPF1(A, B), C) 920 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner, 921 SelectPatternFlavor SPF1, 922 Value *A, Value *B, 923 Instruction &Outer, 924 SelectPatternFlavor SPF2, Value *C) { 925 if (Outer.getType() != Inner->getType()) 926 return nullptr; 927 928 if (C == A || C == B) { 929 // MAX(MAX(A, B), B) -> MAX(A, B) 930 // MIN(MIN(a, b), a) -> MIN(a, b) 931 if (SPF1 == SPF2) 932 return replaceInstUsesWith(Outer, Inner); 933 934 // MAX(MIN(a, b), a) -> a 935 // MIN(MAX(a, b), a) -> a 936 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 937 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 938 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 939 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 940 return replaceInstUsesWith(Outer, C); 941 } 942 943 if (SPF1 == SPF2) { 944 const APInt *CB, *CC; 945 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) { 946 // MIN(MIN(A, 23), 97) -> MIN(A, 23) 947 // MAX(MAX(A, 97), 23) -> MAX(A, 97) 948 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) || 949 (SPF1 == SPF_SMIN && CB->sle(*CC)) || 950 (SPF1 == SPF_UMAX && CB->uge(*CC)) || 951 (SPF1 == SPF_SMAX && CB->sge(*CC))) 952 return replaceInstUsesWith(Outer, Inner); 953 954 // MIN(MIN(A, 97), 23) -> MIN(A, 23) 955 // MAX(MAX(A, 23), 97) -> MAX(A, 97) 956 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) || 957 (SPF1 == SPF_SMIN && CB->sgt(*CC)) || 958 (SPF1 == SPF_UMAX && CB->ult(*CC)) || 959 (SPF1 == SPF_SMAX && CB->slt(*CC))) { 960 Outer.replaceUsesOfWith(Inner, A); 961 return &Outer; 962 } 963 } 964 } 965 966 // ABS(ABS(X)) -> ABS(X) 967 // NABS(NABS(X)) -> NABS(X) 968 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) { 969 return replaceInstUsesWith(Outer, Inner); 970 } 971 972 // ABS(NABS(X)) -> ABS(X) 973 // NABS(ABS(X)) -> NABS(X) 974 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) || 975 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) { 976 SelectInst *SI = cast<SelectInst>(Inner); 977 Value *NewSI = 978 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(), 979 SI->getTrueValue(), SI->getName(), SI); 980 return replaceInstUsesWith(Outer, NewSI); 981 } 982 983 auto IsFreeOrProfitableToInvert = 984 [&](Value *V, Value *&NotV, bool &ElidesXor) { 985 if (match(V, m_Not(m_Value(NotV)))) { 986 // If V has at most 2 uses then we can get rid of the xor operation 987 // entirely. 988 ElidesXor |= !V->hasNUsesOrMore(3); 989 return true; 990 } 991 992 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) { 993 NotV = nullptr; 994 return true; 995 } 996 997 return false; 998 }; 999 1000 Value *NotA, *NotB, *NotC; 1001 bool ElidesXor = false; 1002 1003 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C) 1004 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C) 1005 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C) 1006 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C) 1007 // 1008 // This transform is performance neutral if we can elide at least one xor from 1009 // the set of three operands, since we'll be tacking on an xor at the very 1010 // end. 1011 if (SelectPatternResult::isMinOrMax(SPF1) && 1012 SelectPatternResult::isMinOrMax(SPF2) && 1013 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) && 1014 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) && 1015 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) { 1016 if (!NotA) 1017 NotA = Builder.CreateNot(A); 1018 if (!NotB) 1019 NotB = Builder.CreateNot(B); 1020 if (!NotC) 1021 NotC = Builder.CreateNot(C); 1022 1023 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA, 1024 NotB); 1025 Value *NewOuter = Builder.CreateNot( 1026 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC)); 1027 return replaceInstUsesWith(Outer, NewOuter); 1028 } 1029 1030 return nullptr; 1031 } 1032 1033 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))). 1034 /// This is even legal for FP. 1035 static Instruction *foldAddSubSelect(SelectInst &SI, 1036 InstCombiner::BuilderTy &Builder) { 1037 Value *CondVal = SI.getCondition(); 1038 Value *TrueVal = SI.getTrueValue(); 1039 Value *FalseVal = SI.getFalseValue(); 1040 auto *TI = dyn_cast<Instruction>(TrueVal); 1041 auto *FI = dyn_cast<Instruction>(FalseVal); 1042 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse()) 1043 return nullptr; 1044 1045 Instruction *AddOp = nullptr, *SubOp = nullptr; 1046 if ((TI->getOpcode() == Instruction::Sub && 1047 FI->getOpcode() == Instruction::Add) || 1048 (TI->getOpcode() == Instruction::FSub && 1049 FI->getOpcode() == Instruction::FAdd)) { 1050 AddOp = FI; 1051 SubOp = TI; 1052 } else if ((FI->getOpcode() == Instruction::Sub && 1053 TI->getOpcode() == Instruction::Add) || 1054 (FI->getOpcode() == Instruction::FSub && 1055 TI->getOpcode() == Instruction::FAdd)) { 1056 AddOp = TI; 1057 SubOp = FI; 1058 } 1059 1060 if (AddOp) { 1061 Value *OtherAddOp = nullptr; 1062 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 1063 OtherAddOp = AddOp->getOperand(1); 1064 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 1065 OtherAddOp = AddOp->getOperand(0); 1066 } 1067 1068 if (OtherAddOp) { 1069 // So at this point we know we have (Y -> OtherAddOp): 1070 // select C, (add X, Y), (sub X, Z) 1071 Value *NegVal; // Compute -Z 1072 if (SI.getType()->isFPOrFPVectorTy()) { 1073 NegVal = Builder.CreateFNeg(SubOp->getOperand(1)); 1074 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 1075 FastMathFlags Flags = AddOp->getFastMathFlags(); 1076 Flags &= SubOp->getFastMathFlags(); 1077 NegInst->setFastMathFlags(Flags); 1078 } 1079 } else { 1080 NegVal = Builder.CreateNeg(SubOp->getOperand(1)); 1081 } 1082 1083 Value *NewTrueOp = OtherAddOp; 1084 Value *NewFalseOp = NegVal; 1085 if (AddOp != TI) 1086 std::swap(NewTrueOp, NewFalseOp); 1087 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp, 1088 SI.getName() + ".p", &SI); 1089 1090 if (SI.getType()->isFPOrFPVectorTy()) { 1091 Instruction *RI = 1092 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 1093 1094 FastMathFlags Flags = AddOp->getFastMathFlags(); 1095 Flags &= SubOp->getFastMathFlags(); 1096 RI->setFastMathFlags(Flags); 1097 return RI; 1098 } else 1099 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 1100 } 1101 } 1102 return nullptr; 1103 } 1104 1105 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) { 1106 Instruction *ExtInst; 1107 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) && 1108 !match(Sel.getFalseValue(), m_Instruction(ExtInst))) 1109 return nullptr; 1110 1111 auto ExtOpcode = ExtInst->getOpcode(); 1112 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt) 1113 return nullptr; 1114 1115 // TODO: Handle larger types? That requires adjusting FoldOpIntoSelect too. 1116 Value *X = ExtInst->getOperand(0); 1117 Type *SmallType = X->getType(); 1118 if (!SmallType->isIntOrIntVectorTy(1)) 1119 return nullptr; 1120 1121 Constant *C; 1122 if (!match(Sel.getTrueValue(), m_Constant(C)) && 1123 !match(Sel.getFalseValue(), m_Constant(C))) 1124 return nullptr; 1125 1126 // If the constant is the same after truncation to the smaller type and 1127 // extension to the original type, we can narrow the select. 1128 Value *Cond = Sel.getCondition(); 1129 Type *SelType = Sel.getType(); 1130 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType); 1131 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType); 1132 if (ExtC == C) { 1133 Value *TruncCVal = cast<Value>(TruncC); 1134 if (ExtInst == Sel.getFalseValue()) 1135 std::swap(X, TruncCVal); 1136 1137 // select Cond, (ext X), C --> ext(select Cond, X, C') 1138 // select Cond, C, (ext X) --> ext(select Cond, C', X) 1139 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel); 1140 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType); 1141 } 1142 1143 // If one arm of the select is the extend of the condition, replace that arm 1144 // with the extension of the appropriate known bool value. 1145 if (Cond == X) { 1146 if (ExtInst == Sel.getTrueValue()) { 1147 // select X, (sext X), C --> select X, -1, C 1148 // select X, (zext X), C --> select X, 1, C 1149 Constant *One = ConstantInt::getTrue(SmallType); 1150 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType); 1151 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel); 1152 } else { 1153 // select X, C, (sext X) --> select X, C, 0 1154 // select X, C, (zext X) --> select X, C, 0 1155 Constant *Zero = ConstantInt::getNullValue(SelType); 1156 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel); 1157 } 1158 } 1159 1160 return nullptr; 1161 } 1162 1163 /// Try to transform a vector select with a constant condition vector into a 1164 /// shuffle for easier combining with other shuffles and insert/extract. 1165 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) { 1166 Value *CondVal = SI.getCondition(); 1167 Constant *CondC; 1168 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC))) 1169 return nullptr; 1170 1171 unsigned NumElts = CondVal->getType()->getVectorNumElements(); 1172 SmallVector<Constant *, 16> Mask; 1173 Mask.reserve(NumElts); 1174 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext()); 1175 for (unsigned i = 0; i != NumElts; ++i) { 1176 Constant *Elt = CondC->getAggregateElement(i); 1177 if (!Elt) 1178 return nullptr; 1179 1180 if (Elt->isOneValue()) { 1181 // If the select condition element is true, choose from the 1st vector. 1182 Mask.push_back(ConstantInt::get(Int32Ty, i)); 1183 } else if (Elt->isNullValue()) { 1184 // If the select condition element is false, choose from the 2nd vector. 1185 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts)); 1186 } else if (isa<UndefValue>(Elt)) { 1187 // Undef in a select condition (choose one of the operands) does not mean 1188 // the same thing as undef in a shuffle mask (any value is acceptable), so 1189 // give up. 1190 return nullptr; 1191 } else { 1192 // Bail out on a constant expression. 1193 return nullptr; 1194 } 1195 } 1196 1197 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), 1198 ConstantVector::get(Mask)); 1199 } 1200 1201 /// Reuse bitcasted operands between a compare and select: 1202 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 1203 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D)) 1204 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel, 1205 InstCombiner::BuilderTy &Builder) { 1206 Value *Cond = Sel.getCondition(); 1207 Value *TVal = Sel.getTrueValue(); 1208 Value *FVal = Sel.getFalseValue(); 1209 1210 CmpInst::Predicate Pred; 1211 Value *A, *B; 1212 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B)))) 1213 return nullptr; 1214 1215 // The select condition is a compare instruction. If the select's true/false 1216 // values are already the same as the compare operands, there's nothing to do. 1217 if (TVal == A || TVal == B || FVal == A || FVal == B) 1218 return nullptr; 1219 1220 Value *C, *D; 1221 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D)))) 1222 return nullptr; 1223 1224 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc) 1225 Value *TSrc, *FSrc; 1226 if (!match(TVal, m_BitCast(m_Value(TSrc))) || 1227 !match(FVal, m_BitCast(m_Value(FSrc)))) 1228 return nullptr; 1229 1230 // If the select true/false values are *different bitcasts* of the same source 1231 // operands, make the select operands the same as the compare operands and 1232 // cast the result. This is the canonical select form for min/max. 1233 Value *NewSel; 1234 if (TSrc == C && FSrc == D) { 1235 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 1236 // bitcast (select (cmp A, B), A, B) 1237 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel); 1238 } else if (TSrc == D && FSrc == C) { 1239 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) --> 1240 // bitcast (select (cmp A, B), B, A) 1241 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel); 1242 } else { 1243 return nullptr; 1244 } 1245 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType()); 1246 } 1247 1248 /// Try to eliminate select instructions that test the returned flag of cmpxchg 1249 /// instructions. 1250 /// 1251 /// If a select instruction tests the returned flag of a cmpxchg instruction and 1252 /// selects between the returned value of the cmpxchg instruction its compare 1253 /// operand, the result of the select will always be equal to its false value. 1254 /// For example: 1255 /// 1256 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 1257 /// %1 = extractvalue { i64, i1 } %0, 1 1258 /// %2 = extractvalue { i64, i1 } %0, 0 1259 /// %3 = select i1 %1, i64 %compare, i64 %2 1260 /// ret i64 %3 1261 /// 1262 /// The returned value of the cmpxchg instruction (%2) is the original value 1263 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2 1264 /// must have been equal to %compare. Thus, the result of the select is always 1265 /// equal to %2, and the code can be simplified to: 1266 /// 1267 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 1268 /// %1 = extractvalue { i64, i1 } %0, 0 1269 /// ret i64 %1 1270 /// 1271 static Instruction *foldSelectCmpXchg(SelectInst &SI) { 1272 // A helper that determines if V is an extractvalue instruction whose 1273 // aggregate operand is a cmpxchg instruction and whose single index is equal 1274 // to I. If such conditions are true, the helper returns the cmpxchg 1275 // instruction; otherwise, a nullptr is returned. 1276 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * { 1277 auto *Extract = dyn_cast<ExtractValueInst>(V); 1278 if (!Extract) 1279 return nullptr; 1280 if (Extract->getIndices()[0] != I) 1281 return nullptr; 1282 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand()); 1283 }; 1284 1285 // If the select has a single user, and this user is a select instruction that 1286 // we can simplify, skip the cmpxchg simplification for now. 1287 if (SI.hasOneUse()) 1288 if (auto *Select = dyn_cast<SelectInst>(SI.user_back())) 1289 if (Select->getCondition() == SI.getCondition()) 1290 if (Select->getFalseValue() == SI.getTrueValue() || 1291 Select->getTrueValue() == SI.getFalseValue()) 1292 return nullptr; 1293 1294 // Ensure the select condition is the returned flag of a cmpxchg instruction. 1295 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1); 1296 if (!CmpXchg) 1297 return nullptr; 1298 1299 // Check the true value case: The true value of the select is the returned 1300 // value of the same cmpxchg used by the condition, and the false value is the 1301 // cmpxchg instruction's compare operand. 1302 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0)) 1303 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) { 1304 SI.setTrueValue(SI.getFalseValue()); 1305 return &SI; 1306 } 1307 1308 // Check the false value case: The false value of the select is the returned 1309 // value of the same cmpxchg used by the condition, and the true value is the 1310 // cmpxchg instruction's compare operand. 1311 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0)) 1312 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) { 1313 SI.setTrueValue(SI.getFalseValue()); 1314 return &SI; 1315 } 1316 1317 return nullptr; 1318 } 1319 1320 /// Reduce a sequence of min/max with a common operand. 1321 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS, 1322 Value *RHS, 1323 InstCombiner::BuilderTy &Builder) { 1324 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max"); 1325 // TODO: Allow FP min/max with nnan/nsz. 1326 if (!LHS->getType()->isIntOrIntVectorTy()) 1327 return nullptr; 1328 1329 // Match 3 of the same min/max ops. Example: umin(umin(), umin()). 1330 Value *A, *B, *C, *D; 1331 SelectPatternResult L = matchSelectPattern(LHS, A, B); 1332 SelectPatternResult R = matchSelectPattern(RHS, C, D); 1333 if (SPF != L.Flavor || L.Flavor != R.Flavor) 1334 return nullptr; 1335 1336 // Look for a common operand. The use checks are different than usual because 1337 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by 1338 // the select. 1339 Value *MinMaxOp = nullptr; 1340 Value *ThirdOp = nullptr; 1341 if (LHS->getNumUses() <= 2 && RHS->getNumUses() > 2) { 1342 // If the LHS is only used in this chain and the RHS is used outside of it, 1343 // reuse the RHS min/max because that will eliminate the LHS. 1344 if (D == A || C == A) { 1345 // min(min(a, b), min(c, a)) --> min(min(c, a), b) 1346 // min(min(a, b), min(a, d)) --> min(min(a, d), b) 1347 MinMaxOp = RHS; 1348 ThirdOp = B; 1349 } else if (D == B || C == B) { 1350 // min(min(a, b), min(c, b)) --> min(min(c, b), a) 1351 // min(min(a, b), min(b, d)) --> min(min(b, d), a) 1352 MinMaxOp = RHS; 1353 ThirdOp = A; 1354 } 1355 } else if (RHS->getNumUses() <= 2) { 1356 // Reuse the LHS. This will eliminate the RHS. 1357 if (D == A || D == B) { 1358 // min(min(a, b), min(c, a)) --> min(min(a, b), c) 1359 // min(min(a, b), min(c, b)) --> min(min(a, b), c) 1360 MinMaxOp = LHS; 1361 ThirdOp = C; 1362 } else if (C == A || C == B) { 1363 // min(min(a, b), min(b, d)) --> min(min(a, b), d) 1364 // min(min(a, b), min(c, b)) --> min(min(a, b), d) 1365 MinMaxOp = LHS; 1366 ThirdOp = D; 1367 } 1368 } 1369 if (!MinMaxOp || !ThirdOp) 1370 return nullptr; 1371 1372 CmpInst::Predicate P = getMinMaxPred(SPF); 1373 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp); 1374 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp); 1375 } 1376 1377 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 1378 Value *CondVal = SI.getCondition(); 1379 Value *TrueVal = SI.getTrueValue(); 1380 Value *FalseVal = SI.getFalseValue(); 1381 Type *SelType = SI.getType(); 1382 1383 // FIXME: Remove this workaround when freeze related patches are done. 1384 // For select with undef operand which feeds into an equality comparison, 1385 // don't simplify it so loop unswitch can know the equality comparison 1386 // may have an undef operand. This is a workaround for PR31652 caused by 1387 // descrepancy about branch on undef between LoopUnswitch and GVN. 1388 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) { 1389 if (llvm::any_of(SI.users(), [&](User *U) { 1390 ICmpInst *CI = dyn_cast<ICmpInst>(U); 1391 if (CI && CI->isEquality()) 1392 return true; 1393 return false; 1394 })) { 1395 return nullptr; 1396 } 1397 } 1398 1399 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, 1400 SQ.getWithInstruction(&SI))) 1401 return replaceInstUsesWith(SI, V); 1402 1403 if (Instruction *I = canonicalizeSelectToShuffle(SI)) 1404 return I; 1405 1406 // Canonicalize a one-use integer compare with a non-canonical predicate by 1407 // inverting the predicate and swapping the select operands. This matches a 1408 // compare canonicalization for conditional branches. 1409 // TODO: Should we do the same for FP compares? 1410 CmpInst::Predicate Pred; 1411 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) && 1412 !isCanonicalPredicate(Pred)) { 1413 // Swap true/false values and condition. 1414 CmpInst *Cond = cast<CmpInst>(CondVal); 1415 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 1416 SI.setOperand(1, FalseVal); 1417 SI.setOperand(2, TrueVal); 1418 SI.swapProfMetadata(); 1419 Worklist.Add(Cond); 1420 return &SI; 1421 } 1422 1423 if (SelType->isIntOrIntVectorTy(1) && 1424 TrueVal->getType() == CondVal->getType()) { 1425 if (match(TrueVal, m_One())) { 1426 // Change: A = select B, true, C --> A = or B, C 1427 return BinaryOperator::CreateOr(CondVal, FalseVal); 1428 } 1429 if (match(TrueVal, m_Zero())) { 1430 // Change: A = select B, false, C --> A = and !B, C 1431 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1432 return BinaryOperator::CreateAnd(NotCond, FalseVal); 1433 } 1434 if (match(FalseVal, m_Zero())) { 1435 // Change: A = select B, C, false --> A = and B, C 1436 return BinaryOperator::CreateAnd(CondVal, TrueVal); 1437 } 1438 if (match(FalseVal, m_One())) { 1439 // Change: A = select B, C, true --> A = or !B, C 1440 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1441 return BinaryOperator::CreateOr(NotCond, TrueVal); 1442 } 1443 1444 // select a, a, b -> a | b 1445 // select a, b, a -> a & b 1446 if (CondVal == TrueVal) 1447 return BinaryOperator::CreateOr(CondVal, FalseVal); 1448 if (CondVal == FalseVal) 1449 return BinaryOperator::CreateAnd(CondVal, TrueVal); 1450 1451 // select a, ~a, b -> (~a) & b 1452 // select a, b, ~a -> (~a) | b 1453 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 1454 return BinaryOperator::CreateAnd(TrueVal, FalseVal); 1455 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 1456 return BinaryOperator::CreateOr(TrueVal, FalseVal); 1457 } 1458 1459 // Selecting between two integer or vector splat integer constants? 1460 // 1461 // Note that we don't handle a scalar select of vectors: 1462 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0> 1463 // because that may need 3 instructions to splat the condition value: 1464 // extend, insertelement, shufflevector. 1465 if (SelType->isIntOrIntVectorTy() && 1466 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) { 1467 // select C, 1, 0 -> zext C to int 1468 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero())) 1469 return new ZExtInst(CondVal, SelType); 1470 1471 // select C, -1, 0 -> sext C to int 1472 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero())) 1473 return new SExtInst(CondVal, SelType); 1474 1475 // select C, 0, 1 -> zext !C to int 1476 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) { 1477 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1478 return new ZExtInst(NotCond, SelType); 1479 } 1480 1481 // select C, 0, -1 -> sext !C to int 1482 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) { 1483 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 1484 return new SExtInst(NotCond, SelType); 1485 } 1486 } 1487 1488 // See if we are selecting two values based on a comparison of the two values. 1489 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 1490 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) { 1491 // Transform (X == Y) ? X : Y -> Y 1492 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 1493 // This is not safe in general for floating point: 1494 // consider X== -0, Y== +0. 1495 // It becomes safe if either operand is a nonzero constant. 1496 ConstantFP *CFPt, *CFPf; 1497 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 1498 !CFPt->getValueAPF().isZero()) || 1499 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 1500 !CFPf->getValueAPF().isZero())) 1501 return replaceInstUsesWith(SI, FalseVal); 1502 } 1503 // Transform (X une Y) ? X : Y -> X 1504 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 1505 // This is not safe in general for floating point: 1506 // consider X== -0, Y== +0. 1507 // It becomes safe if either operand is a nonzero constant. 1508 ConstantFP *CFPt, *CFPf; 1509 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 1510 !CFPt->getValueAPF().isZero()) || 1511 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 1512 !CFPf->getValueAPF().isZero())) 1513 return replaceInstUsesWith(SI, TrueVal); 1514 } 1515 1516 // Canonicalize to use ordered comparisons by swapping the select 1517 // operands. 1518 // 1519 // e.g. 1520 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X 1521 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 1522 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 1523 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1524 Builder.setFastMathFlags(FCI->getFastMathFlags()); 1525 Value *NewCond = Builder.CreateFCmp(InvPred, TrueVal, FalseVal, 1526 FCI->getName() + ".inv"); 1527 1528 return SelectInst::Create(NewCond, FalseVal, TrueVal, 1529 SI.getName() + ".p"); 1530 } 1531 1532 // NOTE: if we wanted to, this is where to detect MIN/MAX 1533 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){ 1534 // Transform (X == Y) ? Y : X -> X 1535 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 1536 // This is not safe in general for floating point: 1537 // consider X== -0, Y== +0. 1538 // It becomes safe if either operand is a nonzero constant. 1539 ConstantFP *CFPt, *CFPf; 1540 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 1541 !CFPt->getValueAPF().isZero()) || 1542 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 1543 !CFPf->getValueAPF().isZero())) 1544 return replaceInstUsesWith(SI, FalseVal); 1545 } 1546 // Transform (X une Y) ? Y : X -> Y 1547 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 1548 // This is not safe in general for floating point: 1549 // consider X== -0, Y== +0. 1550 // It becomes safe if either operand is a nonzero constant. 1551 ConstantFP *CFPt, *CFPf; 1552 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 1553 !CFPt->getValueAPF().isZero()) || 1554 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 1555 !CFPf->getValueAPF().isZero())) 1556 return replaceInstUsesWith(SI, TrueVal); 1557 } 1558 1559 // Canonicalize to use ordered comparisons by swapping the select 1560 // operands. 1561 // 1562 // e.g. 1563 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y 1564 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 1565 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 1566 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1567 Builder.setFastMathFlags(FCI->getFastMathFlags()); 1568 Value *NewCond = Builder.CreateFCmp(InvPred, FalseVal, TrueVal, 1569 FCI->getName() + ".inv"); 1570 1571 return SelectInst::Create(NewCond, FalseVal, TrueVal, 1572 SI.getName() + ".p"); 1573 } 1574 1575 // NOTE: if we wanted to, this is where to detect MIN/MAX 1576 } 1577 // NOTE: if we wanted to, this is where to detect ABS 1578 } 1579 1580 // See if we are selecting two values based on a comparison of the two values. 1581 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 1582 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI)) 1583 return Result; 1584 1585 if (Instruction *Add = foldAddSubSelect(SI, Builder)) 1586 return Add; 1587 1588 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 1589 auto *TI = dyn_cast<Instruction>(TrueVal); 1590 auto *FI = dyn_cast<Instruction>(FalseVal); 1591 if (TI && FI && TI->getOpcode() == FI->getOpcode()) 1592 if (Instruction *IV = foldSelectOpOp(SI, TI, FI)) 1593 return IV; 1594 1595 if (Instruction *I = foldSelectExtConst(SI)) 1596 return I; 1597 1598 // See if we can fold the select into one of our operands. 1599 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) { 1600 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal)) 1601 return FoldI; 1602 1603 Value *LHS, *RHS, *LHS2, *RHS2; 1604 Instruction::CastOps CastOp; 1605 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp); 1606 auto SPF = SPR.Flavor; 1607 1608 if (SelectPatternResult::isMinOrMax(SPF)) { 1609 // Canonicalize so that 1610 // - type casts are outside select patterns. 1611 // - float clamp is transformed to min/max pattern 1612 1613 bool IsCastNeeded = LHS->getType() != SelType; 1614 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0); 1615 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1); 1616 if (IsCastNeeded || 1617 (LHS->getType()->isFPOrFPVectorTy() && 1618 ((CmpLHS != LHS && CmpLHS != RHS) || 1619 (CmpRHS != LHS && CmpRHS != RHS)))) { 1620 CmpInst::Predicate Pred = getMinMaxPred(SPF, SPR.Ordered); 1621 1622 Value *Cmp; 1623 if (CmpInst::isIntPredicate(Pred)) { 1624 Cmp = Builder.CreateICmp(Pred, LHS, RHS); 1625 } else { 1626 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 1627 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags(); 1628 Builder.setFastMathFlags(FMF); 1629 Cmp = Builder.CreateFCmp(Pred, LHS, RHS); 1630 } 1631 1632 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI); 1633 if (!IsCastNeeded) 1634 return replaceInstUsesWith(SI, NewSI); 1635 1636 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType); 1637 return replaceInstUsesWith(SI, NewCast); 1638 } 1639 1640 // MAX(~a, ~b) -> ~MIN(a, b) 1641 // MIN(~a, ~b) -> ~MAX(a, b) 1642 Value *A, *B; 1643 if (match(LHS, m_Not(m_Value(A))) && match(RHS, m_Not(m_Value(B))) && 1644 (LHS->getNumUses() <= 2 || RHS->getNumUses() <= 2)) { 1645 CmpInst::Predicate InvertedPred = getInverseMinMaxPred(SPF); 1646 Value *InvertedCmp = Builder.CreateICmp(InvertedPred, A, B); 1647 Value *NewSel = Builder.CreateSelect(InvertedCmp, A, B); 1648 return BinaryOperator::CreateNot(NewSel); 1649 } 1650 1651 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder)) 1652 return I; 1653 } 1654 1655 if (SPF) { 1656 // MAX(MAX(a, b), a) -> MAX(a, b) 1657 // MIN(MIN(a, b), a) -> MIN(a, b) 1658 // MAX(MIN(a, b), a) -> a 1659 // MIN(MAX(a, b), a) -> a 1660 // ABS(ABS(a)) -> ABS(a) 1661 // NABS(NABS(a)) -> NABS(a) 1662 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor) 1663 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 1664 SI, SPF, RHS)) 1665 return R; 1666 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor) 1667 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2, 1668 SI, SPF, LHS)) 1669 return R; 1670 } 1671 1672 // TODO. 1673 // ABS(-X) -> ABS(X) 1674 } 1675 1676 // See if we can fold the select into a phi node if the condition is a select. 1677 if (auto *PN = dyn_cast<PHINode>(SI.getCondition())) 1678 // The true/false values have to be live in the PHI predecessor's blocks. 1679 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 1680 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 1681 if (Instruction *NV = foldOpIntoPhi(SI, PN)) 1682 return NV; 1683 1684 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 1685 if (TrueSI->getCondition()->getType() == CondVal->getType()) { 1686 // select(C, select(C, a, b), c) -> select(C, a, c) 1687 if (TrueSI->getCondition() == CondVal) { 1688 if (SI.getTrueValue() == TrueSI->getTrueValue()) 1689 return nullptr; 1690 SI.setOperand(1, TrueSI->getTrueValue()); 1691 return &SI; 1692 } 1693 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b) 1694 // We choose this as normal form to enable folding on the And and shortening 1695 // paths for the values (this helps GetUnderlyingObjects() for example). 1696 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) { 1697 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition()); 1698 SI.setOperand(0, And); 1699 SI.setOperand(1, TrueSI->getTrueValue()); 1700 return &SI; 1701 } 1702 } 1703 } 1704 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 1705 if (FalseSI->getCondition()->getType() == CondVal->getType()) { 1706 // select(C, a, select(C, b, c)) -> select(C, a, c) 1707 if (FalseSI->getCondition() == CondVal) { 1708 if (SI.getFalseValue() == FalseSI->getFalseValue()) 1709 return nullptr; 1710 SI.setOperand(2, FalseSI->getFalseValue()); 1711 return &SI; 1712 } 1713 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b) 1714 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) { 1715 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition()); 1716 SI.setOperand(0, Or); 1717 SI.setOperand(2, FalseSI->getFalseValue()); 1718 return &SI; 1719 } 1720 } 1721 } 1722 1723 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) { 1724 // The select might be preventing a division by 0. 1725 switch (BO->getOpcode()) { 1726 default: 1727 return true; 1728 case Instruction::SRem: 1729 case Instruction::URem: 1730 case Instruction::SDiv: 1731 case Instruction::UDiv: 1732 return false; 1733 } 1734 }; 1735 1736 // Try to simplify a binop sandwiched between 2 selects with the same 1737 // condition. 1738 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z) 1739 BinaryOperator *TrueBO; 1740 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && 1741 canMergeSelectThroughBinop(TrueBO)) { 1742 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) { 1743 if (TrueBOSI->getCondition() == CondVal) { 1744 TrueBO->setOperand(0, TrueBOSI->getTrueValue()); 1745 Worklist.Add(TrueBO); 1746 return &SI; 1747 } 1748 } 1749 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) { 1750 if (TrueBOSI->getCondition() == CondVal) { 1751 TrueBO->setOperand(1, TrueBOSI->getTrueValue()); 1752 Worklist.Add(TrueBO); 1753 return &SI; 1754 } 1755 } 1756 } 1757 1758 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W)) 1759 BinaryOperator *FalseBO; 1760 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && 1761 canMergeSelectThroughBinop(FalseBO)) { 1762 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) { 1763 if (FalseBOSI->getCondition() == CondVal) { 1764 FalseBO->setOperand(0, FalseBOSI->getFalseValue()); 1765 Worklist.Add(FalseBO); 1766 return &SI; 1767 } 1768 } 1769 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) { 1770 if (FalseBOSI->getCondition() == CondVal) { 1771 FalseBO->setOperand(1, FalseBOSI->getFalseValue()); 1772 Worklist.Add(FalseBO); 1773 return &SI; 1774 } 1775 } 1776 } 1777 1778 if (BinaryOperator::isNot(CondVal)) { 1779 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal)); 1780 SI.setOperand(1, FalseVal); 1781 SI.setOperand(2, TrueVal); 1782 return &SI; 1783 } 1784 1785 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) { 1786 unsigned VWidth = VecTy->getNumElements(); 1787 APInt UndefElts(VWidth, 0); 1788 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1789 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) { 1790 if (V != &SI) 1791 return replaceInstUsesWith(SI, V); 1792 return &SI; 1793 } 1794 } 1795 1796 // See if we can determine the result of this select based on a dominating 1797 // condition. 1798 BasicBlock *Parent = SI.getParent(); 1799 if (BasicBlock *Dom = Parent->getSinglePredecessor()) { 1800 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator()); 1801 if (PBI && PBI->isConditional() && 1802 PBI->getSuccessor(0) != PBI->getSuccessor(1) && 1803 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) { 1804 bool CondIsTrue = PBI->getSuccessor(0) == Parent; 1805 Optional<bool> Implication = isImpliedCondition( 1806 PBI->getCondition(), SI.getCondition(), DL, CondIsTrue); 1807 if (Implication) { 1808 Value *V = *Implication ? TrueVal : FalseVal; 1809 return replaceInstUsesWith(SI, V); 1810 } 1811 } 1812 } 1813 1814 // If we can compute the condition, there's no need for a select. 1815 // Like the above fold, we are attempting to reduce compile-time cost by 1816 // putting this fold here with limitations rather than in InstSimplify. 1817 // The motivation for this call into value tracking is to take advantage of 1818 // the assumption cache, so make sure that is populated. 1819 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) { 1820 KnownBits Known(1); 1821 computeKnownBits(CondVal, Known, 0, &SI); 1822 if (Known.One.isOneValue()) 1823 return replaceInstUsesWith(SI, TrueVal); 1824 if (Known.Zero.isOneValue()) 1825 return replaceInstUsesWith(SI, FalseVal); 1826 } 1827 1828 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder)) 1829 return BitCastSel; 1830 1831 // Simplify selects that test the returned flag of cmpxchg instructions. 1832 if (Instruction *Select = foldSelectCmpXchg(SI)) 1833 return Select; 1834 1835 return nullptr; 1836 } 1837