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