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