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