1 //===- InstCombineSelect.cpp ----------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the visitSelect function. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "InstCombineInternal.h" 14 #include "llvm/ADT/APInt.h" 15 #include "llvm/ADT/Optional.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/AssumptionCache.h" 19 #include "llvm/Analysis/CmpInstAnalysis.h" 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/IR/BasicBlock.h" 23 #include "llvm/IR/Constant.h" 24 #include "llvm/IR/Constants.h" 25 #include "llvm/IR/DerivedTypes.h" 26 #include "llvm/IR/IRBuilder.h" 27 #include "llvm/IR/InstrTypes.h" 28 #include "llvm/IR/Instruction.h" 29 #include "llvm/IR/Instructions.h" 30 #include "llvm/IR/IntrinsicInst.h" 31 #include "llvm/IR/Intrinsics.h" 32 #include "llvm/IR/Operator.h" 33 #include "llvm/IR/PatternMatch.h" 34 #include "llvm/IR/Type.h" 35 #include "llvm/IR/User.h" 36 #include "llvm/IR/Value.h" 37 #include "llvm/Support/Casting.h" 38 #include "llvm/Support/ErrorHandling.h" 39 #include "llvm/Support/KnownBits.h" 40 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h" 41 #include <cassert> 42 #include <utility> 43 44 using namespace llvm; 45 using namespace PatternMatch; 46 47 #define DEBUG_TYPE "instcombine" 48 49 static Value *createMinMax(InstCombiner::BuilderTy &Builder, 50 SelectPatternFlavor SPF, Value *A, Value *B) { 51 CmpInst::Predicate Pred = getMinMaxPred(SPF); 52 assert(CmpInst::isIntPredicate(Pred) && "Expected integer predicate"); 53 return Builder.CreateSelect(Builder.CreateICmp(Pred, A, B), A, B); 54 } 55 56 /// Replace a select operand based on an equality comparison with the identity 57 /// constant of a binop. 58 static Instruction *foldSelectBinOpIdentity(SelectInst &Sel, 59 const TargetLibraryInfo &TLI) { 60 // The select condition must be an equality compare with a constant operand. 61 Value *X; 62 Constant *C; 63 CmpInst::Predicate Pred; 64 if (!match(Sel.getCondition(), m_Cmp(Pred, m_Value(X), m_Constant(C)))) 65 return nullptr; 66 67 bool IsEq; 68 if (ICmpInst::isEquality(Pred)) 69 IsEq = Pred == ICmpInst::ICMP_EQ; 70 else if (Pred == FCmpInst::FCMP_OEQ) 71 IsEq = true; 72 else if (Pred == FCmpInst::FCMP_UNE) 73 IsEq = false; 74 else 75 return nullptr; 76 77 // A select operand must be a binop. 78 BinaryOperator *BO; 79 if (!match(Sel.getOperand(IsEq ? 1 : 2), m_BinOp(BO))) 80 return nullptr; 81 82 // The compare constant must be the identity constant for that binop. 83 // If this a floating-point compare with 0.0, any zero constant will do. 84 Type *Ty = BO->getType(); 85 Constant *IdC = ConstantExpr::getBinOpIdentity(BO->getOpcode(), Ty, true); 86 if (IdC != C) { 87 if (!IdC || !CmpInst::isFPPredicate(Pred)) 88 return nullptr; 89 if (!match(IdC, m_AnyZeroFP()) || !match(C, m_AnyZeroFP())) 90 return nullptr; 91 } 92 93 // Last, match the compare variable operand with a binop operand. 94 Value *Y; 95 if (!BO->isCommutative() && !match(BO, m_BinOp(m_Value(Y), m_Specific(X)))) 96 return nullptr; 97 if (!match(BO, m_c_BinOp(m_Value(Y), m_Specific(X)))) 98 return nullptr; 99 100 // +0.0 compares equal to -0.0, and so it does not behave as required for this 101 // transform. Bail out if we can not exclude that possibility. 102 if (isa<FPMathOperator>(BO)) 103 if (!BO->hasNoSignedZeros() && !CannotBeNegativeZero(Y, &TLI)) 104 return nullptr; 105 106 // BO = binop Y, X 107 // S = { select (cmp eq X, C), BO, ? } or { select (cmp ne X, C), ?, BO } 108 // => 109 // S = { select (cmp eq X, C), Y, ? } or { select (cmp ne X, C), ?, Y } 110 Sel.setOperand(IsEq ? 1 : 2, Y); 111 return &Sel; 112 } 113 114 /// This folds: 115 /// select (icmp eq (and X, C1)), TC, FC 116 /// iff C1 is a power 2 and the difference between TC and FC is a power-of-2. 117 /// To something like: 118 /// (shr (and (X, C1)), (log2(C1) - log2(TC-FC))) + FC 119 /// Or: 120 /// (shl (and (X, C1)), (log2(TC-FC) - log2(C1))) + FC 121 /// With some variations depending if FC is larger than TC, or the shift 122 /// isn't needed, or the bit widths don't match. 123 static Value *foldSelectICmpAnd(SelectInst &Sel, ICmpInst *Cmp, 124 InstCombiner::BuilderTy &Builder) { 125 const APInt *SelTC, *SelFC; 126 if (!match(Sel.getTrueValue(), m_APInt(SelTC)) || 127 !match(Sel.getFalseValue(), m_APInt(SelFC))) 128 return nullptr; 129 130 // If this is a vector select, we need a vector compare. 131 Type *SelType = Sel.getType(); 132 if (SelType->isVectorTy() != Cmp->getType()->isVectorTy()) 133 return nullptr; 134 135 Value *V; 136 APInt AndMask; 137 bool CreateAnd = false; 138 ICmpInst::Predicate Pred = Cmp->getPredicate(); 139 if (ICmpInst::isEquality(Pred)) { 140 if (!match(Cmp->getOperand(1), m_Zero())) 141 return nullptr; 142 143 V = Cmp->getOperand(0); 144 const APInt *AndRHS; 145 if (!match(V, m_And(m_Value(), m_Power2(AndRHS)))) 146 return nullptr; 147 148 AndMask = *AndRHS; 149 } else if (decomposeBitTestICmp(Cmp->getOperand(0), Cmp->getOperand(1), 150 Pred, V, AndMask)) { 151 assert(ICmpInst::isEquality(Pred) && "Not equality test?"); 152 if (!AndMask.isPowerOf2()) 153 return nullptr; 154 155 CreateAnd = true; 156 } else { 157 return nullptr; 158 } 159 160 // In general, when both constants are non-zero, we would need an offset to 161 // replace the select. This would require more instructions than we started 162 // with. But there's one special-case that we handle here because it can 163 // simplify/reduce the instructions. 164 APInt TC = *SelTC; 165 APInt FC = *SelFC; 166 if (!TC.isNullValue() && !FC.isNullValue()) { 167 // If the select constants differ by exactly one bit and that's the same 168 // bit that is masked and checked by the select condition, the select can 169 // be replaced by bitwise logic to set/clear one bit of the constant result. 170 if (TC.getBitWidth() != AndMask.getBitWidth() || (TC ^ FC) != AndMask) 171 return nullptr; 172 if (CreateAnd) { 173 // If we have to create an 'and', then we must kill the cmp to not 174 // increase the instruction count. 175 if (!Cmp->hasOneUse()) 176 return nullptr; 177 V = Builder.CreateAnd(V, ConstantInt::get(SelType, AndMask)); 178 } 179 bool ExtraBitInTC = TC.ugt(FC); 180 if (Pred == ICmpInst::ICMP_EQ) { 181 // If the masked bit in V is clear, clear or set the bit in the result: 182 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) ^ TC 183 // (V & AndMaskC) == 0 ? TC : FC --> (V & AndMaskC) | TC 184 Constant *C = ConstantInt::get(SelType, TC); 185 return ExtraBitInTC ? Builder.CreateXor(V, C) : Builder.CreateOr(V, C); 186 } 187 if (Pred == ICmpInst::ICMP_NE) { 188 // If the masked bit in V is set, set or clear the bit in the result: 189 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) | FC 190 // (V & AndMaskC) != 0 ? TC : FC --> (V & AndMaskC) ^ FC 191 Constant *C = ConstantInt::get(SelType, FC); 192 return ExtraBitInTC ? Builder.CreateOr(V, C) : Builder.CreateXor(V, C); 193 } 194 llvm_unreachable("Only expecting equality predicates"); 195 } 196 197 // Make sure one of the select arms is a power-of-2. 198 if (!TC.isPowerOf2() && !FC.isPowerOf2()) 199 return nullptr; 200 201 // Determine which shift is needed to transform result of the 'and' into the 202 // desired result. 203 const APInt &ValC = !TC.isNullValue() ? TC : FC; 204 unsigned ValZeros = ValC.logBase2(); 205 unsigned AndZeros = AndMask.logBase2(); 206 207 // Insert the 'and' instruction on the input to the truncate. 208 if (CreateAnd) 209 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), AndMask)); 210 211 // If types don't match, we can still convert the select by introducing a zext 212 // or a trunc of the 'and'. 213 if (ValZeros > AndZeros) { 214 V = Builder.CreateZExtOrTrunc(V, SelType); 215 V = Builder.CreateShl(V, ValZeros - AndZeros); 216 } else if (ValZeros < AndZeros) { 217 V = Builder.CreateLShr(V, AndZeros - ValZeros); 218 V = Builder.CreateZExtOrTrunc(V, SelType); 219 } else { 220 V = Builder.CreateZExtOrTrunc(V, SelType); 221 } 222 223 // Okay, now we know that everything is set up, we just don't know whether we 224 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 225 bool ShouldNotVal = !TC.isNullValue(); 226 ShouldNotVal ^= Pred == ICmpInst::ICMP_NE; 227 if (ShouldNotVal) 228 V = Builder.CreateXor(V, ValC); 229 230 return V; 231 } 232 233 /// We want to turn code that looks like this: 234 /// %C = or %A, %B 235 /// %D = select %cond, %C, %A 236 /// into: 237 /// %C = select %cond, %B, 0 238 /// %D = or %A, %C 239 /// 240 /// Assuming that the specified instruction is an operand to the select, return 241 /// a bitmask indicating which operands of this instruction are foldable if they 242 /// equal the other incoming value of the select. 243 static unsigned getSelectFoldableOperands(BinaryOperator *I) { 244 switch (I->getOpcode()) { 245 case Instruction::Add: 246 case Instruction::Mul: 247 case Instruction::And: 248 case Instruction::Or: 249 case Instruction::Xor: 250 return 3; // Can fold through either operand. 251 case Instruction::Sub: // Can only fold on the amount subtracted. 252 case Instruction::Shl: // Can only fold on the shift amount. 253 case Instruction::LShr: 254 case Instruction::AShr: 255 return 1; 256 default: 257 return 0; // Cannot fold 258 } 259 } 260 261 /// For the same transformation as the previous function, return the identity 262 /// constant that goes into the select. 263 static APInt getSelectFoldableConstant(BinaryOperator *I) { 264 switch (I->getOpcode()) { 265 default: llvm_unreachable("This cannot happen!"); 266 case Instruction::Add: 267 case Instruction::Sub: 268 case Instruction::Or: 269 case Instruction::Xor: 270 case Instruction::Shl: 271 case Instruction::LShr: 272 case Instruction::AShr: 273 return APInt::getNullValue(I->getType()->getScalarSizeInBits()); 274 case Instruction::And: 275 return APInt::getAllOnesValue(I->getType()->getScalarSizeInBits()); 276 case Instruction::Mul: 277 return APInt(I->getType()->getScalarSizeInBits(), 1); 278 } 279 } 280 281 /// We have (select c, TI, FI), and we know that TI and FI have the same opcode. 282 Instruction *InstCombiner::foldSelectOpOp(SelectInst &SI, Instruction *TI, 283 Instruction *FI) { 284 // Don't break up min/max patterns. The hasOneUse checks below prevent that 285 // for most cases, but vector min/max with bitcasts can be transformed. If the 286 // one-use restrictions are eased for other patterns, we still don't want to 287 // obfuscate min/max. 288 if ((match(&SI, m_SMin(m_Value(), m_Value())) || 289 match(&SI, m_SMax(m_Value(), m_Value())) || 290 match(&SI, m_UMin(m_Value(), m_Value())) || 291 match(&SI, m_UMax(m_Value(), m_Value())))) 292 return nullptr; 293 294 // If this is a cast from the same type, merge. 295 Value *Cond = SI.getCondition(); 296 Type *CondTy = Cond->getType(); 297 if (TI->getNumOperands() == 1 && TI->isCast()) { 298 Type *FIOpndTy = FI->getOperand(0)->getType(); 299 if (TI->getOperand(0)->getType() != FIOpndTy) 300 return nullptr; 301 302 // The select condition may be a vector. We may only change the operand 303 // type if the vector width remains the same (and matches the condition). 304 if (CondTy->isVectorTy()) { 305 if (!FIOpndTy->isVectorTy()) 306 return nullptr; 307 if (CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements()) 308 return nullptr; 309 310 // TODO: If the backend knew how to deal with casts better, we could 311 // remove this limitation. For now, there's too much potential to create 312 // worse codegen by promoting the select ahead of size-altering casts 313 // (PR28160). 314 // 315 // Note that ValueTracking's matchSelectPattern() looks through casts 316 // without checking 'hasOneUse' when it matches min/max patterns, so this 317 // transform may end up happening anyway. 318 if (TI->getOpcode() != Instruction::BitCast && 319 (!TI->hasOneUse() || !FI->hasOneUse())) 320 return nullptr; 321 } else if (!TI->hasOneUse() || !FI->hasOneUse()) { 322 // TODO: The one-use restrictions for a scalar select could be eased if 323 // the fold of a select in visitLoadInst() was enhanced to match a pattern 324 // that includes a cast. 325 return nullptr; 326 } 327 328 // Fold this by inserting a select from the input values. 329 Value *NewSI = 330 Builder.CreateSelect(Cond, TI->getOperand(0), FI->getOperand(0), 331 SI.getName() + ".v", &SI); 332 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 333 TI->getType()); 334 } 335 336 // Cond ? -X : -Y --> -(Cond ? X : Y) 337 Value *X, *Y; 338 if (match(TI, m_FNeg(m_Value(X))) && match(FI, m_FNeg(m_Value(Y))) && 339 (TI->hasOneUse() || FI->hasOneUse())) { 340 Value *NewSel = Builder.CreateSelect(Cond, X, Y, SI.getName() + ".v", &SI); 341 // TODO: Remove the hack for the binop form when the unary op is optimized 342 // properly with all IR passes. 343 if (TI->getOpcode() != Instruction::FNeg) 344 return BinaryOperator::CreateFNegFMF(NewSel, cast<BinaryOperator>(TI)); 345 return UnaryOperator::CreateFNeg(NewSel); 346 } 347 348 // Only handle binary operators (including two-operand getelementptr) with 349 // one-use here. As with the cast case above, it may be possible to relax the 350 // one-use constraint, but that needs be examined carefully since it may not 351 // reduce the total number of instructions. 352 if (TI->getNumOperands() != 2 || FI->getNumOperands() != 2 || 353 (!isa<BinaryOperator>(TI) && !isa<GetElementPtrInst>(TI)) || 354 !TI->hasOneUse() || !FI->hasOneUse()) 355 return nullptr; 356 357 // Figure out if the operations have any operands in common. 358 Value *MatchOp, *OtherOpT, *OtherOpF; 359 bool MatchIsOpZero; 360 if (TI->getOperand(0) == FI->getOperand(0)) { 361 MatchOp = TI->getOperand(0); 362 OtherOpT = TI->getOperand(1); 363 OtherOpF = FI->getOperand(1); 364 MatchIsOpZero = true; 365 } else if (TI->getOperand(1) == FI->getOperand(1)) { 366 MatchOp = TI->getOperand(1); 367 OtherOpT = TI->getOperand(0); 368 OtherOpF = FI->getOperand(0); 369 MatchIsOpZero = false; 370 } else if (!TI->isCommutative()) { 371 return nullptr; 372 } else if (TI->getOperand(0) == FI->getOperand(1)) { 373 MatchOp = TI->getOperand(0); 374 OtherOpT = TI->getOperand(1); 375 OtherOpF = FI->getOperand(0); 376 MatchIsOpZero = true; 377 } else if (TI->getOperand(1) == FI->getOperand(0)) { 378 MatchOp = TI->getOperand(1); 379 OtherOpT = TI->getOperand(0); 380 OtherOpF = FI->getOperand(1); 381 MatchIsOpZero = true; 382 } else { 383 return nullptr; 384 } 385 386 // If the select condition is a vector, the operands of the original select's 387 // operands also must be vectors. This may not be the case for getelementptr 388 // for example. 389 if (CondTy->isVectorTy() && (!OtherOpT->getType()->isVectorTy() || 390 !OtherOpF->getType()->isVectorTy())) 391 return nullptr; 392 393 // If we reach here, they do have operations in common. 394 Value *NewSI = Builder.CreateSelect(Cond, OtherOpT, OtherOpF, 395 SI.getName() + ".v", &SI); 396 Value *Op0 = MatchIsOpZero ? MatchOp : NewSI; 397 Value *Op1 = MatchIsOpZero ? NewSI : MatchOp; 398 if (auto *BO = dyn_cast<BinaryOperator>(TI)) { 399 BinaryOperator *NewBO = BinaryOperator::Create(BO->getOpcode(), Op0, Op1); 400 NewBO->copyIRFlags(TI); 401 NewBO->andIRFlags(FI); 402 return NewBO; 403 } 404 if (auto *TGEP = dyn_cast<GetElementPtrInst>(TI)) { 405 auto *FGEP = cast<GetElementPtrInst>(FI); 406 Type *ElementType = TGEP->getResultElementType(); 407 return TGEP->isInBounds() && FGEP->isInBounds() 408 ? GetElementPtrInst::CreateInBounds(ElementType, Op0, {Op1}) 409 : GetElementPtrInst::Create(ElementType, Op0, {Op1}); 410 } 411 llvm_unreachable("Expected BinaryOperator or GEP"); 412 return nullptr; 413 } 414 415 static bool isSelect01(const APInt &C1I, const APInt &C2I) { 416 if (!C1I.isNullValue() && !C2I.isNullValue()) // One side must be zero. 417 return false; 418 return C1I.isOneValue() || C1I.isAllOnesValue() || 419 C2I.isOneValue() || C2I.isAllOnesValue(); 420 } 421 422 /// Try to fold the select into one of the operands to allow further 423 /// optimization. 424 Instruction *InstCombiner::foldSelectIntoOp(SelectInst &SI, Value *TrueVal, 425 Value *FalseVal) { 426 // See the comment above GetSelectFoldableOperands for a description of the 427 // transformation we are doing here. 428 if (auto *TVI = dyn_cast<BinaryOperator>(TrueVal)) { 429 if (TVI->hasOneUse() && !isa<Constant>(FalseVal)) { 430 if (unsigned SFO = getSelectFoldableOperands(TVI)) { 431 unsigned OpToFold = 0; 432 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 433 OpToFold = 1; 434 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 435 OpToFold = 2; 436 } 437 438 if (OpToFold) { 439 APInt CI = getSelectFoldableConstant(TVI); 440 Value *OOp = TVI->getOperand(2-OpToFold); 441 // Avoid creating select between 2 constants unless it's selecting 442 // between 0, 1 and -1. 443 const APInt *OOpC; 444 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 445 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) { 446 Value *C = ConstantInt::get(OOp->getType(), CI); 447 Value *NewSel = Builder.CreateSelect(SI.getCondition(), OOp, C); 448 NewSel->takeName(TVI); 449 BinaryOperator *BO = BinaryOperator::Create(TVI->getOpcode(), 450 FalseVal, NewSel); 451 BO->copyIRFlags(TVI); 452 return BO; 453 } 454 } 455 } 456 } 457 } 458 459 if (auto *FVI = dyn_cast<BinaryOperator>(FalseVal)) { 460 if (FVI->hasOneUse() && !isa<Constant>(TrueVal)) { 461 if (unsigned SFO = getSelectFoldableOperands(FVI)) { 462 unsigned OpToFold = 0; 463 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 464 OpToFold = 1; 465 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 466 OpToFold = 2; 467 } 468 469 if (OpToFold) { 470 APInt CI = getSelectFoldableConstant(FVI); 471 Value *OOp = FVI->getOperand(2-OpToFold); 472 // Avoid creating select between 2 constants unless it's selecting 473 // between 0, 1 and -1. 474 const APInt *OOpC; 475 bool OOpIsAPInt = match(OOp, m_APInt(OOpC)); 476 if (!isa<Constant>(OOp) || (OOpIsAPInt && isSelect01(CI, *OOpC))) { 477 Value *C = ConstantInt::get(OOp->getType(), CI); 478 Value *NewSel = Builder.CreateSelect(SI.getCondition(), C, OOp); 479 NewSel->takeName(FVI); 480 BinaryOperator *BO = BinaryOperator::Create(FVI->getOpcode(), 481 TrueVal, NewSel); 482 BO->copyIRFlags(FVI); 483 return BO; 484 } 485 } 486 } 487 } 488 } 489 490 return nullptr; 491 } 492 493 /// We want to turn: 494 /// (select (icmp eq (and X, Y), 0), (and (lshr X, Z), 1), 1) 495 /// into: 496 /// zext (icmp ne i32 (and X, (or Y, (shl 1, Z))), 0) 497 /// Note: 498 /// Z may be 0 if lshr is missing. 499 /// Worst-case scenario is that we will replace 5 instructions with 5 different 500 /// instructions, but we got rid of select. 501 static Instruction *foldSelectICmpAndAnd(Type *SelType, const ICmpInst *Cmp, 502 Value *TVal, Value *FVal, 503 InstCombiner::BuilderTy &Builder) { 504 if (!(Cmp->hasOneUse() && Cmp->getOperand(0)->hasOneUse() && 505 Cmp->getPredicate() == ICmpInst::ICMP_EQ && 506 match(Cmp->getOperand(1), m_Zero()) && match(FVal, m_One()))) 507 return nullptr; 508 509 // The TrueVal has general form of: and %B, 1 510 Value *B; 511 if (!match(TVal, m_OneUse(m_And(m_Value(B), m_One())))) 512 return nullptr; 513 514 // Where %B may be optionally shifted: lshr %X, %Z. 515 Value *X, *Z; 516 const bool HasShift = match(B, m_OneUse(m_LShr(m_Value(X), m_Value(Z)))); 517 if (!HasShift) 518 X = B; 519 520 Value *Y; 521 if (!match(Cmp->getOperand(0), m_c_And(m_Specific(X), m_Value(Y)))) 522 return nullptr; 523 524 // ((X & Y) == 0) ? ((X >> Z) & 1) : 1 --> (X & (Y | (1 << Z))) != 0 525 // ((X & Y) == 0) ? (X & 1) : 1 --> (X & (Y | 1)) != 0 526 Constant *One = ConstantInt::get(SelType, 1); 527 Value *MaskB = HasShift ? Builder.CreateShl(One, Z) : One; 528 Value *FullMask = Builder.CreateOr(Y, MaskB); 529 Value *MaskedX = Builder.CreateAnd(X, FullMask); 530 Value *ICmpNeZero = Builder.CreateIsNotNull(MaskedX); 531 return new ZExtInst(ICmpNeZero, SelType); 532 } 533 534 /// We want to turn: 535 /// (select (icmp sgt x, C), lshr (X, Y), ashr (X, Y)); iff C s>= -1 536 /// (select (icmp slt x, C), ashr (X, Y), lshr (X, Y)); iff C s>= 0 537 /// into: 538 /// ashr (X, Y) 539 static Value *foldSelectICmpLshrAshr(const ICmpInst *IC, Value *TrueVal, 540 Value *FalseVal, 541 InstCombiner::BuilderTy &Builder) { 542 ICmpInst::Predicate Pred = IC->getPredicate(); 543 Value *CmpLHS = IC->getOperand(0); 544 Value *CmpRHS = IC->getOperand(1); 545 if (!CmpRHS->getType()->isIntOrIntVectorTy()) 546 return nullptr; 547 548 Value *X, *Y; 549 unsigned Bitwidth = CmpRHS->getType()->getScalarSizeInBits(); 550 if ((Pred != ICmpInst::ICMP_SGT || 551 !match(CmpRHS, 552 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, -1)))) && 553 (Pred != ICmpInst::ICMP_SLT || 554 !match(CmpRHS, 555 m_SpecificInt_ICMP(ICmpInst::ICMP_SGE, APInt(Bitwidth, 0))))) 556 return nullptr; 557 558 // Canonicalize so that ashr is in FalseVal. 559 if (Pred == ICmpInst::ICMP_SLT) 560 std::swap(TrueVal, FalseVal); 561 562 if (match(TrueVal, m_LShr(m_Value(X), m_Value(Y))) && 563 match(FalseVal, m_AShr(m_Specific(X), m_Specific(Y))) && 564 match(CmpLHS, m_Specific(X))) { 565 const auto *Ashr = cast<Instruction>(FalseVal); 566 // if lshr is not exact and ashr is, this new ashr must not be exact. 567 bool IsExact = Ashr->isExact() && cast<Instruction>(TrueVal)->isExact(); 568 return Builder.CreateAShr(X, Y, IC->getName(), IsExact); 569 } 570 571 return nullptr; 572 } 573 574 /// We want to turn: 575 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) 576 /// into: 577 /// (or (shl (and X, C1), C3), Y) 578 /// iff: 579 /// C1 and C2 are both powers of 2 580 /// where: 581 /// C3 = Log(C2) - Log(C1) 582 /// 583 /// This transform handles cases where: 584 /// 1. The icmp predicate is inverted 585 /// 2. The select operands are reversed 586 /// 3. The magnitude of C2 and C1 are flipped 587 static Value *foldSelectICmpAndOr(const ICmpInst *IC, Value *TrueVal, 588 Value *FalseVal, 589 InstCombiner::BuilderTy &Builder) { 590 // Only handle integer compares. Also, if this is a vector select, we need a 591 // vector compare. 592 if (!TrueVal->getType()->isIntOrIntVectorTy() || 593 TrueVal->getType()->isVectorTy() != IC->getType()->isVectorTy()) 594 return nullptr; 595 596 Value *CmpLHS = IC->getOperand(0); 597 Value *CmpRHS = IC->getOperand(1); 598 599 Value *V; 600 unsigned C1Log; 601 bool IsEqualZero; 602 bool NeedAnd = false; 603 if (IC->isEquality()) { 604 if (!match(CmpRHS, m_Zero())) 605 return nullptr; 606 607 const APInt *C1; 608 if (!match(CmpLHS, m_And(m_Value(), m_Power2(C1)))) 609 return nullptr; 610 611 V = CmpLHS; 612 C1Log = C1->logBase2(); 613 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_EQ; 614 } else if (IC->getPredicate() == ICmpInst::ICMP_SLT || 615 IC->getPredicate() == ICmpInst::ICMP_SGT) { 616 // We also need to recognize (icmp slt (trunc (X)), 0) and 617 // (icmp sgt (trunc (X)), -1). 618 IsEqualZero = IC->getPredicate() == ICmpInst::ICMP_SGT; 619 if ((IsEqualZero && !match(CmpRHS, m_AllOnes())) || 620 (!IsEqualZero && !match(CmpRHS, m_Zero()))) 621 return nullptr; 622 623 if (!match(CmpLHS, m_OneUse(m_Trunc(m_Value(V))))) 624 return nullptr; 625 626 C1Log = CmpLHS->getType()->getScalarSizeInBits() - 1; 627 NeedAnd = true; 628 } else { 629 return nullptr; 630 } 631 632 const APInt *C2; 633 bool OrOnTrueVal = false; 634 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2))); 635 if (!OrOnFalseVal) 636 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2))); 637 638 if (!OrOnFalseVal && !OrOnTrueVal) 639 return nullptr; 640 641 Value *Y = OrOnFalseVal ? TrueVal : FalseVal; 642 643 unsigned C2Log = C2->logBase2(); 644 645 bool NeedXor = (!IsEqualZero && OrOnFalseVal) || (IsEqualZero && OrOnTrueVal); 646 bool NeedShift = C1Log != C2Log; 647 bool NeedZExtTrunc = Y->getType()->getScalarSizeInBits() != 648 V->getType()->getScalarSizeInBits(); 649 650 // Make sure we don't create more instructions than we save. 651 Value *Or = OrOnFalseVal ? FalseVal : TrueVal; 652 if ((NeedShift + NeedXor + NeedZExtTrunc) > 653 (IC->hasOneUse() + Or->hasOneUse())) 654 return nullptr; 655 656 if (NeedAnd) { 657 // Insert the AND instruction on the input to the truncate. 658 APInt C1 = APInt::getOneBitSet(V->getType()->getScalarSizeInBits(), C1Log); 659 V = Builder.CreateAnd(V, ConstantInt::get(V->getType(), C1)); 660 } 661 662 if (C2Log > C1Log) { 663 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 664 V = Builder.CreateShl(V, C2Log - C1Log); 665 } else if (C1Log > C2Log) { 666 V = Builder.CreateLShr(V, C1Log - C2Log); 667 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 668 } else 669 V = Builder.CreateZExtOrTrunc(V, Y->getType()); 670 671 if (NeedXor) 672 V = Builder.CreateXor(V, *C2); 673 674 return Builder.CreateOr(V, Y); 675 } 676 677 /// Transform patterns such as (a > b) ? a - b : 0 into usub.sat(a, b). 678 /// There are 8 commuted/swapped variants of this pattern. 679 /// TODO: Also support a - UMIN(a,b) patterns. 680 static Value *canonicalizeSaturatedSubtract(const ICmpInst *ICI, 681 const Value *TrueVal, 682 const Value *FalseVal, 683 InstCombiner::BuilderTy &Builder) { 684 ICmpInst::Predicate Pred = ICI->getPredicate(); 685 if (!ICmpInst::isUnsigned(Pred)) 686 return nullptr; 687 688 // (b > a) ? 0 : a - b -> (b <= a) ? a - b : 0 689 if (match(TrueVal, m_Zero())) { 690 Pred = ICmpInst::getInversePredicate(Pred); 691 std::swap(TrueVal, FalseVal); 692 } 693 if (!match(FalseVal, m_Zero())) 694 return nullptr; 695 696 Value *A = ICI->getOperand(0); 697 Value *B = ICI->getOperand(1); 698 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_ULT) { 699 // (b < a) ? a - b : 0 -> (a > b) ? a - b : 0 700 std::swap(A, B); 701 Pred = ICmpInst::getSwappedPredicate(Pred); 702 } 703 704 assert((Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_UGT) && 705 "Unexpected isUnsigned predicate!"); 706 707 // Account for swapped form of subtraction: ((a > b) ? b - a : 0). 708 bool IsNegative = false; 709 if (match(TrueVal, m_Sub(m_Specific(B), m_Specific(A)))) 710 IsNegative = true; 711 else if (!match(TrueVal, m_Sub(m_Specific(A), m_Specific(B)))) 712 return nullptr; 713 714 // If sub is used anywhere else, we wouldn't be able to eliminate it 715 // afterwards. 716 if (!TrueVal->hasOneUse()) 717 return nullptr; 718 719 // (a > b) ? a - b : 0 -> usub.sat(a, b) 720 // (a > b) ? b - a : 0 -> -usub.sat(a, b) 721 Value *Result = Builder.CreateBinaryIntrinsic(Intrinsic::usub_sat, A, B); 722 if (IsNegative) 723 Result = Builder.CreateNeg(Result); 724 return Result; 725 } 726 727 static Value *canonicalizeSaturatedAdd(ICmpInst *Cmp, Value *TVal, Value *FVal, 728 InstCombiner::BuilderTy &Builder) { 729 if (!Cmp->hasOneUse()) 730 return nullptr; 731 732 // Match unsigned saturated add with constant. 733 Value *Cmp0 = Cmp->getOperand(0); 734 Value *Cmp1 = Cmp->getOperand(1); 735 ICmpInst::Predicate Pred = Cmp->getPredicate(); 736 Value *X; 737 const APInt *C, *CmpC; 738 if (Pred == ICmpInst::ICMP_ULT && 739 match(TVal, m_Add(m_Value(X), m_APInt(C))) && X == Cmp0 && 740 match(FVal, m_AllOnes()) && match(Cmp1, m_APInt(CmpC)) && *CmpC == ~*C) { 741 // (X u< ~C) ? (X + C) : -1 --> uadd.sat(X, C) 742 return Builder.CreateBinaryIntrinsic( 743 Intrinsic::uadd_sat, X, ConstantInt::get(X->getType(), *C)); 744 } 745 746 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 747 // There are 8 commuted variants. 748 // Canonicalize -1 (saturated result) to true value of the select. Just 749 // swapping the compare operands is legal, because the selected value is the 750 // same in case of equality, so we can interchange u< and u<=. 751 if (match(FVal, m_AllOnes())) { 752 std::swap(TVal, FVal); 753 std::swap(Cmp0, Cmp1); 754 } 755 if (!match(TVal, m_AllOnes())) 756 return nullptr; 757 758 // Canonicalize predicate to 'ULT'. 759 if (Pred == ICmpInst::ICMP_UGT) { 760 Pred = ICmpInst::ICMP_ULT; 761 std::swap(Cmp0, Cmp1); 762 } 763 if (Pred != ICmpInst::ICMP_ULT) 764 return nullptr; 765 766 // Match unsigned saturated add of 2 variables with an unnecessary 'not'. 767 Value *Y; 768 if (match(Cmp0, m_Not(m_Value(X))) && 769 match(FVal, m_c_Add(m_Specific(X), m_Value(Y))) && Y == Cmp1) { 770 // (~X u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) 771 // (~X u< Y) ? -1 : (Y + X) --> uadd.sat(X, Y) 772 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, X, Y); 773 } 774 // The 'not' op may be included in the sum but not the compare. 775 X = Cmp0; 776 Y = Cmp1; 777 if (match(FVal, m_c_Add(m_Not(m_Specific(X)), m_Specific(Y)))) { 778 // (X u< Y) ? -1 : (~X + Y) --> uadd.sat(~X, Y) 779 // (X u< Y) ? -1 : (Y + ~X) --> uadd.sat(Y, ~X) 780 BinaryOperator *BO = cast<BinaryOperator>(FVal); 781 return Builder.CreateBinaryIntrinsic( 782 Intrinsic::uadd_sat, BO->getOperand(0), BO->getOperand(1)); 783 } 784 // The overflow may be detected via the add wrapping round. 785 if (match(Cmp0, m_c_Add(m_Specific(Cmp1), m_Value(Y))) && 786 match(FVal, m_c_Add(m_Specific(Cmp1), m_Specific(Y)))) { 787 // ((X + Y) u< X) ? -1 : (X + Y) --> uadd.sat(X, Y) 788 // ((X + Y) u< Y) ? -1 : (X + Y) --> uadd.sat(X, Y) 789 return Builder.CreateBinaryIntrinsic(Intrinsic::uadd_sat, Cmp1, Y); 790 } 791 792 return nullptr; 793 } 794 795 /// Fold the following code sequence: 796 /// \code 797 /// int a = ctlz(x & -x); 798 // x ? 31 - a : a; 799 /// \code 800 /// 801 /// into: 802 /// cttz(x) 803 static Instruction *foldSelectCtlzToCttz(ICmpInst *ICI, Value *TrueVal, 804 Value *FalseVal, 805 InstCombiner::BuilderTy &Builder) { 806 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits(); 807 if (!ICI->isEquality() || !match(ICI->getOperand(1), m_Zero())) 808 return nullptr; 809 810 if (ICI->getPredicate() == ICmpInst::ICMP_NE) 811 std::swap(TrueVal, FalseVal); 812 813 if (!match(FalseVal, 814 m_Xor(m_Deferred(TrueVal), m_SpecificInt(BitWidth - 1)))) 815 return nullptr; 816 817 if (!match(TrueVal, m_Intrinsic<Intrinsic::ctlz>())) 818 return nullptr; 819 820 Value *X = ICI->getOperand(0); 821 auto *II = cast<IntrinsicInst>(TrueVal); 822 if (!match(II->getOperand(0), m_c_And(m_Specific(X), m_Neg(m_Specific(X))))) 823 return nullptr; 824 825 Function *F = Intrinsic::getDeclaration(II->getModule(), Intrinsic::cttz, 826 II->getType()); 827 return CallInst::Create(F, {X, II->getArgOperand(1)}); 828 } 829 830 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single 831 /// call to cttz/ctlz with flag 'is_zero_undef' cleared. 832 /// 833 /// For example, we can fold the following code sequence: 834 /// \code 835 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true) 836 /// %1 = icmp ne i32 %x, 0 837 /// %2 = select i1 %1, i32 %0, i32 32 838 /// \code 839 /// 840 /// into: 841 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false) 842 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal, 843 InstCombiner::BuilderTy &Builder) { 844 ICmpInst::Predicate Pred = ICI->getPredicate(); 845 Value *CmpLHS = ICI->getOperand(0); 846 Value *CmpRHS = ICI->getOperand(1); 847 848 // Check if the condition value compares a value for equality against zero. 849 if (!ICI->isEquality() || !match(CmpRHS, m_Zero())) 850 return nullptr; 851 852 Value *Count = FalseVal; 853 Value *ValueOnZero = TrueVal; 854 if (Pred == ICmpInst::ICMP_NE) 855 std::swap(Count, ValueOnZero); 856 857 // Skip zero extend/truncate. 858 Value *V = nullptr; 859 if (match(Count, m_ZExt(m_Value(V))) || 860 match(Count, m_Trunc(m_Value(V)))) 861 Count = V; 862 863 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the 864 // input to the cttz/ctlz is used as LHS for the compare instruction. 865 if (!match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) && 866 !match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) 867 return nullptr; 868 869 IntrinsicInst *II = cast<IntrinsicInst>(Count); 870 871 // Check if the value propagated on zero is a constant number equal to the 872 // sizeof in bits of 'Count'. 873 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits(); 874 if (match(ValueOnZero, m_SpecificInt(SizeOfInBits))) { 875 // Explicitly clear the 'undef_on_zero' flag. 876 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone()); 877 NewI->setArgOperand(1, ConstantInt::getFalse(NewI->getContext())); 878 Builder.Insert(NewI); 879 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType()); 880 } 881 882 // If the ValueOnZero is not the bitwidth, we can at least make use of the 883 // fact that the cttz/ctlz result will not be used if the input is zero, so 884 // it's okay to relax it to undef for that case. 885 if (II->hasOneUse() && !match(II->getArgOperand(1), m_One())) 886 II->setArgOperand(1, ConstantInt::getTrue(II->getContext())); 887 888 return nullptr; 889 } 890 891 /// Return true if we find and adjust an icmp+select pattern where the compare 892 /// is with a constant that can be incremented or decremented to match the 893 /// minimum or maximum idiom. 894 static bool adjustMinMax(SelectInst &Sel, ICmpInst &Cmp) { 895 ICmpInst::Predicate Pred = Cmp.getPredicate(); 896 Value *CmpLHS = Cmp.getOperand(0); 897 Value *CmpRHS = Cmp.getOperand(1); 898 Value *TrueVal = Sel.getTrueValue(); 899 Value *FalseVal = Sel.getFalseValue(); 900 901 // We may move or edit the compare, so make sure the select is the only user. 902 const APInt *CmpC; 903 if (!Cmp.hasOneUse() || !match(CmpRHS, m_APInt(CmpC))) 904 return false; 905 906 // These transforms only work for selects of integers or vector selects of 907 // integer vectors. 908 Type *SelTy = Sel.getType(); 909 auto *SelEltTy = dyn_cast<IntegerType>(SelTy->getScalarType()); 910 if (!SelEltTy || SelTy->isVectorTy() != Cmp.getType()->isVectorTy()) 911 return false; 912 913 Constant *AdjustedRHS; 914 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 915 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC + 1); 916 else if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 917 AdjustedRHS = ConstantInt::get(CmpRHS->getType(), *CmpC - 1); 918 else 919 return false; 920 921 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 922 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 923 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 924 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) { 925 ; // Nothing to do here. Values match without any sign/zero extension. 926 } 927 // Types do not match. Instead of calculating this with mixed types, promote 928 // all to the larger type. This enables scalar evolution to analyze this 929 // expression. 930 else if (CmpRHS->getType()->getScalarSizeInBits() < SelEltTy->getBitWidth()) { 931 Constant *SextRHS = ConstantExpr::getSExt(AdjustedRHS, SelTy); 932 933 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 934 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 935 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 936 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 937 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && SextRHS == FalseVal) { 938 CmpLHS = TrueVal; 939 AdjustedRHS = SextRHS; 940 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 941 SextRHS == TrueVal) { 942 CmpLHS = FalseVal; 943 AdjustedRHS = SextRHS; 944 } else if (Cmp.isUnsigned()) { 945 Constant *ZextRHS = ConstantExpr::getZExt(AdjustedRHS, SelTy); 946 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 947 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 948 // zext + signed compare cannot be changed: 949 // 0xff <s 0x00, but 0x00ff >s 0x0000 950 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && ZextRHS == FalseVal) { 951 CmpLHS = TrueVal; 952 AdjustedRHS = ZextRHS; 953 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 954 ZextRHS == TrueVal) { 955 CmpLHS = FalseVal; 956 AdjustedRHS = ZextRHS; 957 } else { 958 return false; 959 } 960 } else { 961 return false; 962 } 963 } else { 964 return false; 965 } 966 967 Pred = ICmpInst::getSwappedPredicate(Pred); 968 CmpRHS = AdjustedRHS; 969 std::swap(FalseVal, TrueVal); 970 Cmp.setPredicate(Pred); 971 Cmp.setOperand(0, CmpLHS); 972 Cmp.setOperand(1, CmpRHS); 973 Sel.setOperand(1, TrueVal); 974 Sel.setOperand(2, FalseVal); 975 Sel.swapProfMetadata(); 976 977 // Move the compare instruction right before the select instruction. Otherwise 978 // the sext/zext value may be defined after the compare instruction uses it. 979 Cmp.moveBefore(&Sel); 980 981 return true; 982 } 983 984 /// If this is an integer min/max (icmp + select) with a constant operand, 985 /// create the canonical icmp for the min/max operation and canonicalize the 986 /// constant to the 'false' operand of the select: 987 /// select (icmp Pred X, C1), C2, X --> select (icmp Pred' X, C2), X, C2 988 /// Note: if C1 != C2, this will change the icmp constant to the existing 989 /// constant operand of the select. 990 static Instruction * 991 canonicalizeMinMaxWithConstant(SelectInst &Sel, ICmpInst &Cmp, 992 InstCombiner::BuilderTy &Builder) { 993 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1))) 994 return nullptr; 995 996 // Canonicalize the compare predicate based on whether we have min or max. 997 Value *LHS, *RHS; 998 SelectPatternResult SPR = matchSelectPattern(&Sel, LHS, RHS); 999 if (!SelectPatternResult::isMinOrMax(SPR.Flavor)) 1000 return nullptr; 1001 1002 // Is this already canonical? 1003 ICmpInst::Predicate CanonicalPred = getMinMaxPred(SPR.Flavor); 1004 if (Cmp.getOperand(0) == LHS && Cmp.getOperand(1) == RHS && 1005 Cmp.getPredicate() == CanonicalPred) 1006 return nullptr; 1007 1008 // Create the canonical compare and plug it into the select. 1009 Sel.setCondition(Builder.CreateICmp(CanonicalPred, LHS, RHS)); 1010 1011 // If the select operands did not change, we're done. 1012 if (Sel.getTrueValue() == LHS && Sel.getFalseValue() == RHS) 1013 return &Sel; 1014 1015 // If we are swapping the select operands, swap the metadata too. 1016 assert(Sel.getTrueValue() == RHS && Sel.getFalseValue() == LHS && 1017 "Unexpected results from matchSelectPattern"); 1018 Sel.swapValues(); 1019 Sel.swapProfMetadata(); 1020 return &Sel; 1021 } 1022 1023 /// There are many select variants for each of ABS/NABS. 1024 /// In matchSelectPattern(), there are different compare constants, compare 1025 /// predicates/operands and select operands. 1026 /// In isKnownNegation(), there are different formats of negated operands. 1027 /// Canonicalize all these variants to 1 pattern. 1028 /// This makes CSE more likely. 1029 static Instruction *canonicalizeAbsNabs(SelectInst &Sel, ICmpInst &Cmp, 1030 InstCombiner::BuilderTy &Builder) { 1031 if (!Cmp.hasOneUse() || !isa<Constant>(Cmp.getOperand(1))) 1032 return nullptr; 1033 1034 // Choose a sign-bit check for the compare (likely simpler for codegen). 1035 // ABS: (X <s 0) ? -X : X 1036 // NABS: (X <s 0) ? X : -X 1037 Value *LHS, *RHS; 1038 SelectPatternFlavor SPF = matchSelectPattern(&Sel, LHS, RHS).Flavor; 1039 if (SPF != SelectPatternFlavor::SPF_ABS && 1040 SPF != SelectPatternFlavor::SPF_NABS) 1041 return nullptr; 1042 1043 Value *TVal = Sel.getTrueValue(); 1044 Value *FVal = Sel.getFalseValue(); 1045 assert(isKnownNegation(TVal, FVal) && 1046 "Unexpected result from matchSelectPattern"); 1047 1048 // The compare may use the negated abs()/nabs() operand, or it may use 1049 // negation in non-canonical form such as: sub A, B. 1050 bool CmpUsesNegatedOp = match(Cmp.getOperand(0), m_Neg(m_Specific(TVal))) || 1051 match(Cmp.getOperand(0), m_Neg(m_Specific(FVal))); 1052 1053 bool CmpCanonicalized = !CmpUsesNegatedOp && 1054 match(Cmp.getOperand(1), m_ZeroInt()) && 1055 Cmp.getPredicate() == ICmpInst::ICMP_SLT; 1056 bool RHSCanonicalized = match(RHS, m_Neg(m_Specific(LHS))); 1057 1058 // Is this already canonical? 1059 if (CmpCanonicalized && RHSCanonicalized) 1060 return nullptr; 1061 1062 // If RHS is used by other instructions except compare and select, don't 1063 // canonicalize it to not increase the instruction count. 1064 if (!(RHS->hasOneUse() || (RHS->hasNUses(2) && CmpUsesNegatedOp))) 1065 return nullptr; 1066 1067 // Create the canonical compare: icmp slt LHS 0. 1068 if (!CmpCanonicalized) { 1069 Cmp.setPredicate(ICmpInst::ICMP_SLT); 1070 Cmp.setOperand(1, ConstantInt::getNullValue(Cmp.getOperand(0)->getType())); 1071 if (CmpUsesNegatedOp) 1072 Cmp.setOperand(0, LHS); 1073 } 1074 1075 // Create the canonical RHS: RHS = sub (0, LHS). 1076 if (!RHSCanonicalized) { 1077 assert(RHS->hasOneUse() && "RHS use number is not right"); 1078 RHS = Builder.CreateNeg(LHS); 1079 if (TVal == LHS) { 1080 Sel.setFalseValue(RHS); 1081 FVal = RHS; 1082 } else { 1083 Sel.setTrueValue(RHS); 1084 TVal = RHS; 1085 } 1086 } 1087 1088 // If the select operands do not change, we're done. 1089 if (SPF == SelectPatternFlavor::SPF_NABS) { 1090 if (TVal == LHS) 1091 return &Sel; 1092 assert(FVal == LHS && "Unexpected results from matchSelectPattern"); 1093 } else { 1094 if (FVal == LHS) 1095 return &Sel; 1096 assert(TVal == LHS && "Unexpected results from matchSelectPattern"); 1097 } 1098 1099 // We are swapping the select operands, so swap the metadata too. 1100 Sel.swapValues(); 1101 Sel.swapProfMetadata(); 1102 return &Sel; 1103 } 1104 1105 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *ReplaceOp, 1106 const SimplifyQuery &Q) { 1107 // If this is a binary operator, try to simplify it with the replaced op 1108 // because we know Op and ReplaceOp are equivalant. 1109 // For example: V = X + 1, Op = X, ReplaceOp = 42 1110 // Simplifies as: add(42, 1) --> 43 1111 if (auto *BO = dyn_cast<BinaryOperator>(V)) { 1112 if (BO->getOperand(0) == Op) 1113 return SimplifyBinOp(BO->getOpcode(), ReplaceOp, BO->getOperand(1), Q); 1114 if (BO->getOperand(1) == Op) 1115 return SimplifyBinOp(BO->getOpcode(), BO->getOperand(0), ReplaceOp, Q); 1116 } 1117 1118 return nullptr; 1119 } 1120 1121 /// If we have a select with an equality comparison, then we know the value in 1122 /// one of the arms of the select. See if substituting this value into an arm 1123 /// and simplifying the result yields the same value as the other arm. 1124 /// 1125 /// To make this transform safe, we must drop poison-generating flags 1126 /// (nsw, etc) if we simplified to a binop because the select may be guarding 1127 /// that poison from propagating. If the existing binop already had no 1128 /// poison-generating flags, then this transform can be done by instsimplify. 1129 /// 1130 /// Consider: 1131 /// %cmp = icmp eq i32 %x, 2147483647 1132 /// %add = add nsw i32 %x, 1 1133 /// %sel = select i1 %cmp, i32 -2147483648, i32 %add 1134 /// 1135 /// We can't replace %sel with %add unless we strip away the flags. 1136 /// TODO: Wrapping flags could be preserved in some cases with better analysis. 1137 static Value *foldSelectValueEquivalence(SelectInst &Sel, ICmpInst &Cmp, 1138 const SimplifyQuery &Q) { 1139 if (!Cmp.isEquality()) 1140 return nullptr; 1141 1142 // Canonicalize the pattern to ICMP_EQ by swapping the select operands. 1143 Value *TrueVal = Sel.getTrueValue(), *FalseVal = Sel.getFalseValue(); 1144 if (Cmp.getPredicate() == ICmpInst::ICMP_NE) 1145 std::swap(TrueVal, FalseVal); 1146 1147 // Try each equivalence substitution possibility. 1148 // We have an 'EQ' comparison, so the select's false value will propagate. 1149 // Example: 1150 // (X == 42) ? 43 : (X + 1) --> (X == 42) ? (X + 1) : (X + 1) --> X + 1 1151 // (X == 42) ? (X + 1) : 43 --> (X == 42) ? (42 + 1) : 43 --> 43 1152 Value *CmpLHS = Cmp.getOperand(0), *CmpRHS = Cmp.getOperand(1); 1153 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q) == TrueVal || 1154 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q) == TrueVal || 1155 simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q) == FalseVal || 1156 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q) == FalseVal) { 1157 if (auto *FalseInst = dyn_cast<Instruction>(FalseVal)) 1158 FalseInst->dropPoisonGeneratingFlags(); 1159 return FalseVal; 1160 } 1161 return nullptr; 1162 } 1163 1164 // See if this is a pattern like: 1165 // %old_cmp1 = icmp slt i32 %x, C2 1166 // %old_replacement = select i1 %old_cmp1, i32 %target_low, i32 %target_high 1167 // %old_x_offseted = add i32 %x, C1 1168 // %old_cmp0 = icmp ult i32 %old_x_offseted, C0 1169 // %r = select i1 %old_cmp0, i32 %x, i32 %old_replacement 1170 // This can be rewritten as more canonical pattern: 1171 // %new_cmp1 = icmp slt i32 %x, -C1 1172 // %new_cmp2 = icmp sge i32 %x, C0-C1 1173 // %new_clamped_low = select i1 %new_cmp1, i32 %target_low, i32 %x 1174 // %r = select i1 %new_cmp2, i32 %target_high, i32 %new_clamped_low 1175 // Iff -C1 s<= C2 s<= C0-C1 1176 // Also ULT predicate can also be UGT iff C0 != -1 (+invert result) 1177 // SLT predicate can also be SGT iff C2 != INT_MAX (+invert res.) 1178 static Instruction *canonicalizeClampLike(SelectInst &Sel0, ICmpInst &Cmp0, 1179 InstCombiner::BuilderTy &Builder) { 1180 Value *X = Sel0.getTrueValue(); 1181 Value *Sel1 = Sel0.getFalseValue(); 1182 1183 // First match the condition of the outermost select. 1184 // Said condition must be one-use. 1185 if (!Cmp0.hasOneUse()) 1186 return nullptr; 1187 Value *Cmp00 = Cmp0.getOperand(0); 1188 Constant *C0; 1189 if (!match(Cmp0.getOperand(1), 1190 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0)))) 1191 return nullptr; 1192 // Canonicalize Cmp0 into the form we expect. 1193 // FIXME: we shouldn't care about lanes that are 'undef' in the end? 1194 switch (Cmp0.getPredicate()) { 1195 case ICmpInst::Predicate::ICMP_ULT: 1196 break; // Great! 1197 case ICmpInst::Predicate::ICMP_ULE: 1198 // We'd have to increment C0 by one, and for that it must not have all-ones 1199 // element, but then it would have been canonicalized to 'ult' before 1200 // we get here. So we can't do anything useful with 'ule'. 1201 return nullptr; 1202 case ICmpInst::Predicate::ICMP_UGT: 1203 // We want to canonicalize it to 'ult', so we'll need to increment C0, 1204 // which again means it must not have any all-ones elements. 1205 if (!match(C0, 1206 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE, 1207 APInt::getAllOnesValue( 1208 C0->getType()->getScalarSizeInBits())))) 1209 return nullptr; // Can't do, have all-ones element[s]. 1210 C0 = AddOne(C0); 1211 std::swap(X, Sel1); 1212 break; 1213 case ICmpInst::Predicate::ICMP_UGE: 1214 // The only way we'd get this predicate if this `icmp` has extra uses, 1215 // but then we won't be able to do this fold. 1216 return nullptr; 1217 default: 1218 return nullptr; // Unknown predicate. 1219 } 1220 1221 // Now that we've canonicalized the ICmp, we know the X we expect; 1222 // the select in other hand should be one-use. 1223 if (!Sel1->hasOneUse()) 1224 return nullptr; 1225 1226 // We now can finish matching the condition of the outermost select: 1227 // it should either be the X itself, or an addition of some constant to X. 1228 Constant *C1; 1229 if (Cmp00 == X) 1230 C1 = ConstantInt::getNullValue(Sel0.getType()); 1231 else if (!match(Cmp00, 1232 m_Add(m_Specific(X), 1233 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C1))))) 1234 return nullptr; 1235 1236 Value *Cmp1; 1237 ICmpInst::Predicate Pred1; 1238 Constant *C2; 1239 Value *ReplacementLow, *ReplacementHigh; 1240 if (!match(Sel1, m_Select(m_Value(Cmp1), m_Value(ReplacementLow), 1241 m_Value(ReplacementHigh))) || 1242 !match(Cmp1, 1243 m_ICmp(Pred1, m_Specific(X), 1244 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C2))))) 1245 return nullptr; 1246 1247 if (!Cmp1->hasOneUse() && (Cmp00 == X || !Cmp00->hasOneUse())) 1248 return nullptr; // Not enough one-use instructions for the fold. 1249 // FIXME: this restriction could be relaxed if Cmp1 can be reused as one of 1250 // two comparisons we'll need to build. 1251 1252 // Canonicalize Cmp1 into the form we expect. 1253 // FIXME: we shouldn't care about lanes that are 'undef' in the end? 1254 switch (Pred1) { 1255 case ICmpInst::Predicate::ICMP_SLT: 1256 break; 1257 case ICmpInst::Predicate::ICMP_SLE: 1258 // We'd have to increment C2 by one, and for that it must not have signed 1259 // max element, but then it would have been canonicalized to 'slt' before 1260 // we get here. So we can't do anything useful with 'sle'. 1261 return nullptr; 1262 case ICmpInst::Predicate::ICMP_SGT: 1263 // We want to canonicalize it to 'slt', so we'll need to increment C2, 1264 // which again means it must not have any signed max elements. 1265 if (!match(C2, 1266 m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_NE, 1267 APInt::getSignedMaxValue( 1268 C2->getType()->getScalarSizeInBits())))) 1269 return nullptr; // Can't do, have signed max element[s]. 1270 C2 = AddOne(C2); 1271 LLVM_FALLTHROUGH; 1272 case ICmpInst::Predicate::ICMP_SGE: 1273 // Also non-canonical, but here we don't need to change C2, 1274 // so we don't have any restrictions on C2, so we can just handle it. 1275 std::swap(ReplacementLow, ReplacementHigh); 1276 break; 1277 default: 1278 return nullptr; // Unknown predicate. 1279 } 1280 1281 // The thresholds of this clamp-like pattern. 1282 auto *ThresholdLowIncl = ConstantExpr::getNeg(C1); 1283 auto *ThresholdHighExcl = ConstantExpr::getSub(C0, C1); 1284 1285 // The fold has a precondition 1: C2 s>= ThresholdLow 1286 auto *Precond1 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SGE, C2, 1287 ThresholdLowIncl); 1288 if (!match(Precond1, m_One())) 1289 return nullptr; 1290 // The fold has a precondition 2: C2 s<= ThresholdHigh 1291 auto *Precond2 = ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_SLE, C2, 1292 ThresholdHighExcl); 1293 if (!match(Precond2, m_One())) 1294 return nullptr; 1295 1296 // All good, finally emit the new pattern. 1297 Value *ShouldReplaceLow = Builder.CreateICmpSLT(X, ThresholdLowIncl); 1298 Value *ShouldReplaceHigh = Builder.CreateICmpSGE(X, ThresholdHighExcl); 1299 Value *MaybeReplacedLow = 1300 Builder.CreateSelect(ShouldReplaceLow, ReplacementLow, X); 1301 Instruction *MaybeReplacedHigh = 1302 SelectInst::Create(ShouldReplaceHigh, ReplacementHigh, MaybeReplacedLow); 1303 1304 return MaybeReplacedHigh; 1305 } 1306 1307 // If we have 1308 // %cmp = icmp [canonical predicate] i32 %x, C0 1309 // %r = select i1 %cmp, i32 %y, i32 C1 1310 // Where C0 != C1 and %x may be different from %y, see if the constant that we 1311 // will have if we flip the strictness of the predicate (i.e. without changing 1312 // the result) is identical to the C1 in select. If it matches we can change 1313 // original comparison to one with swapped predicate, reuse the constant, 1314 // and swap the hands of select. 1315 static Instruction * 1316 tryToReuseConstantFromSelectInComparison(SelectInst &Sel, ICmpInst &Cmp, 1317 InstCombiner::BuilderTy &Builder) { 1318 ICmpInst::Predicate Pred; 1319 Value *X; 1320 Constant *C0; 1321 if (!match(&Cmp, m_OneUse(m_ICmp( 1322 Pred, m_Value(X), 1323 m_CombineAnd(m_AnyIntegralConstant(), m_Constant(C0)))))) 1324 return nullptr; 1325 1326 // If comparison predicate is non-relational, we won't be able to do anything. 1327 if (ICmpInst::isEquality(Pred)) 1328 return nullptr; 1329 1330 // If comparison predicate is non-canonical, then we certainly won't be able 1331 // to make it canonical; canonicalizeCmpWithConstant() already tried. 1332 if (!isCanonicalPredicate(Pred)) 1333 return nullptr; 1334 1335 // If the [input] type of comparison and select type are different, lets abort 1336 // for now. We could try to compare constants with trunc/[zs]ext though. 1337 if (C0->getType() != Sel.getType()) 1338 return nullptr; 1339 1340 // FIXME: are there any magic icmp predicate+constant pairs we must not touch? 1341 1342 Value *SelVal0, *SelVal1; // We do not care which one is from where. 1343 match(&Sel, m_Select(m_Value(), m_Value(SelVal0), m_Value(SelVal1))); 1344 // At least one of these values we are selecting between must be a constant 1345 // else we'll never succeed. 1346 if (!match(SelVal0, m_AnyIntegralConstant()) && 1347 !match(SelVal1, m_AnyIntegralConstant())) 1348 return nullptr; 1349 1350 // Does this constant C match any of the `select` values? 1351 auto MatchesSelectValue = [SelVal0, SelVal1](Constant *C) { 1352 return C->isElementWiseEqual(SelVal0) || C->isElementWiseEqual(SelVal1); 1353 }; 1354 1355 // If C0 *already* matches true/false value of select, we are done. 1356 if (MatchesSelectValue(C0)) 1357 return nullptr; 1358 1359 // Check the constant we'd have with flipped-strictness predicate. 1360 auto FlippedStrictness = getFlippedStrictnessPredicateAndConstant(Pred, C0); 1361 if (!FlippedStrictness) 1362 return nullptr; 1363 1364 // If said constant doesn't match either, then there is no hope, 1365 if (!MatchesSelectValue(FlippedStrictness->second)) 1366 return nullptr; 1367 1368 // It matched! Lets insert the new comparison just before select. 1369 InstCombiner::BuilderTy::InsertPointGuard Guard(Builder); 1370 Builder.SetInsertPoint(&Sel); 1371 1372 Pred = ICmpInst::getSwappedPredicate(Pred); // Yes, swapped. 1373 Value *NewCmp = Builder.CreateICmp(Pred, X, FlippedStrictness->second, 1374 Cmp.getName() + ".inv"); 1375 Sel.setCondition(NewCmp); 1376 Sel.swapValues(); 1377 Sel.swapProfMetadata(); 1378 1379 return &Sel; 1380 } 1381 1382 /// Visit a SelectInst that has an ICmpInst as its first operand. 1383 Instruction *InstCombiner::foldSelectInstWithICmp(SelectInst &SI, 1384 ICmpInst *ICI) { 1385 if (Value *V = foldSelectValueEquivalence(SI, *ICI, SQ)) 1386 return replaceInstUsesWith(SI, V); 1387 1388 if (Instruction *NewSel = canonicalizeMinMaxWithConstant(SI, *ICI, Builder)) 1389 return NewSel; 1390 1391 if (Instruction *NewAbs = canonicalizeAbsNabs(SI, *ICI, Builder)) 1392 return NewAbs; 1393 1394 if (Instruction *NewAbs = canonicalizeClampLike(SI, *ICI, Builder)) 1395 return NewAbs; 1396 1397 if (Instruction *NewSel = 1398 tryToReuseConstantFromSelectInComparison(SI, *ICI, Builder)) 1399 return NewSel; 1400 1401 bool Changed = adjustMinMax(SI, *ICI); 1402 1403 if (Value *V = foldSelectICmpAnd(SI, ICI, Builder)) 1404 return replaceInstUsesWith(SI, V); 1405 1406 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 1407 Value *TrueVal = SI.getTrueValue(); 1408 Value *FalseVal = SI.getFalseValue(); 1409 ICmpInst::Predicate Pred = ICI->getPredicate(); 1410 Value *CmpLHS = ICI->getOperand(0); 1411 Value *CmpRHS = ICI->getOperand(1); 1412 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 1413 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 1414 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 1415 SI.setOperand(1, CmpRHS); 1416 Changed = true; 1417 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 1418 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 1419 SI.setOperand(2, CmpRHS); 1420 Changed = true; 1421 } 1422 } 1423 1424 // FIXME: This code is nearly duplicated in InstSimplify. Using/refactoring 1425 // decomposeBitTestICmp() might help. 1426 { 1427 unsigned BitWidth = 1428 DL.getTypeSizeInBits(TrueVal->getType()->getScalarType()); 1429 APInt MinSignedValue = APInt::getSignedMinValue(BitWidth); 1430 Value *X; 1431 const APInt *Y, *C; 1432 bool TrueWhenUnset; 1433 bool IsBitTest = false; 1434 if (ICmpInst::isEquality(Pred) && 1435 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) && 1436 match(CmpRHS, m_Zero())) { 1437 IsBitTest = true; 1438 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ; 1439 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) { 1440 X = CmpLHS; 1441 Y = &MinSignedValue; 1442 IsBitTest = true; 1443 TrueWhenUnset = false; 1444 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) { 1445 X = CmpLHS; 1446 Y = &MinSignedValue; 1447 IsBitTest = true; 1448 TrueWhenUnset = true; 1449 } 1450 if (IsBitTest) { 1451 Value *V = nullptr; 1452 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y 1453 if (TrueWhenUnset && TrueVal == X && 1454 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1455 V = Builder.CreateAnd(X, ~(*Y)); 1456 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y 1457 else if (!TrueWhenUnset && FalseVal == X && 1458 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1459 V = Builder.CreateAnd(X, ~(*Y)); 1460 // (X & Y) == 0 ? X ^ Y : X --> X | Y 1461 else if (TrueWhenUnset && FalseVal == X && 1462 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1463 V = Builder.CreateOr(X, *Y); 1464 // (X & Y) != 0 ? X : X ^ Y --> X | Y 1465 else if (!TrueWhenUnset && TrueVal == X && 1466 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 1467 V = Builder.CreateOr(X, *Y); 1468 1469 if (V) 1470 return replaceInstUsesWith(SI, V); 1471 } 1472 } 1473 1474 if (Instruction *V = 1475 foldSelectICmpAndAnd(SI.getType(), ICI, TrueVal, FalseVal, Builder)) 1476 return V; 1477 1478 if (Instruction *V = foldSelectCtlzToCttz(ICI, TrueVal, FalseVal, Builder)) 1479 return V; 1480 1481 if (Value *V = foldSelectICmpAndOr(ICI, TrueVal, FalseVal, Builder)) 1482 return replaceInstUsesWith(SI, V); 1483 1484 if (Value *V = foldSelectICmpLshrAshr(ICI, TrueVal, FalseVal, Builder)) 1485 return replaceInstUsesWith(SI, V); 1486 1487 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder)) 1488 return replaceInstUsesWith(SI, V); 1489 1490 if (Value *V = canonicalizeSaturatedSubtract(ICI, TrueVal, FalseVal, Builder)) 1491 return replaceInstUsesWith(SI, V); 1492 1493 if (Value *V = canonicalizeSaturatedAdd(ICI, TrueVal, FalseVal, Builder)) 1494 return replaceInstUsesWith(SI, V); 1495 1496 return Changed ? &SI : nullptr; 1497 } 1498 1499 /// SI is a select whose condition is a PHI node (but the two may be in 1500 /// different blocks). See if the true/false values (V) are live in all of the 1501 /// predecessor blocks of the PHI. For example, cases like this can't be mapped: 1502 /// 1503 /// X = phi [ C1, BB1], [C2, BB2] 1504 /// Y = add 1505 /// Z = select X, Y, 0 1506 /// 1507 /// because Y is not live in BB1/BB2. 1508 static bool canSelectOperandBeMappingIntoPredBlock(const Value *V, 1509 const SelectInst &SI) { 1510 // If the value is a non-instruction value like a constant or argument, it 1511 // can always be mapped. 1512 const Instruction *I = dyn_cast<Instruction>(V); 1513 if (!I) return true; 1514 1515 // If V is a PHI node defined in the same block as the condition PHI, we can 1516 // map the arguments. 1517 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 1518 1519 if (const PHINode *VP = dyn_cast<PHINode>(I)) 1520 if (VP->getParent() == CondPHI->getParent()) 1521 return true; 1522 1523 // Otherwise, if the PHI and select are defined in the same block and if V is 1524 // defined in a different block, then we can transform it. 1525 if (SI.getParent() == CondPHI->getParent() && 1526 I->getParent() != CondPHI->getParent()) 1527 return true; 1528 1529 // Otherwise we have a 'hard' case and we can't tell without doing more 1530 // detailed dominator based analysis, punt. 1531 return false; 1532 } 1533 1534 /// We have an SPF (e.g. a min or max) of an SPF of the form: 1535 /// SPF2(SPF1(A, B), C) 1536 Instruction *InstCombiner::foldSPFofSPF(Instruction *Inner, 1537 SelectPatternFlavor SPF1, 1538 Value *A, Value *B, 1539 Instruction &Outer, 1540 SelectPatternFlavor SPF2, Value *C) { 1541 if (Outer.getType() != Inner->getType()) 1542 return nullptr; 1543 1544 if (C == A || C == B) { 1545 // MAX(MAX(A, B), B) -> MAX(A, B) 1546 // MIN(MIN(a, b), a) -> MIN(a, b) 1547 // TODO: This could be done in instsimplify. 1548 if (SPF1 == SPF2 && SelectPatternResult::isMinOrMax(SPF1)) 1549 return replaceInstUsesWith(Outer, Inner); 1550 1551 // MAX(MIN(a, b), a) -> a 1552 // MIN(MAX(a, b), a) -> a 1553 // TODO: This could be done in instsimplify. 1554 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 1555 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 1556 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 1557 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 1558 return replaceInstUsesWith(Outer, C); 1559 } 1560 1561 if (SPF1 == SPF2) { 1562 const APInt *CB, *CC; 1563 if (match(B, m_APInt(CB)) && match(C, m_APInt(CC))) { 1564 // MIN(MIN(A, 23), 97) -> MIN(A, 23) 1565 // MAX(MAX(A, 97), 23) -> MAX(A, 97) 1566 // TODO: This could be done in instsimplify. 1567 if ((SPF1 == SPF_UMIN && CB->ule(*CC)) || 1568 (SPF1 == SPF_SMIN && CB->sle(*CC)) || 1569 (SPF1 == SPF_UMAX && CB->uge(*CC)) || 1570 (SPF1 == SPF_SMAX && CB->sge(*CC))) 1571 return replaceInstUsesWith(Outer, Inner); 1572 1573 // MIN(MIN(A, 97), 23) -> MIN(A, 23) 1574 // MAX(MAX(A, 23), 97) -> MAX(A, 97) 1575 if ((SPF1 == SPF_UMIN && CB->ugt(*CC)) || 1576 (SPF1 == SPF_SMIN && CB->sgt(*CC)) || 1577 (SPF1 == SPF_UMAX && CB->ult(*CC)) || 1578 (SPF1 == SPF_SMAX && CB->slt(*CC))) { 1579 Outer.replaceUsesOfWith(Inner, A); 1580 return &Outer; 1581 } 1582 } 1583 } 1584 1585 // max(max(A, B), min(A, B)) --> max(A, B) 1586 // min(min(A, B), max(A, B)) --> min(A, B) 1587 // TODO: This could be done in instsimplify. 1588 if (SPF1 == SPF2 && 1589 ((SPF1 == SPF_UMIN && match(C, m_c_UMax(m_Specific(A), m_Specific(B)))) || 1590 (SPF1 == SPF_SMIN && match(C, m_c_SMax(m_Specific(A), m_Specific(B)))) || 1591 (SPF1 == SPF_UMAX && match(C, m_c_UMin(m_Specific(A), m_Specific(B)))) || 1592 (SPF1 == SPF_SMAX && match(C, m_c_SMin(m_Specific(A), m_Specific(B)))))) 1593 return replaceInstUsesWith(Outer, Inner); 1594 1595 // ABS(ABS(X)) -> ABS(X) 1596 // NABS(NABS(X)) -> NABS(X) 1597 // TODO: This could be done in instsimplify. 1598 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) { 1599 return replaceInstUsesWith(Outer, Inner); 1600 } 1601 1602 // ABS(NABS(X)) -> ABS(X) 1603 // NABS(ABS(X)) -> NABS(X) 1604 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) || 1605 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) { 1606 SelectInst *SI = cast<SelectInst>(Inner); 1607 Value *NewSI = 1608 Builder.CreateSelect(SI->getCondition(), SI->getFalseValue(), 1609 SI->getTrueValue(), SI->getName(), SI); 1610 return replaceInstUsesWith(Outer, NewSI); 1611 } 1612 1613 auto IsFreeOrProfitableToInvert = 1614 [&](Value *V, Value *&NotV, bool &ElidesXor) { 1615 if (match(V, m_Not(m_Value(NotV)))) { 1616 // If V has at most 2 uses then we can get rid of the xor operation 1617 // entirely. 1618 ElidesXor |= !V->hasNUsesOrMore(3); 1619 return true; 1620 } 1621 1622 if (isFreeToInvert(V, !V->hasNUsesOrMore(3))) { 1623 NotV = nullptr; 1624 return true; 1625 } 1626 1627 return false; 1628 }; 1629 1630 Value *NotA, *NotB, *NotC; 1631 bool ElidesXor = false; 1632 1633 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C) 1634 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C) 1635 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C) 1636 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C) 1637 // 1638 // This transform is performance neutral if we can elide at least one xor from 1639 // the set of three operands, since we'll be tacking on an xor at the very 1640 // end. 1641 if (SelectPatternResult::isMinOrMax(SPF1) && 1642 SelectPatternResult::isMinOrMax(SPF2) && 1643 IsFreeOrProfitableToInvert(A, NotA, ElidesXor) && 1644 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) && 1645 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) { 1646 if (!NotA) 1647 NotA = Builder.CreateNot(A); 1648 if (!NotB) 1649 NotB = Builder.CreateNot(B); 1650 if (!NotC) 1651 NotC = Builder.CreateNot(C); 1652 1653 Value *NewInner = createMinMax(Builder, getInverseMinMaxFlavor(SPF1), NotA, 1654 NotB); 1655 Value *NewOuter = Builder.CreateNot( 1656 createMinMax(Builder, getInverseMinMaxFlavor(SPF2), NewInner, NotC)); 1657 return replaceInstUsesWith(Outer, NewOuter); 1658 } 1659 1660 return nullptr; 1661 } 1662 1663 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))). 1664 /// This is even legal for FP. 1665 static Instruction *foldAddSubSelect(SelectInst &SI, 1666 InstCombiner::BuilderTy &Builder) { 1667 Value *CondVal = SI.getCondition(); 1668 Value *TrueVal = SI.getTrueValue(); 1669 Value *FalseVal = SI.getFalseValue(); 1670 auto *TI = dyn_cast<Instruction>(TrueVal); 1671 auto *FI = dyn_cast<Instruction>(FalseVal); 1672 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse()) 1673 return nullptr; 1674 1675 Instruction *AddOp = nullptr, *SubOp = nullptr; 1676 if ((TI->getOpcode() == Instruction::Sub && 1677 FI->getOpcode() == Instruction::Add) || 1678 (TI->getOpcode() == Instruction::FSub && 1679 FI->getOpcode() == Instruction::FAdd)) { 1680 AddOp = FI; 1681 SubOp = TI; 1682 } else if ((FI->getOpcode() == Instruction::Sub && 1683 TI->getOpcode() == Instruction::Add) || 1684 (FI->getOpcode() == Instruction::FSub && 1685 TI->getOpcode() == Instruction::FAdd)) { 1686 AddOp = TI; 1687 SubOp = FI; 1688 } 1689 1690 if (AddOp) { 1691 Value *OtherAddOp = nullptr; 1692 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 1693 OtherAddOp = AddOp->getOperand(1); 1694 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 1695 OtherAddOp = AddOp->getOperand(0); 1696 } 1697 1698 if (OtherAddOp) { 1699 // So at this point we know we have (Y -> OtherAddOp): 1700 // select C, (add X, Y), (sub X, Z) 1701 Value *NegVal; // Compute -Z 1702 if (SI.getType()->isFPOrFPVectorTy()) { 1703 NegVal = Builder.CreateFNeg(SubOp->getOperand(1)); 1704 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 1705 FastMathFlags Flags = AddOp->getFastMathFlags(); 1706 Flags &= SubOp->getFastMathFlags(); 1707 NegInst->setFastMathFlags(Flags); 1708 } 1709 } else { 1710 NegVal = Builder.CreateNeg(SubOp->getOperand(1)); 1711 } 1712 1713 Value *NewTrueOp = OtherAddOp; 1714 Value *NewFalseOp = NegVal; 1715 if (AddOp != TI) 1716 std::swap(NewTrueOp, NewFalseOp); 1717 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp, 1718 SI.getName() + ".p", &SI); 1719 1720 if (SI.getType()->isFPOrFPVectorTy()) { 1721 Instruction *RI = 1722 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 1723 1724 FastMathFlags Flags = AddOp->getFastMathFlags(); 1725 Flags &= SubOp->getFastMathFlags(); 1726 RI->setFastMathFlags(Flags); 1727 return RI; 1728 } else 1729 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 1730 } 1731 } 1732 return nullptr; 1733 } 1734 1735 /// Turn X + Y overflows ? -1 : X + Y -> uadd_sat X, Y 1736 /// And X - Y overflows ? 0 : X - Y -> usub_sat X, Y 1737 /// Along with a number of patterns similar to: 1738 /// X + Y overflows ? (X < 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1739 /// X - Y overflows ? (X > 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1740 static Instruction * 1741 foldOverflowingAddSubSelect(SelectInst &SI, InstCombiner::BuilderTy &Builder) { 1742 Value *CondVal = SI.getCondition(); 1743 Value *TrueVal = SI.getTrueValue(); 1744 Value *FalseVal = SI.getFalseValue(); 1745 1746 WithOverflowInst *II; 1747 if (!match(CondVal, m_ExtractValue<1>(m_WithOverflowInst(II))) || 1748 !match(FalseVal, m_ExtractValue<0>(m_Specific(II)))) 1749 return nullptr; 1750 1751 Value *X = II->getLHS(); 1752 Value *Y = II->getRHS(); 1753 1754 auto IsSignedSaturateLimit = [&](Value *Limit, bool IsAdd) { 1755 Type *Ty = Limit->getType(); 1756 1757 ICmpInst::Predicate Pred; 1758 Value *TrueVal, *FalseVal, *Op; 1759 const APInt *C; 1760 if (!match(Limit, m_Select(m_ICmp(Pred, m_Value(Op), m_APInt(C)), 1761 m_Value(TrueVal), m_Value(FalseVal)))) 1762 return false; 1763 1764 auto IsZeroOrOne = [](const APInt &C) { 1765 return C.isNullValue() || C.isOneValue(); 1766 }; 1767 auto IsMinMax = [&](Value *Min, Value *Max) { 1768 APInt MinVal = APInt::getSignedMinValue(Ty->getScalarSizeInBits()); 1769 APInt MaxVal = APInt::getSignedMaxValue(Ty->getScalarSizeInBits()); 1770 return match(Min, m_SpecificInt(MinVal)) && 1771 match(Max, m_SpecificInt(MaxVal)); 1772 }; 1773 1774 if (Op != X && Op != Y) 1775 return false; 1776 1777 if (IsAdd) { 1778 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1779 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1780 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1781 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1782 if (Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) && 1783 IsMinMax(TrueVal, FalseVal)) 1784 return true; 1785 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1786 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1787 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1788 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1789 if (Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) && 1790 IsMinMax(FalseVal, TrueVal)) 1791 return true; 1792 } else { 1793 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1794 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1795 if (Op == X && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C + 1) && 1796 IsMinMax(TrueVal, FalseVal)) 1797 return true; 1798 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1799 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1800 if (Op == X && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 2) && 1801 IsMinMax(FalseVal, TrueVal)) 1802 return true; 1803 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1804 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1805 if (Op == Y && Pred == ICmpInst::ICMP_SLT && IsZeroOrOne(*C) && 1806 IsMinMax(FalseVal, TrueVal)) 1807 return true; 1808 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1809 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1810 if (Op == Y && Pred == ICmpInst::ICMP_SGT && IsZeroOrOne(*C + 1) && 1811 IsMinMax(TrueVal, FalseVal)) 1812 return true; 1813 } 1814 1815 return false; 1816 }; 1817 1818 Intrinsic::ID NewIntrinsicID; 1819 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow && 1820 match(TrueVal, m_AllOnes())) 1821 // X + Y overflows ? -1 : X + Y -> uadd_sat X, Y 1822 NewIntrinsicID = Intrinsic::uadd_sat; 1823 else if (II->getIntrinsicID() == Intrinsic::usub_with_overflow && 1824 match(TrueVal, m_Zero())) 1825 // X - Y overflows ? 0 : X - Y -> usub_sat X, Y 1826 NewIntrinsicID = Intrinsic::usub_sat; 1827 else if (II->getIntrinsicID() == Intrinsic::sadd_with_overflow && 1828 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/true)) 1829 // X + Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1830 // X + Y overflows ? (X <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1831 // X + Y overflows ? (X >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1832 // X + Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1833 // X + Y overflows ? (Y <s 0 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1834 // X + Y overflows ? (Y <s 1 ? INTMIN : INTMAX) : X + Y --> sadd_sat X, Y 1835 // X + Y overflows ? (Y >s 0 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1836 // X + Y overflows ? (Y >s -1 ? INTMAX : INTMIN) : X + Y --> sadd_sat X, Y 1837 NewIntrinsicID = Intrinsic::sadd_sat; 1838 else if (II->getIntrinsicID() == Intrinsic::ssub_with_overflow && 1839 IsSignedSaturateLimit(TrueVal, /*IsAdd=*/false)) 1840 // X - Y overflows ? (X <s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1841 // X - Y overflows ? (X <s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1842 // X - Y overflows ? (X >s -1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1843 // X - Y overflows ? (X >s -2 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1844 // X - Y overflows ? (Y <s 0 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1845 // X - Y overflows ? (Y <s 1 ? INTMAX : INTMIN) : X - Y --> ssub_sat X, Y 1846 // X - Y overflows ? (Y >s 0 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1847 // X - Y overflows ? (Y >s -1 ? INTMIN : INTMAX) : X - Y --> ssub_sat X, Y 1848 NewIntrinsicID = Intrinsic::ssub_sat; 1849 else 1850 return nullptr; 1851 1852 Function *F = 1853 Intrinsic::getDeclaration(SI.getModule(), NewIntrinsicID, SI.getType()); 1854 return CallInst::Create(F, {X, Y}); 1855 } 1856 1857 Instruction *InstCombiner::foldSelectExtConst(SelectInst &Sel) { 1858 Constant *C; 1859 if (!match(Sel.getTrueValue(), m_Constant(C)) && 1860 !match(Sel.getFalseValue(), m_Constant(C))) 1861 return nullptr; 1862 1863 Instruction *ExtInst; 1864 if (!match(Sel.getTrueValue(), m_Instruction(ExtInst)) && 1865 !match(Sel.getFalseValue(), m_Instruction(ExtInst))) 1866 return nullptr; 1867 1868 auto ExtOpcode = ExtInst->getOpcode(); 1869 if (ExtOpcode != Instruction::ZExt && ExtOpcode != Instruction::SExt) 1870 return nullptr; 1871 1872 // If we are extending from a boolean type or if we can create a select that 1873 // has the same size operands as its condition, try to narrow the select. 1874 Value *X = ExtInst->getOperand(0); 1875 Type *SmallType = X->getType(); 1876 Value *Cond = Sel.getCondition(); 1877 auto *Cmp = dyn_cast<CmpInst>(Cond); 1878 if (!SmallType->isIntOrIntVectorTy(1) && 1879 (!Cmp || Cmp->getOperand(0)->getType() != SmallType)) 1880 return nullptr; 1881 1882 // If the constant is the same after truncation to the smaller type and 1883 // extension to the original type, we can narrow the select. 1884 Type *SelType = Sel.getType(); 1885 Constant *TruncC = ConstantExpr::getTrunc(C, SmallType); 1886 Constant *ExtC = ConstantExpr::getCast(ExtOpcode, TruncC, SelType); 1887 if (ExtC == C) { 1888 Value *TruncCVal = cast<Value>(TruncC); 1889 if (ExtInst == Sel.getFalseValue()) 1890 std::swap(X, TruncCVal); 1891 1892 // select Cond, (ext X), C --> ext(select Cond, X, C') 1893 // select Cond, C, (ext X) --> ext(select Cond, C', X) 1894 Value *NewSel = Builder.CreateSelect(Cond, X, TruncCVal, "narrow", &Sel); 1895 return CastInst::Create(Instruction::CastOps(ExtOpcode), NewSel, SelType); 1896 } 1897 1898 // If one arm of the select is the extend of the condition, replace that arm 1899 // with the extension of the appropriate known bool value. 1900 if (Cond == X) { 1901 if (ExtInst == Sel.getTrueValue()) { 1902 // select X, (sext X), C --> select X, -1, C 1903 // select X, (zext X), C --> select X, 1, C 1904 Constant *One = ConstantInt::getTrue(SmallType); 1905 Constant *AllOnesOrOne = ConstantExpr::getCast(ExtOpcode, One, SelType); 1906 return SelectInst::Create(Cond, AllOnesOrOne, C, "", nullptr, &Sel); 1907 } else { 1908 // select X, C, (sext X) --> select X, C, 0 1909 // select X, C, (zext X) --> select X, C, 0 1910 Constant *Zero = ConstantInt::getNullValue(SelType); 1911 return SelectInst::Create(Cond, C, Zero, "", nullptr, &Sel); 1912 } 1913 } 1914 1915 return nullptr; 1916 } 1917 1918 /// Try to transform a vector select with a constant condition vector into a 1919 /// shuffle for easier combining with other shuffles and insert/extract. 1920 static Instruction *canonicalizeSelectToShuffle(SelectInst &SI) { 1921 Value *CondVal = SI.getCondition(); 1922 Constant *CondC; 1923 if (!CondVal->getType()->isVectorTy() || !match(CondVal, m_Constant(CondC))) 1924 return nullptr; 1925 1926 unsigned NumElts = CondVal->getType()->getVectorNumElements(); 1927 SmallVector<Constant *, 16> Mask; 1928 Mask.reserve(NumElts); 1929 Type *Int32Ty = Type::getInt32Ty(CondVal->getContext()); 1930 for (unsigned i = 0; i != NumElts; ++i) { 1931 Constant *Elt = CondC->getAggregateElement(i); 1932 if (!Elt) 1933 return nullptr; 1934 1935 if (Elt->isOneValue()) { 1936 // If the select condition element is true, choose from the 1st vector. 1937 Mask.push_back(ConstantInt::get(Int32Ty, i)); 1938 } else if (Elt->isNullValue()) { 1939 // If the select condition element is false, choose from the 2nd vector. 1940 Mask.push_back(ConstantInt::get(Int32Ty, i + NumElts)); 1941 } else if (isa<UndefValue>(Elt)) { 1942 // Undef in a select condition (choose one of the operands) does not mean 1943 // the same thing as undef in a shuffle mask (any value is acceptable), so 1944 // give up. 1945 return nullptr; 1946 } else { 1947 // Bail out on a constant expression. 1948 return nullptr; 1949 } 1950 } 1951 1952 return new ShuffleVectorInst(SI.getTrueValue(), SI.getFalseValue(), 1953 ConstantVector::get(Mask)); 1954 } 1955 1956 /// If we have a select of vectors with a scalar condition, try to convert that 1957 /// to a vector select by splatting the condition. A splat may get folded with 1958 /// other operations in IR and having all operands of a select be vector types 1959 /// is likely better for vector codegen. 1960 static Instruction *canonicalizeScalarSelectOfVecs( 1961 SelectInst &Sel, InstCombiner::BuilderTy &Builder) { 1962 Type *Ty = Sel.getType(); 1963 if (!Ty->isVectorTy()) 1964 return nullptr; 1965 1966 // We can replace a single-use extract with constant index. 1967 Value *Cond = Sel.getCondition(); 1968 if (!match(Cond, m_OneUse(m_ExtractElement(m_Value(), m_ConstantInt())))) 1969 return nullptr; 1970 1971 // select (extelt V, Index), T, F --> select (splat V, Index), T, F 1972 // Splatting the extracted condition reduces code (we could directly create a 1973 // splat shuffle of the source vector to eliminate the intermediate step). 1974 unsigned NumElts = Ty->getVectorNumElements(); 1975 Value *SplatCond = Builder.CreateVectorSplat(NumElts, Cond); 1976 Sel.setCondition(SplatCond); 1977 return &Sel; 1978 } 1979 1980 /// Reuse bitcasted operands between a compare and select: 1981 /// select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 1982 /// bitcast (select (cmp (bitcast C), (bitcast D)), (bitcast C), (bitcast D)) 1983 static Instruction *foldSelectCmpBitcasts(SelectInst &Sel, 1984 InstCombiner::BuilderTy &Builder) { 1985 Value *Cond = Sel.getCondition(); 1986 Value *TVal = Sel.getTrueValue(); 1987 Value *FVal = Sel.getFalseValue(); 1988 1989 CmpInst::Predicate Pred; 1990 Value *A, *B; 1991 if (!match(Cond, m_Cmp(Pred, m_Value(A), m_Value(B)))) 1992 return nullptr; 1993 1994 // The select condition is a compare instruction. If the select's true/false 1995 // values are already the same as the compare operands, there's nothing to do. 1996 if (TVal == A || TVal == B || FVal == A || FVal == B) 1997 return nullptr; 1998 1999 Value *C, *D; 2000 if (!match(A, m_BitCast(m_Value(C))) || !match(B, m_BitCast(m_Value(D)))) 2001 return nullptr; 2002 2003 // select (cmp (bitcast C), (bitcast D)), (bitcast TSrc), (bitcast FSrc) 2004 Value *TSrc, *FSrc; 2005 if (!match(TVal, m_BitCast(m_Value(TSrc))) || 2006 !match(FVal, m_BitCast(m_Value(FSrc)))) 2007 return nullptr; 2008 2009 // If the select true/false values are *different bitcasts* of the same source 2010 // operands, make the select operands the same as the compare operands and 2011 // cast the result. This is the canonical select form for min/max. 2012 Value *NewSel; 2013 if (TSrc == C && FSrc == D) { 2014 // select (cmp (bitcast C), (bitcast D)), (bitcast' C), (bitcast' D) --> 2015 // bitcast (select (cmp A, B), A, B) 2016 NewSel = Builder.CreateSelect(Cond, A, B, "", &Sel); 2017 } else if (TSrc == D && FSrc == C) { 2018 // select (cmp (bitcast C), (bitcast D)), (bitcast' D), (bitcast' C) --> 2019 // bitcast (select (cmp A, B), B, A) 2020 NewSel = Builder.CreateSelect(Cond, B, A, "", &Sel); 2021 } else { 2022 return nullptr; 2023 } 2024 return CastInst::CreateBitOrPointerCast(NewSel, Sel.getType()); 2025 } 2026 2027 /// Try to eliminate select instructions that test the returned flag of cmpxchg 2028 /// instructions. 2029 /// 2030 /// If a select instruction tests the returned flag of a cmpxchg instruction and 2031 /// selects between the returned value of the cmpxchg instruction its compare 2032 /// operand, the result of the select will always be equal to its false value. 2033 /// For example: 2034 /// 2035 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 2036 /// %1 = extractvalue { i64, i1 } %0, 1 2037 /// %2 = extractvalue { i64, i1 } %0, 0 2038 /// %3 = select i1 %1, i64 %compare, i64 %2 2039 /// ret i64 %3 2040 /// 2041 /// The returned value of the cmpxchg instruction (%2) is the original value 2042 /// located at %ptr prior to any update. If the cmpxchg operation succeeds, %2 2043 /// must have been equal to %compare. Thus, the result of the select is always 2044 /// equal to %2, and the code can be simplified to: 2045 /// 2046 /// %0 = cmpxchg i64* %ptr, i64 %compare, i64 %new_value seq_cst seq_cst 2047 /// %1 = extractvalue { i64, i1 } %0, 0 2048 /// ret i64 %1 2049 /// 2050 static Instruction *foldSelectCmpXchg(SelectInst &SI) { 2051 // A helper that determines if V is an extractvalue instruction whose 2052 // aggregate operand is a cmpxchg instruction and whose single index is equal 2053 // to I. If such conditions are true, the helper returns the cmpxchg 2054 // instruction; otherwise, a nullptr is returned. 2055 auto isExtractFromCmpXchg = [](Value *V, unsigned I) -> AtomicCmpXchgInst * { 2056 auto *Extract = dyn_cast<ExtractValueInst>(V); 2057 if (!Extract) 2058 return nullptr; 2059 if (Extract->getIndices()[0] != I) 2060 return nullptr; 2061 return dyn_cast<AtomicCmpXchgInst>(Extract->getAggregateOperand()); 2062 }; 2063 2064 // If the select has a single user, and this user is a select instruction that 2065 // we can simplify, skip the cmpxchg simplification for now. 2066 if (SI.hasOneUse()) 2067 if (auto *Select = dyn_cast<SelectInst>(SI.user_back())) 2068 if (Select->getCondition() == SI.getCondition()) 2069 if (Select->getFalseValue() == SI.getTrueValue() || 2070 Select->getTrueValue() == SI.getFalseValue()) 2071 return nullptr; 2072 2073 // Ensure the select condition is the returned flag of a cmpxchg instruction. 2074 auto *CmpXchg = isExtractFromCmpXchg(SI.getCondition(), 1); 2075 if (!CmpXchg) 2076 return nullptr; 2077 2078 // Check the true value case: The true value of the select is the returned 2079 // value of the same cmpxchg used by the condition, and the false value is the 2080 // cmpxchg instruction's compare operand. 2081 if (auto *X = isExtractFromCmpXchg(SI.getTrueValue(), 0)) 2082 if (X == CmpXchg && X->getCompareOperand() == SI.getFalseValue()) { 2083 SI.setTrueValue(SI.getFalseValue()); 2084 return &SI; 2085 } 2086 2087 // Check the false value case: The false value of the select is the returned 2088 // value of the same cmpxchg used by the condition, and the true value is the 2089 // cmpxchg instruction's compare operand. 2090 if (auto *X = isExtractFromCmpXchg(SI.getFalseValue(), 0)) 2091 if (X == CmpXchg && X->getCompareOperand() == SI.getTrueValue()) { 2092 SI.setTrueValue(SI.getFalseValue()); 2093 return &SI; 2094 } 2095 2096 return nullptr; 2097 } 2098 2099 static Instruction *moveAddAfterMinMax(SelectPatternFlavor SPF, Value *X, 2100 Value *Y, 2101 InstCombiner::BuilderTy &Builder) { 2102 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected min/max pattern"); 2103 bool IsUnsigned = SPF == SelectPatternFlavor::SPF_UMIN || 2104 SPF == SelectPatternFlavor::SPF_UMAX; 2105 // TODO: If InstSimplify could fold all cases where C2 <= C1, we could change 2106 // the constant value check to an assert. 2107 Value *A; 2108 const APInt *C1, *C2; 2109 if (IsUnsigned && match(X, m_NUWAdd(m_Value(A), m_APInt(C1))) && 2110 match(Y, m_APInt(C2)) && C2->uge(*C1) && X->hasNUses(2)) { 2111 // umin (add nuw A, C1), C2 --> add nuw (umin A, C2 - C1), C1 2112 // umax (add nuw A, C1), C2 --> add nuw (umax A, C2 - C1), C1 2113 Value *NewMinMax = createMinMax(Builder, SPF, A, 2114 ConstantInt::get(X->getType(), *C2 - *C1)); 2115 return BinaryOperator::CreateNUW(BinaryOperator::Add, NewMinMax, 2116 ConstantInt::get(X->getType(), *C1)); 2117 } 2118 2119 if (!IsUnsigned && match(X, m_NSWAdd(m_Value(A), m_APInt(C1))) && 2120 match(Y, m_APInt(C2)) && X->hasNUses(2)) { 2121 bool Overflow; 2122 APInt Diff = C2->ssub_ov(*C1, Overflow); 2123 if (!Overflow) { 2124 // smin (add nsw A, C1), C2 --> add nsw (smin A, C2 - C1), C1 2125 // smax (add nsw A, C1), C2 --> add nsw (smax A, C2 - C1), C1 2126 Value *NewMinMax = createMinMax(Builder, SPF, A, 2127 ConstantInt::get(X->getType(), Diff)); 2128 return BinaryOperator::CreateNSW(BinaryOperator::Add, NewMinMax, 2129 ConstantInt::get(X->getType(), *C1)); 2130 } 2131 } 2132 2133 return nullptr; 2134 } 2135 2136 /// Match a sadd_sat or ssub_sat which is using min/max to clamp the value. 2137 Instruction *InstCombiner::matchSAddSubSat(SelectInst &MinMax1) { 2138 Type *Ty = MinMax1.getType(); 2139 2140 // We are looking for a tree of: 2141 // max(INT_MIN, min(INT_MAX, add(sext(A), sext(B)))) 2142 // Where the min and max could be reversed 2143 Instruction *MinMax2; 2144 BinaryOperator *AddSub; 2145 const APInt *MinValue, *MaxValue; 2146 if (match(&MinMax1, m_SMin(m_Instruction(MinMax2), m_APInt(MaxValue)))) { 2147 if (!match(MinMax2, m_SMax(m_BinOp(AddSub), m_APInt(MinValue)))) 2148 return nullptr; 2149 } else if (match(&MinMax1, 2150 m_SMax(m_Instruction(MinMax2), m_APInt(MinValue)))) { 2151 if (!match(MinMax2, m_SMin(m_BinOp(AddSub), m_APInt(MaxValue)))) 2152 return nullptr; 2153 } else 2154 return nullptr; 2155 2156 // Check that the constants clamp a saturate, and that the new type would be 2157 // sensible to convert to. 2158 if (!(*MaxValue + 1).isPowerOf2() || -*MinValue != *MaxValue + 1) 2159 return nullptr; 2160 // In what bitwidth can this be treated as saturating arithmetics? 2161 unsigned NewBitWidth = (*MaxValue + 1).logBase2() + 1; 2162 // FIXME: This isn't quite right for vectors, but using the scalar type is a 2163 // good first approximation for what should be done there. 2164 if (!shouldChangeType(Ty->getScalarType()->getIntegerBitWidth(), NewBitWidth)) 2165 return nullptr; 2166 2167 // Also make sure that the number of uses is as expected. The "3"s are for the 2168 // the two items of min/max (the compare and the select). 2169 if (MinMax2->hasNUsesOrMore(3) || AddSub->hasNUsesOrMore(3)) 2170 return nullptr; 2171 2172 // Create the new type (which can be a vector type) 2173 Type *NewTy = Ty->getWithNewBitWidth(NewBitWidth); 2174 // Match the two extends from the add/sub 2175 Value *A, *B; 2176 if(!match(AddSub, m_BinOp(m_SExt(m_Value(A)), m_SExt(m_Value(B))))) 2177 return nullptr; 2178 // And check the incoming values are of a type smaller than or equal to the 2179 // size of the saturation. Otherwise the higher bits can cause different 2180 // results. 2181 if (A->getType()->getScalarSizeInBits() > NewBitWidth || 2182 B->getType()->getScalarSizeInBits() > NewBitWidth) 2183 return nullptr; 2184 2185 Intrinsic::ID IntrinsicID; 2186 if (AddSub->getOpcode() == Instruction::Add) 2187 IntrinsicID = Intrinsic::sadd_sat; 2188 else if (AddSub->getOpcode() == Instruction::Sub) 2189 IntrinsicID = Intrinsic::ssub_sat; 2190 else 2191 return nullptr; 2192 2193 // Finally create and return the sat intrinsic, truncated to the new type 2194 Function *F = Intrinsic::getDeclaration(MinMax1.getModule(), IntrinsicID, NewTy); 2195 Value *AT = Builder.CreateSExt(A, NewTy); 2196 Value *BT = Builder.CreateSExt(B, NewTy); 2197 Value *Sat = Builder.CreateCall(F, {AT, BT}); 2198 return CastInst::Create(Instruction::SExt, Sat, Ty); 2199 } 2200 2201 /// Reduce a sequence of min/max with a common operand. 2202 static Instruction *factorizeMinMaxTree(SelectPatternFlavor SPF, Value *LHS, 2203 Value *RHS, 2204 InstCombiner::BuilderTy &Builder) { 2205 assert(SelectPatternResult::isMinOrMax(SPF) && "Expected a min/max"); 2206 // TODO: Allow FP min/max with nnan/nsz. 2207 if (!LHS->getType()->isIntOrIntVectorTy()) 2208 return nullptr; 2209 2210 // Match 3 of the same min/max ops. Example: umin(umin(), umin()). 2211 Value *A, *B, *C, *D; 2212 SelectPatternResult L = matchSelectPattern(LHS, A, B); 2213 SelectPatternResult R = matchSelectPattern(RHS, C, D); 2214 if (SPF != L.Flavor || L.Flavor != R.Flavor) 2215 return nullptr; 2216 2217 // Look for a common operand. The use checks are different than usual because 2218 // a min/max pattern typically has 2 uses of each op: 1 by the cmp and 1 by 2219 // the select. 2220 Value *MinMaxOp = nullptr; 2221 Value *ThirdOp = nullptr; 2222 if (!LHS->hasNUsesOrMore(3) && RHS->hasNUsesOrMore(3)) { 2223 // If the LHS is only used in this chain and the RHS is used outside of it, 2224 // reuse the RHS min/max because that will eliminate the LHS. 2225 if (D == A || C == A) { 2226 // min(min(a, b), min(c, a)) --> min(min(c, a), b) 2227 // min(min(a, b), min(a, d)) --> min(min(a, d), b) 2228 MinMaxOp = RHS; 2229 ThirdOp = B; 2230 } else if (D == B || C == B) { 2231 // min(min(a, b), min(c, b)) --> min(min(c, b), a) 2232 // min(min(a, b), min(b, d)) --> min(min(b, d), a) 2233 MinMaxOp = RHS; 2234 ThirdOp = A; 2235 } 2236 } else if (!RHS->hasNUsesOrMore(3)) { 2237 // Reuse the LHS. This will eliminate the RHS. 2238 if (D == A || D == B) { 2239 // min(min(a, b), min(c, a)) --> min(min(a, b), c) 2240 // min(min(a, b), min(c, b)) --> min(min(a, b), c) 2241 MinMaxOp = LHS; 2242 ThirdOp = C; 2243 } else if (C == A || C == B) { 2244 // min(min(a, b), min(b, d)) --> min(min(a, b), d) 2245 // min(min(a, b), min(c, b)) --> min(min(a, b), d) 2246 MinMaxOp = LHS; 2247 ThirdOp = D; 2248 } 2249 } 2250 if (!MinMaxOp || !ThirdOp) 2251 return nullptr; 2252 2253 CmpInst::Predicate P = getMinMaxPred(SPF); 2254 Value *CmpABC = Builder.CreateICmp(P, MinMaxOp, ThirdOp); 2255 return SelectInst::Create(CmpABC, MinMaxOp, ThirdOp); 2256 } 2257 2258 /// Try to reduce a rotate pattern that includes a compare and select into a 2259 /// funnel shift intrinsic. Example: 2260 /// rotl32(a, b) --> (b == 0 ? a : ((a >> (32 - b)) | (a << b))) 2261 /// --> call llvm.fshl.i32(a, a, b) 2262 static Instruction *foldSelectRotate(SelectInst &Sel) { 2263 // The false value of the select must be a rotate of the true value. 2264 Value *Or0, *Or1; 2265 if (!match(Sel.getFalseValue(), m_OneUse(m_Or(m_Value(Or0), m_Value(Or1))))) 2266 return nullptr; 2267 2268 Value *TVal = Sel.getTrueValue(); 2269 Value *SA0, *SA1; 2270 if (!match(Or0, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA0)))) || 2271 !match(Or1, m_OneUse(m_LogicalShift(m_Specific(TVal), m_Value(SA1))))) 2272 return nullptr; 2273 2274 auto ShiftOpcode0 = cast<BinaryOperator>(Or0)->getOpcode(); 2275 auto ShiftOpcode1 = cast<BinaryOperator>(Or1)->getOpcode(); 2276 if (ShiftOpcode0 == ShiftOpcode1) 2277 return nullptr; 2278 2279 // We have one of these patterns so far: 2280 // select ?, TVal, (or (lshr TVal, SA0), (shl TVal, SA1)) 2281 // select ?, TVal, (or (shl TVal, SA0), (lshr TVal, SA1)) 2282 // This must be a power-of-2 rotate for a bitmasking transform to be valid. 2283 unsigned Width = Sel.getType()->getScalarSizeInBits(); 2284 if (!isPowerOf2_32(Width)) 2285 return nullptr; 2286 2287 // Check the shift amounts to see if they are an opposite pair. 2288 Value *ShAmt; 2289 if (match(SA1, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA0))))) 2290 ShAmt = SA0; 2291 else if (match(SA0, m_OneUse(m_Sub(m_SpecificInt(Width), m_Specific(SA1))))) 2292 ShAmt = SA1; 2293 else 2294 return nullptr; 2295 2296 // Finally, see if the select is filtering out a shift-by-zero. 2297 Value *Cond = Sel.getCondition(); 2298 ICmpInst::Predicate Pred; 2299 if (!match(Cond, m_OneUse(m_ICmp(Pred, m_Specific(ShAmt), m_ZeroInt()))) || 2300 Pred != ICmpInst::ICMP_EQ) 2301 return nullptr; 2302 2303 // This is a rotate that avoids shift-by-bitwidth UB in a suboptimal way. 2304 // Convert to funnel shift intrinsic. 2305 bool IsFshl = (ShAmt == SA0 && ShiftOpcode0 == BinaryOperator::Shl) || 2306 (ShAmt == SA1 && ShiftOpcode1 == BinaryOperator::Shl); 2307 Intrinsic::ID IID = IsFshl ? Intrinsic::fshl : Intrinsic::fshr; 2308 Function *F = Intrinsic::getDeclaration(Sel.getModule(), IID, Sel.getType()); 2309 return IntrinsicInst::Create(F, { TVal, TVal, ShAmt }); 2310 } 2311 2312 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 2313 Value *CondVal = SI.getCondition(); 2314 Value *TrueVal = SI.getTrueValue(); 2315 Value *FalseVal = SI.getFalseValue(); 2316 Type *SelType = SI.getType(); 2317 2318 // FIXME: Remove this workaround when freeze related patches are done. 2319 // For select with undef operand which feeds into an equality comparison, 2320 // don't simplify it so loop unswitch can know the equality comparison 2321 // may have an undef operand. This is a workaround for PR31652 caused by 2322 // descrepancy about branch on undef between LoopUnswitch and GVN. 2323 if (isa<UndefValue>(TrueVal) || isa<UndefValue>(FalseVal)) { 2324 if (llvm::any_of(SI.users(), [&](User *U) { 2325 ICmpInst *CI = dyn_cast<ICmpInst>(U); 2326 if (CI && CI->isEquality()) 2327 return true; 2328 return false; 2329 })) { 2330 return nullptr; 2331 } 2332 } 2333 2334 if (Value *V = SimplifySelectInst(CondVal, TrueVal, FalseVal, 2335 SQ.getWithInstruction(&SI))) 2336 return replaceInstUsesWith(SI, V); 2337 2338 if (Instruction *I = canonicalizeSelectToShuffle(SI)) 2339 return I; 2340 2341 if (Instruction *I = canonicalizeScalarSelectOfVecs(SI, Builder)) 2342 return I; 2343 2344 // Canonicalize a one-use integer compare with a non-canonical predicate by 2345 // inverting the predicate and swapping the select operands. This matches a 2346 // compare canonicalization for conditional branches. 2347 // TODO: Should we do the same for FP compares? 2348 CmpInst::Predicate Pred; 2349 if (match(CondVal, m_OneUse(m_ICmp(Pred, m_Value(), m_Value()))) && 2350 !isCanonicalPredicate(Pred)) { 2351 // Swap true/false values and condition. 2352 CmpInst *Cond = cast<CmpInst>(CondVal); 2353 Cond->setPredicate(CmpInst::getInversePredicate(Pred)); 2354 SI.setOperand(1, FalseVal); 2355 SI.setOperand(2, TrueVal); 2356 SI.swapProfMetadata(); 2357 Worklist.Add(Cond); 2358 return &SI; 2359 } 2360 2361 if (SelType->isIntOrIntVectorTy(1) && 2362 TrueVal->getType() == CondVal->getType()) { 2363 if (match(TrueVal, m_One())) { 2364 // Change: A = select B, true, C --> A = or B, C 2365 return BinaryOperator::CreateOr(CondVal, FalseVal); 2366 } 2367 if (match(TrueVal, m_Zero())) { 2368 // Change: A = select B, false, C --> A = and !B, C 2369 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2370 return BinaryOperator::CreateAnd(NotCond, FalseVal); 2371 } 2372 if (match(FalseVal, m_Zero())) { 2373 // Change: A = select B, C, false --> A = and B, C 2374 return BinaryOperator::CreateAnd(CondVal, TrueVal); 2375 } 2376 if (match(FalseVal, m_One())) { 2377 // Change: A = select B, C, true --> A = or !B, C 2378 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2379 return BinaryOperator::CreateOr(NotCond, TrueVal); 2380 } 2381 2382 // select a, a, b -> a | b 2383 // select a, b, a -> a & b 2384 if (CondVal == TrueVal) 2385 return BinaryOperator::CreateOr(CondVal, FalseVal); 2386 if (CondVal == FalseVal) 2387 return BinaryOperator::CreateAnd(CondVal, TrueVal); 2388 2389 // select a, ~a, b -> (~a) & b 2390 // select a, b, ~a -> (~a) | b 2391 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 2392 return BinaryOperator::CreateAnd(TrueVal, FalseVal); 2393 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 2394 return BinaryOperator::CreateOr(TrueVal, FalseVal); 2395 } 2396 2397 // Selecting between two integer or vector splat integer constants? 2398 // 2399 // Note that we don't handle a scalar select of vectors: 2400 // select i1 %c, <2 x i8> <1, 1>, <2 x i8> <0, 0> 2401 // because that may need 3 instructions to splat the condition value: 2402 // extend, insertelement, shufflevector. 2403 if (SelType->isIntOrIntVectorTy() && 2404 CondVal->getType()->isVectorTy() == SelType->isVectorTy()) { 2405 // select C, 1, 0 -> zext C to int 2406 if (match(TrueVal, m_One()) && match(FalseVal, m_Zero())) 2407 return new ZExtInst(CondVal, SelType); 2408 2409 // select C, -1, 0 -> sext C to int 2410 if (match(TrueVal, m_AllOnes()) && match(FalseVal, m_Zero())) 2411 return new SExtInst(CondVal, SelType); 2412 2413 // select C, 0, 1 -> zext !C to int 2414 if (match(TrueVal, m_Zero()) && match(FalseVal, m_One())) { 2415 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2416 return new ZExtInst(NotCond, SelType); 2417 } 2418 2419 // select C, 0, -1 -> sext !C to int 2420 if (match(TrueVal, m_Zero()) && match(FalseVal, m_AllOnes())) { 2421 Value *NotCond = Builder.CreateNot(CondVal, "not." + CondVal->getName()); 2422 return new SExtInst(NotCond, SelType); 2423 } 2424 } 2425 2426 // See if we are selecting two values based on a comparison of the two values. 2427 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 2428 Value *Cmp0 = FCI->getOperand(0), *Cmp1 = FCI->getOperand(1); 2429 if ((Cmp0 == TrueVal && Cmp1 == FalseVal) || 2430 (Cmp0 == FalseVal && Cmp1 == TrueVal)) { 2431 // Canonicalize to use ordered comparisons by swapping the select 2432 // operands. 2433 // 2434 // e.g. 2435 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X 2436 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 2437 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 2438 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2439 // FIXME: The FMF should propagate from the select, not the fcmp. 2440 Builder.setFastMathFlags(FCI->getFastMathFlags()); 2441 Value *NewCond = Builder.CreateFCmp(InvPred, Cmp0, Cmp1, 2442 FCI->getName() + ".inv"); 2443 Value *NewSel = Builder.CreateSelect(NewCond, FalseVal, TrueVal); 2444 return replaceInstUsesWith(SI, NewSel); 2445 } 2446 2447 // NOTE: if we wanted to, this is where to detect MIN/MAX 2448 } 2449 } 2450 2451 // Canonicalize select with fcmp to fabs(). -0.0 makes this tricky. We need 2452 // fast-math-flags (nsz) or fsub with +0.0 (not fneg) for this to work. We 2453 // also require nnan because we do not want to unintentionally change the 2454 // sign of a NaN value. 2455 // FIXME: These folds should test/propagate FMF from the select, not the 2456 // fsub or fneg. 2457 // (X <= +/-0.0) ? (0.0 - X) : X --> fabs(X) 2458 Instruction *FSub; 2459 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 2460 match(TrueVal, m_FSub(m_PosZeroFP(), m_Specific(FalseVal))) && 2461 match(TrueVal, m_Instruction(FSub)) && FSub->hasNoNaNs() && 2462 (Pred == FCmpInst::FCMP_OLE || Pred == FCmpInst::FCMP_ULE)) { 2463 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FSub); 2464 return replaceInstUsesWith(SI, Fabs); 2465 } 2466 // (X > +/-0.0) ? X : (0.0 - X) --> fabs(X) 2467 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 2468 match(FalseVal, m_FSub(m_PosZeroFP(), m_Specific(TrueVal))) && 2469 match(FalseVal, m_Instruction(FSub)) && FSub->hasNoNaNs() && 2470 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_UGT)) { 2471 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FSub); 2472 return replaceInstUsesWith(SI, Fabs); 2473 } 2474 // With nnan and nsz: 2475 // (X < +/-0.0) ? -X : X --> fabs(X) 2476 // (X <= +/-0.0) ? -X : X --> fabs(X) 2477 Instruction *FNeg; 2478 if (match(CondVal, m_FCmp(Pred, m_Specific(FalseVal), m_AnyZeroFP())) && 2479 match(TrueVal, m_FNeg(m_Specific(FalseVal))) && 2480 match(TrueVal, m_Instruction(FNeg)) && 2481 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() && 2482 (Pred == FCmpInst::FCMP_OLT || Pred == FCmpInst::FCMP_OLE || 2483 Pred == FCmpInst::FCMP_ULT || Pred == FCmpInst::FCMP_ULE)) { 2484 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, FalseVal, FNeg); 2485 return replaceInstUsesWith(SI, Fabs); 2486 } 2487 // With nnan and nsz: 2488 // (X > +/-0.0) ? X : -X --> fabs(X) 2489 // (X >= +/-0.0) ? X : -X --> fabs(X) 2490 if (match(CondVal, m_FCmp(Pred, m_Specific(TrueVal), m_AnyZeroFP())) && 2491 match(FalseVal, m_FNeg(m_Specific(TrueVal))) && 2492 match(FalseVal, m_Instruction(FNeg)) && 2493 FNeg->hasNoNaNs() && FNeg->hasNoSignedZeros() && 2494 (Pred == FCmpInst::FCMP_OGT || Pred == FCmpInst::FCMP_OGE || 2495 Pred == FCmpInst::FCMP_UGT || Pred == FCmpInst::FCMP_UGE)) { 2496 Value *Fabs = Builder.CreateUnaryIntrinsic(Intrinsic::fabs, TrueVal, FNeg); 2497 return replaceInstUsesWith(SI, Fabs); 2498 } 2499 2500 // See if we are selecting two values based on a comparison of the two values. 2501 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 2502 if (Instruction *Result = foldSelectInstWithICmp(SI, ICI)) 2503 return Result; 2504 2505 if (Instruction *Add = foldAddSubSelect(SI, Builder)) 2506 return Add; 2507 if (Instruction *Add = foldOverflowingAddSubSelect(SI, Builder)) 2508 return Add; 2509 2510 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 2511 auto *TI = dyn_cast<Instruction>(TrueVal); 2512 auto *FI = dyn_cast<Instruction>(FalseVal); 2513 if (TI && FI && TI->getOpcode() == FI->getOpcode()) 2514 if (Instruction *IV = foldSelectOpOp(SI, TI, FI)) 2515 return IV; 2516 2517 if (Instruction *I = foldSelectExtConst(SI)) 2518 return I; 2519 2520 // See if we can fold the select into one of our operands. 2521 if (SelType->isIntOrIntVectorTy() || SelType->isFPOrFPVectorTy()) { 2522 if (Instruction *FoldI = foldSelectIntoOp(SI, TrueVal, FalseVal)) 2523 return FoldI; 2524 2525 Value *LHS, *RHS; 2526 Instruction::CastOps CastOp; 2527 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp); 2528 auto SPF = SPR.Flavor; 2529 if (SPF) { 2530 Value *LHS2, *RHS2; 2531 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor) 2532 if (Instruction *R = foldSPFofSPF(cast<Instruction>(LHS), SPF2, LHS2, 2533 RHS2, SI, SPF, RHS)) 2534 return R; 2535 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor) 2536 if (Instruction *R = foldSPFofSPF(cast<Instruction>(RHS), SPF2, LHS2, 2537 RHS2, SI, SPF, LHS)) 2538 return R; 2539 // TODO. 2540 // ABS(-X) -> ABS(X) 2541 } 2542 2543 if (SelectPatternResult::isMinOrMax(SPF)) { 2544 // Canonicalize so that 2545 // - type casts are outside select patterns. 2546 // - float clamp is transformed to min/max pattern 2547 2548 bool IsCastNeeded = LHS->getType() != SelType; 2549 Value *CmpLHS = cast<CmpInst>(CondVal)->getOperand(0); 2550 Value *CmpRHS = cast<CmpInst>(CondVal)->getOperand(1); 2551 if (IsCastNeeded || 2552 (LHS->getType()->isFPOrFPVectorTy() && 2553 ((CmpLHS != LHS && CmpLHS != RHS) || 2554 (CmpRHS != LHS && CmpRHS != RHS)))) { 2555 CmpInst::Predicate MinMaxPred = getMinMaxPred(SPF, SPR.Ordered); 2556 2557 Value *Cmp; 2558 if (CmpInst::isIntPredicate(MinMaxPred)) { 2559 Cmp = Builder.CreateICmp(MinMaxPred, LHS, RHS); 2560 } else { 2561 IRBuilder<>::FastMathFlagGuard FMFG(Builder); 2562 auto FMF = 2563 cast<FPMathOperator>(SI.getCondition())->getFastMathFlags(); 2564 Builder.setFastMathFlags(FMF); 2565 Cmp = Builder.CreateFCmp(MinMaxPred, LHS, RHS); 2566 } 2567 2568 Value *NewSI = Builder.CreateSelect(Cmp, LHS, RHS, SI.getName(), &SI); 2569 if (!IsCastNeeded) 2570 return replaceInstUsesWith(SI, NewSI); 2571 2572 Value *NewCast = Builder.CreateCast(CastOp, NewSI, SelType); 2573 return replaceInstUsesWith(SI, NewCast); 2574 } 2575 2576 // MAX(~a, ~b) -> ~MIN(a, b) 2577 // MAX(~a, C) -> ~MIN(a, ~C) 2578 // MIN(~a, ~b) -> ~MAX(a, b) 2579 // MIN(~a, C) -> ~MAX(a, ~C) 2580 auto moveNotAfterMinMax = [&](Value *X, Value *Y) -> Instruction * { 2581 Value *A; 2582 if (match(X, m_Not(m_Value(A))) && !X->hasNUsesOrMore(3) && 2583 !isFreeToInvert(A, A->hasOneUse()) && 2584 // Passing false to only consider m_Not and constants. 2585 isFreeToInvert(Y, false)) { 2586 Value *B = Builder.CreateNot(Y); 2587 Value *NewMinMax = createMinMax(Builder, getInverseMinMaxFlavor(SPF), 2588 A, B); 2589 // Copy the profile metadata. 2590 if (MDNode *MD = SI.getMetadata(LLVMContext::MD_prof)) { 2591 cast<SelectInst>(NewMinMax)->setMetadata(LLVMContext::MD_prof, MD); 2592 // Swap the metadata if the operands are swapped. 2593 if (X == SI.getFalseValue() && Y == SI.getTrueValue()) 2594 cast<SelectInst>(NewMinMax)->swapProfMetadata(); 2595 } 2596 2597 return BinaryOperator::CreateNot(NewMinMax); 2598 } 2599 2600 return nullptr; 2601 }; 2602 2603 if (Instruction *I = moveNotAfterMinMax(LHS, RHS)) 2604 return I; 2605 if (Instruction *I = moveNotAfterMinMax(RHS, LHS)) 2606 return I; 2607 2608 if (Instruction *I = moveAddAfterMinMax(SPF, LHS, RHS, Builder)) 2609 return I; 2610 2611 if (Instruction *I = factorizeMinMaxTree(SPF, LHS, RHS, Builder)) 2612 return I; 2613 if (Instruction *I = matchSAddSubSat(SI)) 2614 return I; 2615 } 2616 } 2617 2618 // Canonicalize select of FP values where NaN and -0.0 are not valid as 2619 // minnum/maxnum intrinsics. 2620 if (isa<FPMathOperator>(SI) && SI.hasNoNaNs() && SI.hasNoSignedZeros()) { 2621 Value *X, *Y; 2622 if (match(&SI, m_OrdFMax(m_Value(X), m_Value(Y)))) 2623 return replaceInstUsesWith( 2624 SI, Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, X, Y, &SI)); 2625 2626 if (match(&SI, m_OrdFMin(m_Value(X), m_Value(Y)))) 2627 return replaceInstUsesWith( 2628 SI, Builder.CreateBinaryIntrinsic(Intrinsic::minnum, X, Y, &SI)); 2629 } 2630 2631 // See if we can fold the select into a phi node if the condition is a select. 2632 if (auto *PN = dyn_cast<PHINode>(SI.getCondition())) 2633 // The true/false values have to be live in the PHI predecessor's blocks. 2634 if (canSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 2635 canSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 2636 if (Instruction *NV = foldOpIntoPhi(SI, PN)) 2637 return NV; 2638 2639 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 2640 if (TrueSI->getCondition()->getType() == CondVal->getType()) { 2641 // select(C, select(C, a, b), c) -> select(C, a, c) 2642 if (TrueSI->getCondition() == CondVal) { 2643 if (SI.getTrueValue() == TrueSI->getTrueValue()) 2644 return nullptr; 2645 SI.setOperand(1, TrueSI->getTrueValue()); 2646 return &SI; 2647 } 2648 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b) 2649 // We choose this as normal form to enable folding on the And and shortening 2650 // paths for the values (this helps GetUnderlyingObjects() for example). 2651 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) { 2652 Value *And = Builder.CreateAnd(CondVal, TrueSI->getCondition()); 2653 SI.setOperand(0, And); 2654 SI.setOperand(1, TrueSI->getTrueValue()); 2655 return &SI; 2656 } 2657 } 2658 } 2659 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 2660 if (FalseSI->getCondition()->getType() == CondVal->getType()) { 2661 // select(C, a, select(C, b, c)) -> select(C, a, c) 2662 if (FalseSI->getCondition() == CondVal) { 2663 if (SI.getFalseValue() == FalseSI->getFalseValue()) 2664 return nullptr; 2665 SI.setOperand(2, FalseSI->getFalseValue()); 2666 return &SI; 2667 } 2668 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b) 2669 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) { 2670 Value *Or = Builder.CreateOr(CondVal, FalseSI->getCondition()); 2671 SI.setOperand(0, Or); 2672 SI.setOperand(2, FalseSI->getFalseValue()); 2673 return &SI; 2674 } 2675 } 2676 } 2677 2678 auto canMergeSelectThroughBinop = [](BinaryOperator *BO) { 2679 // The select might be preventing a division by 0. 2680 switch (BO->getOpcode()) { 2681 default: 2682 return true; 2683 case Instruction::SRem: 2684 case Instruction::URem: 2685 case Instruction::SDiv: 2686 case Instruction::UDiv: 2687 return false; 2688 } 2689 }; 2690 2691 // Try to simplify a binop sandwiched between 2 selects with the same 2692 // condition. 2693 // select(C, binop(select(C, X, Y), W), Z) -> select(C, binop(X, W), Z) 2694 BinaryOperator *TrueBO; 2695 if (match(TrueVal, m_OneUse(m_BinOp(TrueBO))) && 2696 canMergeSelectThroughBinop(TrueBO)) { 2697 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(0))) { 2698 if (TrueBOSI->getCondition() == CondVal) { 2699 TrueBO->setOperand(0, TrueBOSI->getTrueValue()); 2700 Worklist.Add(TrueBO); 2701 return &SI; 2702 } 2703 } 2704 if (auto *TrueBOSI = dyn_cast<SelectInst>(TrueBO->getOperand(1))) { 2705 if (TrueBOSI->getCondition() == CondVal) { 2706 TrueBO->setOperand(1, TrueBOSI->getTrueValue()); 2707 Worklist.Add(TrueBO); 2708 return &SI; 2709 } 2710 } 2711 } 2712 2713 // select(C, Z, binop(select(C, X, Y), W)) -> select(C, Z, binop(Y, W)) 2714 BinaryOperator *FalseBO; 2715 if (match(FalseVal, m_OneUse(m_BinOp(FalseBO))) && 2716 canMergeSelectThroughBinop(FalseBO)) { 2717 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(0))) { 2718 if (FalseBOSI->getCondition() == CondVal) { 2719 FalseBO->setOperand(0, FalseBOSI->getFalseValue()); 2720 Worklist.Add(FalseBO); 2721 return &SI; 2722 } 2723 } 2724 if (auto *FalseBOSI = dyn_cast<SelectInst>(FalseBO->getOperand(1))) { 2725 if (FalseBOSI->getCondition() == CondVal) { 2726 FalseBO->setOperand(1, FalseBOSI->getFalseValue()); 2727 Worklist.Add(FalseBO); 2728 return &SI; 2729 } 2730 } 2731 } 2732 2733 Value *NotCond; 2734 if (match(CondVal, m_Not(m_Value(NotCond)))) { 2735 SI.setOperand(0, NotCond); 2736 SI.setOperand(1, FalseVal); 2737 SI.setOperand(2, TrueVal); 2738 SI.swapProfMetadata(); 2739 return &SI; 2740 } 2741 2742 if (VectorType *VecTy = dyn_cast<VectorType>(SelType)) { 2743 unsigned VWidth = VecTy->getNumElements(); 2744 APInt UndefElts(VWidth, 0); 2745 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 2746 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) { 2747 if (V != &SI) 2748 return replaceInstUsesWith(SI, V); 2749 return &SI; 2750 } 2751 } 2752 2753 // If we can compute the condition, there's no need for a select. 2754 // Like the above fold, we are attempting to reduce compile-time cost by 2755 // putting this fold here with limitations rather than in InstSimplify. 2756 // The motivation for this call into value tracking is to take advantage of 2757 // the assumption cache, so make sure that is populated. 2758 if (!CondVal->getType()->isVectorTy() && !AC.assumptions().empty()) { 2759 KnownBits Known(1); 2760 computeKnownBits(CondVal, Known, 0, &SI); 2761 if (Known.One.isOneValue()) 2762 return replaceInstUsesWith(SI, TrueVal); 2763 if (Known.Zero.isOneValue()) 2764 return replaceInstUsesWith(SI, FalseVal); 2765 } 2766 2767 if (Instruction *BitCastSel = foldSelectCmpBitcasts(SI, Builder)) 2768 return BitCastSel; 2769 2770 // Simplify selects that test the returned flag of cmpxchg instructions. 2771 if (Instruction *Select = foldSelectCmpXchg(SI)) 2772 return Select; 2773 2774 if (Instruction *Select = foldSelectBinOpIdentity(SI, TLI)) 2775 return Select; 2776 2777 if (Instruction *Rot = foldSelectRotate(SI)) 2778 return Rot; 2779 2780 return nullptr; 2781 } 2782