1 //===- InstCombineSelect.cpp ----------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the visitSelect function. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "InstCombineInternal.h" 15 #include "llvm/Analysis/ConstantFolding.h" 16 #include "llvm/Analysis/InstructionSimplify.h" 17 #include "llvm/Analysis/ValueTracking.h" 18 #include "llvm/IR/PatternMatch.h" 19 using namespace llvm; 20 using namespace PatternMatch; 21 22 #define DEBUG_TYPE "instcombine" 23 24 static SelectPatternFlavor 25 getInverseMinMaxSelectPattern(SelectPatternFlavor SPF) { 26 switch (SPF) { 27 default: 28 llvm_unreachable("unhandled!"); 29 30 case SPF_SMIN: 31 return SPF_SMAX; 32 case SPF_UMIN: 33 return SPF_UMAX; 34 case SPF_SMAX: 35 return SPF_SMIN; 36 case SPF_UMAX: 37 return SPF_UMIN; 38 } 39 } 40 41 static CmpInst::Predicate getCmpPredicateForMinMax(SelectPatternFlavor SPF, 42 bool Ordered=false) { 43 switch (SPF) { 44 default: 45 llvm_unreachable("unhandled!"); 46 47 case SPF_SMIN: 48 return ICmpInst::ICMP_SLT; 49 case SPF_UMIN: 50 return ICmpInst::ICMP_ULT; 51 case SPF_SMAX: 52 return ICmpInst::ICMP_SGT; 53 case SPF_UMAX: 54 return ICmpInst::ICMP_UGT; 55 case SPF_FMINNUM: 56 return Ordered ? FCmpInst::FCMP_OLT : FCmpInst::FCMP_ULT; 57 case SPF_FMAXNUM: 58 return Ordered ? FCmpInst::FCMP_OGT : FCmpInst::FCMP_UGT; 59 } 60 } 61 62 static Value *generateMinMaxSelectPattern(InstCombiner::BuilderTy *Builder, 63 SelectPatternFlavor SPF, Value *A, 64 Value *B) { 65 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF); 66 assert(CmpInst::isIntPredicate(Pred)); 67 return Builder->CreateSelect(Builder->CreateICmp(Pred, A, B), A, B); 68 } 69 70 /// We want to turn code that looks like this: 71 /// %C = or %A, %B 72 /// %D = select %cond, %C, %A 73 /// into: 74 /// %C = select %cond, %B, 0 75 /// %D = or %A, %C 76 /// 77 /// Assuming that the specified instruction is an operand to the select, return 78 /// a bitmask indicating which operands of this instruction are foldable if they 79 /// equal the other incoming value of the select. 80 /// 81 static unsigned GetSelectFoldableOperands(Instruction *I) { 82 switch (I->getOpcode()) { 83 case Instruction::Add: 84 case Instruction::Mul: 85 case Instruction::And: 86 case Instruction::Or: 87 case Instruction::Xor: 88 return 3; // Can fold through either operand. 89 case Instruction::Sub: // Can only fold on the amount subtracted. 90 case Instruction::Shl: // Can only fold on the shift amount. 91 case Instruction::LShr: 92 case Instruction::AShr: 93 return 1; 94 default: 95 return 0; // Cannot fold 96 } 97 } 98 99 /// For the same transformation as the previous function, return the identity 100 /// constant that goes into the select. 101 static Constant *GetSelectFoldableConstant(Instruction *I) { 102 switch (I->getOpcode()) { 103 default: llvm_unreachable("This cannot happen!"); 104 case Instruction::Add: 105 case Instruction::Sub: 106 case Instruction::Or: 107 case Instruction::Xor: 108 case Instruction::Shl: 109 case Instruction::LShr: 110 case Instruction::AShr: 111 return Constant::getNullValue(I->getType()); 112 case Instruction::And: 113 return Constant::getAllOnesValue(I->getType()); 114 case Instruction::Mul: 115 return ConstantInt::get(I->getType(), 1); 116 } 117 } 118 119 /// Here we have (select c, TI, FI), and we know that TI and FI 120 /// have the same opcode and only one use each. Try to simplify this. 121 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI, 122 Instruction *FI) { 123 // If this is a cast from the same type, merge. 124 if (TI->getNumOperands() == 1 && TI->isCast()) { 125 Type *FIOpndTy = FI->getOperand(0)->getType(); 126 if (TI->getOperand(0)->getType() != FIOpndTy) 127 return nullptr; 128 129 // The select condition may be a vector. We may only change the operand 130 // type if the vector width remains the same (and matches the condition). 131 Type *CondTy = SI.getCondition()->getType(); 132 if (CondTy->isVectorTy() && 133 (!FIOpndTy->isVectorTy() || 134 CondTy->getVectorNumElements() != FIOpndTy->getVectorNumElements())) 135 return nullptr; 136 137 // Fold this by inserting a select from the input values. 138 Value *NewSI = Builder->CreateSelect(SI.getCondition(), TI->getOperand(0), 139 FI->getOperand(0), SI.getName()+".v"); 140 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI, 141 TI->getType()); 142 } 143 144 // Only handle binary operators here. 145 if (!isa<BinaryOperator>(TI)) 146 return nullptr; 147 148 // Figure out if the operations have any operands in common. 149 Value *MatchOp, *OtherOpT, *OtherOpF; 150 bool MatchIsOpZero; 151 if (TI->getOperand(0) == FI->getOperand(0)) { 152 MatchOp = TI->getOperand(0); 153 OtherOpT = TI->getOperand(1); 154 OtherOpF = FI->getOperand(1); 155 MatchIsOpZero = true; 156 } else if (TI->getOperand(1) == FI->getOperand(1)) { 157 MatchOp = TI->getOperand(1); 158 OtherOpT = TI->getOperand(0); 159 OtherOpF = FI->getOperand(0); 160 MatchIsOpZero = false; 161 } else if (!TI->isCommutative()) { 162 return nullptr; 163 } else if (TI->getOperand(0) == FI->getOperand(1)) { 164 MatchOp = TI->getOperand(0); 165 OtherOpT = TI->getOperand(1); 166 OtherOpF = FI->getOperand(0); 167 MatchIsOpZero = true; 168 } else if (TI->getOperand(1) == FI->getOperand(0)) { 169 MatchOp = TI->getOperand(1); 170 OtherOpT = TI->getOperand(0); 171 OtherOpF = FI->getOperand(1); 172 MatchIsOpZero = true; 173 } else { 174 return nullptr; 175 } 176 177 // If we reach here, they do have operations in common. 178 Value *NewSI = Builder->CreateSelect(SI.getCondition(), OtherOpT, 179 OtherOpF, SI.getName()+".v"); 180 181 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) { 182 if (MatchIsOpZero) 183 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI); 184 else 185 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp); 186 } 187 llvm_unreachable("Shouldn't get here"); 188 } 189 190 static bool isSelect01(Constant *C1, Constant *C2) { 191 ConstantInt *C1I = dyn_cast<ConstantInt>(C1); 192 if (!C1I) 193 return false; 194 ConstantInt *C2I = dyn_cast<ConstantInt>(C2); 195 if (!C2I) 196 return false; 197 if (!C1I->isZero() && !C2I->isZero()) // One side must be zero. 198 return false; 199 return C1I->isOne() || C1I->isAllOnesValue() || 200 C2I->isOne() || C2I->isAllOnesValue(); 201 } 202 203 /// Try to fold the select into one of the operands to allow further 204 /// optimization. 205 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal, 206 Value *FalseVal) { 207 // See the comment above GetSelectFoldableOperands for a description of the 208 // transformation we are doing here. 209 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) { 210 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 && 211 !isa<Constant>(FalseVal)) { 212 if (unsigned SFO = GetSelectFoldableOperands(TVI)) { 213 unsigned OpToFold = 0; 214 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) { 215 OpToFold = 1; 216 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) { 217 OpToFold = 2; 218 } 219 220 if (OpToFold) { 221 Constant *C = GetSelectFoldableConstant(TVI); 222 Value *OOp = TVI->getOperand(2-OpToFold); 223 // Avoid creating select between 2 constants unless it's selecting 224 // between 0, 1 and -1. 225 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 226 Value *NewSel = Builder->CreateSelect(SI.getCondition(), OOp, C); 227 NewSel->takeName(TVI); 228 BinaryOperator *TVI_BO = cast<BinaryOperator>(TVI); 229 BinaryOperator *BO = BinaryOperator::Create(TVI_BO->getOpcode(), 230 FalseVal, NewSel); 231 BO->copyIRFlags(TVI_BO); 232 return BO; 233 } 234 } 235 } 236 } 237 } 238 239 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) { 240 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 && 241 !isa<Constant>(TrueVal)) { 242 if (unsigned SFO = GetSelectFoldableOperands(FVI)) { 243 unsigned OpToFold = 0; 244 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) { 245 OpToFold = 1; 246 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) { 247 OpToFold = 2; 248 } 249 250 if (OpToFold) { 251 Constant *C = GetSelectFoldableConstant(FVI); 252 Value *OOp = FVI->getOperand(2-OpToFold); 253 // Avoid creating select between 2 constants unless it's selecting 254 // between 0, 1 and -1. 255 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) { 256 Value *NewSel = Builder->CreateSelect(SI.getCondition(), C, OOp); 257 NewSel->takeName(FVI); 258 BinaryOperator *FVI_BO = cast<BinaryOperator>(FVI); 259 BinaryOperator *BO = BinaryOperator::Create(FVI_BO->getOpcode(), 260 TrueVal, NewSel); 261 BO->copyIRFlags(FVI_BO); 262 return BO; 263 } 264 } 265 } 266 } 267 } 268 269 return nullptr; 270 } 271 272 /// We want to turn: 273 /// (select (icmp eq (and X, C1), 0), Y, (or Y, C2)) 274 /// into: 275 /// (or (shl (and X, C1), C3), y) 276 /// iff: 277 /// C1 and C2 are both powers of 2 278 /// where: 279 /// C3 = Log(C2) - Log(C1) 280 /// 281 /// This transform handles cases where: 282 /// 1. The icmp predicate is inverted 283 /// 2. The select operands are reversed 284 /// 3. The magnitude of C2 and C1 are flipped 285 static Value *foldSelectICmpAndOr(const SelectInst &SI, Value *TrueVal, 286 Value *FalseVal, 287 InstCombiner::BuilderTy *Builder) { 288 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition()); 289 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy()) 290 return nullptr; 291 292 Value *CmpLHS = IC->getOperand(0); 293 Value *CmpRHS = IC->getOperand(1); 294 295 if (!match(CmpRHS, m_Zero())) 296 return nullptr; 297 298 Value *X; 299 const APInt *C1; 300 if (!match(CmpLHS, m_And(m_Value(X), m_Power2(C1)))) 301 return nullptr; 302 303 const APInt *C2; 304 bool OrOnTrueVal = false; 305 bool OrOnFalseVal = match(FalseVal, m_Or(m_Specific(TrueVal), m_Power2(C2))); 306 if (!OrOnFalseVal) 307 OrOnTrueVal = match(TrueVal, m_Or(m_Specific(FalseVal), m_Power2(C2))); 308 309 if (!OrOnFalseVal && !OrOnTrueVal) 310 return nullptr; 311 312 Value *V = CmpLHS; 313 Value *Y = OrOnFalseVal ? TrueVal : FalseVal; 314 315 unsigned C1Log = C1->logBase2(); 316 unsigned C2Log = C2->logBase2(); 317 if (C2Log > C1Log) { 318 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 319 V = Builder->CreateShl(V, C2Log - C1Log); 320 } else if (C1Log > C2Log) { 321 V = Builder->CreateLShr(V, C1Log - C2Log); 322 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 323 } else 324 V = Builder->CreateZExtOrTrunc(V, Y->getType()); 325 326 ICmpInst::Predicate Pred = IC->getPredicate(); 327 if ((Pred == ICmpInst::ICMP_NE && OrOnFalseVal) || 328 (Pred == ICmpInst::ICMP_EQ && OrOnTrueVal)) 329 V = Builder->CreateXor(V, *C2); 330 331 return Builder->CreateOr(V, Y); 332 } 333 334 /// Attempt to fold a cttz/ctlz followed by a icmp plus select into a single 335 /// call to cttz/ctlz with flag 'is_zero_undef' cleared. 336 /// 337 /// For example, we can fold the following code sequence: 338 /// \code 339 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 true) 340 /// %1 = icmp ne i32 %x, 0 341 /// %2 = select i1 %1, i32 %0, i32 32 342 /// \code 343 /// 344 /// into: 345 /// %0 = tail call i32 @llvm.cttz.i32(i32 %x, i1 false) 346 static Value *foldSelectCttzCtlz(ICmpInst *ICI, Value *TrueVal, Value *FalseVal, 347 InstCombiner::BuilderTy *Builder) { 348 ICmpInst::Predicate Pred = ICI->getPredicate(); 349 Value *CmpLHS = ICI->getOperand(0); 350 Value *CmpRHS = ICI->getOperand(1); 351 352 // Check if the condition value compares a value for equality against zero. 353 if (!ICI->isEquality() || !match(CmpRHS, m_Zero())) 354 return nullptr; 355 356 Value *Count = FalseVal; 357 Value *ValueOnZero = TrueVal; 358 if (Pred == ICmpInst::ICMP_NE) 359 std::swap(Count, ValueOnZero); 360 361 // Skip zero extend/truncate. 362 Value *V = nullptr; 363 if (match(Count, m_ZExt(m_Value(V))) || 364 match(Count, m_Trunc(m_Value(V)))) 365 Count = V; 366 367 // Check if the value propagated on zero is a constant number equal to the 368 // sizeof in bits of 'Count'. 369 unsigned SizeOfInBits = Count->getType()->getScalarSizeInBits(); 370 if (!match(ValueOnZero, m_SpecificInt(SizeOfInBits))) 371 return nullptr; 372 373 // Check that 'Count' is a call to intrinsic cttz/ctlz. Also check that the 374 // input to the cttz/ctlz is used as LHS for the compare instruction. 375 if (match(Count, m_Intrinsic<Intrinsic::cttz>(m_Specific(CmpLHS))) || 376 match(Count, m_Intrinsic<Intrinsic::ctlz>(m_Specific(CmpLHS)))) { 377 IntrinsicInst *II = cast<IntrinsicInst>(Count); 378 IRBuilder<> Builder(II); 379 // Explicitly clear the 'undef_on_zero' flag. 380 IntrinsicInst *NewI = cast<IntrinsicInst>(II->clone()); 381 Type *Ty = NewI->getArgOperand(1)->getType(); 382 NewI->setArgOperand(1, Constant::getNullValue(Ty)); 383 Builder.Insert(NewI); 384 return Builder.CreateZExtOrTrunc(NewI, ValueOnZero->getType()); 385 } 386 387 return nullptr; 388 } 389 390 /// Visit a SelectInst that has an ICmpInst as its first operand. 391 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI, 392 ICmpInst *ICI) { 393 bool Changed = false; 394 ICmpInst::Predicate Pred = ICI->getPredicate(); 395 Value *CmpLHS = ICI->getOperand(0); 396 Value *CmpRHS = ICI->getOperand(1); 397 Value *TrueVal = SI.getTrueValue(); 398 Value *FalseVal = SI.getFalseValue(); 399 400 // Check cases where the comparison is with a constant that 401 // can be adjusted to fit the min/max idiom. We may move or edit ICI 402 // here, so make sure the select is the only user. 403 if (ICI->hasOneUse()) 404 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) { 405 switch (Pred) { 406 default: break; 407 case ICmpInst::ICMP_ULT: 408 case ICmpInst::ICMP_SLT: 409 case ICmpInst::ICMP_UGT: 410 case ICmpInst::ICMP_SGT: { 411 // These transformations only work for selects over integers. 412 IntegerType *SelectTy = dyn_cast<IntegerType>(SI.getType()); 413 if (!SelectTy) 414 break; 415 416 Constant *AdjustedRHS; 417 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SGT) 418 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() + 1); 419 else // (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) 420 AdjustedRHS = ConstantInt::get(CI->getContext(), CI->getValue() - 1); 421 422 // X > C ? X : C+1 --> X < C+1 ? C+1 : X 423 // X < C ? X : C-1 --> X > C-1 ? C-1 : X 424 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) || 425 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) 426 ; // Nothing to do here. Values match without any sign/zero extension. 427 428 // Types do not match. Instead of calculating this with mixed types 429 // promote all to the larger type. This enables scalar evolution to 430 // analyze this expression. 431 else if (CmpRHS->getType()->getScalarSizeInBits() 432 < SelectTy->getBitWidth()) { 433 Constant *sextRHS = ConstantExpr::getSExt(AdjustedRHS, SelectTy); 434 435 // X = sext x; x >s c ? X : C+1 --> X = sext x; X <s C+1 ? C+1 : X 436 // X = sext x; x <s c ? X : C-1 --> X = sext x; X >s C-1 ? C-1 : X 437 // X = sext x; x >u c ? X : C+1 --> X = sext x; X <u C+1 ? C+1 : X 438 // X = sext x; x <u c ? X : C-1 --> X = sext x; X >u C-1 ? C-1 : X 439 if (match(TrueVal, m_SExt(m_Specific(CmpLHS))) && 440 sextRHS == FalseVal) { 441 CmpLHS = TrueVal; 442 AdjustedRHS = sextRHS; 443 } else if (match(FalseVal, m_SExt(m_Specific(CmpLHS))) && 444 sextRHS == TrueVal) { 445 CmpLHS = FalseVal; 446 AdjustedRHS = sextRHS; 447 } else if (ICI->isUnsigned()) { 448 Constant *zextRHS = ConstantExpr::getZExt(AdjustedRHS, SelectTy); 449 // X = zext x; x >u c ? X : C+1 --> X = zext x; X <u C+1 ? C+1 : X 450 // X = zext x; x <u c ? X : C-1 --> X = zext x; X >u C-1 ? C-1 : X 451 // zext + signed compare cannot be changed: 452 // 0xff <s 0x00, but 0x00ff >s 0x0000 453 if (match(TrueVal, m_ZExt(m_Specific(CmpLHS))) && 454 zextRHS == FalseVal) { 455 CmpLHS = TrueVal; 456 AdjustedRHS = zextRHS; 457 } else if (match(FalseVal, m_ZExt(m_Specific(CmpLHS))) && 458 zextRHS == TrueVal) { 459 CmpLHS = FalseVal; 460 AdjustedRHS = zextRHS; 461 } else 462 break; 463 } else 464 break; 465 } else 466 break; 467 468 Pred = ICmpInst::getSwappedPredicate(Pred); 469 CmpRHS = AdjustedRHS; 470 std::swap(FalseVal, TrueVal); 471 ICI->setPredicate(Pred); 472 ICI->setOperand(0, CmpLHS); 473 ICI->setOperand(1, CmpRHS); 474 SI.setOperand(1, TrueVal); 475 SI.setOperand(2, FalseVal); 476 477 // Move ICI instruction right before the select instruction. Otherwise 478 // the sext/zext value may be defined after the ICI instruction uses it. 479 ICI->moveBefore(&SI); 480 481 Changed = true; 482 break; 483 } 484 } 485 } 486 487 // Transform (X >s -1) ? C1 : C2 --> ((X >>s 31) & (C2 - C1)) + C1 488 // and (X <s 0) ? C2 : C1 --> ((X >>s 31) & (C2 - C1)) + C1 489 // FIXME: Type and constness constraints could be lifted, but we have to 490 // watch code size carefully. We should consider xor instead of 491 // sub/add when we decide to do that. 492 if (IntegerType *Ty = dyn_cast<IntegerType>(CmpLHS->getType())) { 493 if (TrueVal->getType() == Ty) { 494 if (ConstantInt *Cmp = dyn_cast<ConstantInt>(CmpRHS)) { 495 ConstantInt *C1 = nullptr, *C2 = nullptr; 496 if (Pred == ICmpInst::ICMP_SGT && Cmp->isAllOnesValue()) { 497 C1 = dyn_cast<ConstantInt>(TrueVal); 498 C2 = dyn_cast<ConstantInt>(FalseVal); 499 } else if (Pred == ICmpInst::ICMP_SLT && Cmp->isNullValue()) { 500 C1 = dyn_cast<ConstantInt>(FalseVal); 501 C2 = dyn_cast<ConstantInt>(TrueVal); 502 } 503 if (C1 && C2) { 504 // This shift results in either -1 or 0. 505 Value *AShr = Builder->CreateAShr(CmpLHS, Ty->getBitWidth()-1); 506 507 // Check if we can express the operation with a single or. 508 if (C2->isAllOnesValue()) 509 return replaceInstUsesWith(SI, Builder->CreateOr(AShr, C1)); 510 511 Value *And = Builder->CreateAnd(AShr, C2->getValue()-C1->getValue()); 512 return replaceInstUsesWith(SI, Builder->CreateAdd(And, C1)); 513 } 514 } 515 } 516 } 517 518 // NOTE: if we wanted to, this is where to detect integer MIN/MAX 519 520 if (CmpRHS != CmpLHS && isa<Constant>(CmpRHS)) { 521 if (CmpLHS == TrueVal && Pred == ICmpInst::ICMP_EQ) { 522 // Transform (X == C) ? X : Y -> (X == C) ? C : Y 523 SI.setOperand(1, CmpRHS); 524 Changed = true; 525 } else if (CmpLHS == FalseVal && Pred == ICmpInst::ICMP_NE) { 526 // Transform (X != C) ? Y : X -> (X != C) ? Y : C 527 SI.setOperand(2, CmpRHS); 528 Changed = true; 529 } 530 } 531 532 { 533 unsigned BitWidth = DL.getTypeSizeInBits(TrueVal->getType()); 534 APInt MinSignedValue = APInt::getSignBit(BitWidth); 535 Value *X; 536 const APInt *Y, *C; 537 bool TrueWhenUnset; 538 bool IsBitTest = false; 539 if (ICmpInst::isEquality(Pred) && 540 match(CmpLHS, m_And(m_Value(X), m_Power2(Y))) && 541 match(CmpRHS, m_Zero())) { 542 IsBitTest = true; 543 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ; 544 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) { 545 X = CmpLHS; 546 Y = &MinSignedValue; 547 IsBitTest = true; 548 TrueWhenUnset = false; 549 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) { 550 X = CmpLHS; 551 Y = &MinSignedValue; 552 IsBitTest = true; 553 TrueWhenUnset = true; 554 } 555 if (IsBitTest) { 556 Value *V = nullptr; 557 // (X & Y) == 0 ? X : X ^ Y --> X & ~Y 558 if (TrueWhenUnset && TrueVal == X && 559 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 560 V = Builder->CreateAnd(X, ~(*Y)); 561 // (X & Y) != 0 ? X ^ Y : X --> X & ~Y 562 else if (!TrueWhenUnset && FalseVal == X && 563 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 564 V = Builder->CreateAnd(X, ~(*Y)); 565 // (X & Y) == 0 ? X ^ Y : X --> X | Y 566 else if (TrueWhenUnset && FalseVal == X && 567 match(TrueVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 568 V = Builder->CreateOr(X, *Y); 569 // (X & Y) != 0 ? X : X ^ Y --> X | Y 570 else if (!TrueWhenUnset && TrueVal == X && 571 match(FalseVal, m_Xor(m_Specific(X), m_APInt(C))) && *Y == *C) 572 V = Builder->CreateOr(X, *Y); 573 574 if (V) 575 return replaceInstUsesWith(SI, V); 576 } 577 } 578 579 if (Value *V = foldSelectICmpAndOr(SI, TrueVal, FalseVal, Builder)) 580 return replaceInstUsesWith(SI, V); 581 582 if (Value *V = foldSelectCttzCtlz(ICI, TrueVal, FalseVal, Builder)) 583 return replaceInstUsesWith(SI, V); 584 585 return Changed ? &SI : nullptr; 586 } 587 588 589 /// SI is a select whose condition is a PHI node (but the two may be in 590 /// different blocks). See if the true/false values (V) are live in all of the 591 /// predecessor blocks of the PHI. For example, cases like this can't be mapped: 592 /// 593 /// X = phi [ C1, BB1], [C2, BB2] 594 /// Y = add 595 /// Z = select X, Y, 0 596 /// 597 /// because Y is not live in BB1/BB2. 598 /// 599 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V, 600 const SelectInst &SI) { 601 // If the value is a non-instruction value like a constant or argument, it 602 // can always be mapped. 603 const Instruction *I = dyn_cast<Instruction>(V); 604 if (!I) return true; 605 606 // If V is a PHI node defined in the same block as the condition PHI, we can 607 // map the arguments. 608 const PHINode *CondPHI = cast<PHINode>(SI.getCondition()); 609 610 if (const PHINode *VP = dyn_cast<PHINode>(I)) 611 if (VP->getParent() == CondPHI->getParent()) 612 return true; 613 614 // Otherwise, if the PHI and select are defined in the same block and if V is 615 // defined in a different block, then we can transform it. 616 if (SI.getParent() == CondPHI->getParent() && 617 I->getParent() != CondPHI->getParent()) 618 return true; 619 620 // Otherwise we have a 'hard' case and we can't tell without doing more 621 // detailed dominator based analysis, punt. 622 return false; 623 } 624 625 /// We have an SPF (e.g. a min or max) of an SPF of the form: 626 /// SPF2(SPF1(A, B), C) 627 Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner, 628 SelectPatternFlavor SPF1, 629 Value *A, Value *B, 630 Instruction &Outer, 631 SelectPatternFlavor SPF2, Value *C) { 632 if (Outer.getType() != Inner->getType()) 633 return nullptr; 634 635 if (C == A || C == B) { 636 // MAX(MAX(A, B), B) -> MAX(A, B) 637 // MIN(MIN(a, b), a) -> MIN(a, b) 638 if (SPF1 == SPF2) 639 return replaceInstUsesWith(Outer, Inner); 640 641 // MAX(MIN(a, b), a) -> a 642 // MIN(MAX(a, b), a) -> a 643 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) || 644 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) || 645 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) || 646 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN)) 647 return replaceInstUsesWith(Outer, C); 648 } 649 650 if (SPF1 == SPF2) { 651 if (ConstantInt *CB = dyn_cast<ConstantInt>(B)) { 652 if (ConstantInt *CC = dyn_cast<ConstantInt>(C)) { 653 const APInt &ACB = CB->getValue(); 654 const APInt &ACC = CC->getValue(); 655 656 // MIN(MIN(A, 23), 97) -> MIN(A, 23) 657 // MAX(MAX(A, 97), 23) -> MAX(A, 97) 658 if ((SPF1 == SPF_UMIN && ACB.ule(ACC)) || 659 (SPF1 == SPF_SMIN && ACB.sle(ACC)) || 660 (SPF1 == SPF_UMAX && ACB.uge(ACC)) || 661 (SPF1 == SPF_SMAX && ACB.sge(ACC))) 662 return replaceInstUsesWith(Outer, Inner); 663 664 // MIN(MIN(A, 97), 23) -> MIN(A, 23) 665 // MAX(MAX(A, 23), 97) -> MAX(A, 97) 666 if ((SPF1 == SPF_UMIN && ACB.ugt(ACC)) || 667 (SPF1 == SPF_SMIN && ACB.sgt(ACC)) || 668 (SPF1 == SPF_UMAX && ACB.ult(ACC)) || 669 (SPF1 == SPF_SMAX && ACB.slt(ACC))) { 670 Outer.replaceUsesOfWith(Inner, A); 671 return &Outer; 672 } 673 } 674 } 675 } 676 677 // ABS(ABS(X)) -> ABS(X) 678 // NABS(NABS(X)) -> NABS(X) 679 if (SPF1 == SPF2 && (SPF1 == SPF_ABS || SPF1 == SPF_NABS)) { 680 return replaceInstUsesWith(Outer, Inner); 681 } 682 683 // ABS(NABS(X)) -> ABS(X) 684 // NABS(ABS(X)) -> NABS(X) 685 if ((SPF1 == SPF_ABS && SPF2 == SPF_NABS) || 686 (SPF1 == SPF_NABS && SPF2 == SPF_ABS)) { 687 SelectInst *SI = cast<SelectInst>(Inner); 688 Value *NewSI = Builder->CreateSelect( 689 SI->getCondition(), SI->getFalseValue(), SI->getTrueValue()); 690 return replaceInstUsesWith(Outer, NewSI); 691 } 692 693 auto IsFreeOrProfitableToInvert = 694 [&](Value *V, Value *&NotV, bool &ElidesXor) { 695 if (match(V, m_Not(m_Value(NotV)))) { 696 // If V has at most 2 uses then we can get rid of the xor operation 697 // entirely. 698 ElidesXor |= !V->hasNUsesOrMore(3); 699 return true; 700 } 701 702 if (IsFreeToInvert(V, !V->hasNUsesOrMore(3))) { 703 NotV = nullptr; 704 return true; 705 } 706 707 return false; 708 }; 709 710 Value *NotA, *NotB, *NotC; 711 bool ElidesXor = false; 712 713 // MIN(MIN(~A, ~B), ~C) == ~MAX(MAX(A, B), C) 714 // MIN(MAX(~A, ~B), ~C) == ~MAX(MIN(A, B), C) 715 // MAX(MIN(~A, ~B), ~C) == ~MIN(MAX(A, B), C) 716 // MAX(MAX(~A, ~B), ~C) == ~MIN(MIN(A, B), C) 717 // 718 // This transform is performance neutral if we can elide at least one xor from 719 // the set of three operands, since we'll be tacking on an xor at the very 720 // end. 721 if (IsFreeOrProfitableToInvert(A, NotA, ElidesXor) && 722 IsFreeOrProfitableToInvert(B, NotB, ElidesXor) && 723 IsFreeOrProfitableToInvert(C, NotC, ElidesXor) && ElidesXor) { 724 if (!NotA) 725 NotA = Builder->CreateNot(A); 726 if (!NotB) 727 NotB = Builder->CreateNot(B); 728 if (!NotC) 729 NotC = Builder->CreateNot(C); 730 731 Value *NewInner = generateMinMaxSelectPattern( 732 Builder, getInverseMinMaxSelectPattern(SPF1), NotA, NotB); 733 Value *NewOuter = Builder->CreateNot(generateMinMaxSelectPattern( 734 Builder, getInverseMinMaxSelectPattern(SPF2), NewInner, NotC)); 735 return replaceInstUsesWith(Outer, NewOuter); 736 } 737 738 return nullptr; 739 } 740 741 /// If one of the constants is zero (we know they can't both be) and we have an 742 /// icmp instruction with zero, and we have an 'and' with the non-constant value 743 /// and a power of two we can turn the select into a shift on the result of the 744 /// 'and'. 745 static Value *foldSelectICmpAnd(const SelectInst &SI, ConstantInt *TrueVal, 746 ConstantInt *FalseVal, 747 InstCombiner::BuilderTy *Builder) { 748 const ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition()); 749 if (!IC || !IC->isEquality() || !SI.getType()->isIntegerTy()) 750 return nullptr; 751 752 if (!match(IC->getOperand(1), m_Zero())) 753 return nullptr; 754 755 ConstantInt *AndRHS; 756 Value *LHS = IC->getOperand(0); 757 if (!match(LHS, m_And(m_Value(), m_ConstantInt(AndRHS)))) 758 return nullptr; 759 760 // If both select arms are non-zero see if we have a select of the form 761 // 'x ? 2^n + C : C'. Then we can offset both arms by C, use the logic 762 // for 'x ? 2^n : 0' and fix the thing up at the end. 763 ConstantInt *Offset = nullptr; 764 if (!TrueVal->isZero() && !FalseVal->isZero()) { 765 if ((TrueVal->getValue() - FalseVal->getValue()).isPowerOf2()) 766 Offset = FalseVal; 767 else if ((FalseVal->getValue() - TrueVal->getValue()).isPowerOf2()) 768 Offset = TrueVal; 769 else 770 return nullptr; 771 772 // Adjust TrueVal and FalseVal to the offset. 773 TrueVal = ConstantInt::get(Builder->getContext(), 774 TrueVal->getValue() - Offset->getValue()); 775 FalseVal = ConstantInt::get(Builder->getContext(), 776 FalseVal->getValue() - Offset->getValue()); 777 } 778 779 // Make sure the mask in the 'and' and one of the select arms is a power of 2. 780 if (!AndRHS->getValue().isPowerOf2() || 781 (!TrueVal->getValue().isPowerOf2() && 782 !FalseVal->getValue().isPowerOf2())) 783 return nullptr; 784 785 // Determine which shift is needed to transform result of the 'and' into the 786 // desired result. 787 ConstantInt *ValC = !TrueVal->isZero() ? TrueVal : FalseVal; 788 unsigned ValZeros = ValC->getValue().logBase2(); 789 unsigned AndZeros = AndRHS->getValue().logBase2(); 790 791 // If types don't match we can still convert the select by introducing a zext 792 // or a trunc of the 'and'. The trunc case requires that all of the truncated 793 // bits are zero, we can figure that out by looking at the 'and' mask. 794 if (AndZeros >= ValC->getBitWidth()) 795 return nullptr; 796 797 Value *V = Builder->CreateZExtOrTrunc(LHS, SI.getType()); 798 if (ValZeros > AndZeros) 799 V = Builder->CreateShl(V, ValZeros - AndZeros); 800 else if (ValZeros < AndZeros) 801 V = Builder->CreateLShr(V, AndZeros - ValZeros); 802 803 // Okay, now we know that everything is set up, we just don't know whether we 804 // have a icmp_ne or icmp_eq and whether the true or false val is the zero. 805 bool ShouldNotVal = !TrueVal->isZero(); 806 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE; 807 if (ShouldNotVal) 808 V = Builder->CreateXor(V, ValC); 809 810 // Apply an offset if needed. 811 if (Offset) 812 V = Builder->CreateAdd(V, Offset); 813 return V; 814 } 815 816 /// Turn select C, (X + Y), (X - Y) --> (X + (select C, Y, (-Y))). 817 /// This is even legal for FP. 818 static Instruction *foldAddSubSelect(SelectInst &SI, 819 InstCombiner::BuilderTy &Builder) { 820 Value *CondVal = SI.getCondition(); 821 Value *TrueVal = SI.getTrueValue(); 822 Value *FalseVal = SI.getFalseValue(); 823 auto *TI = dyn_cast<Instruction>(TrueVal); 824 auto *FI = dyn_cast<Instruction>(FalseVal); 825 if (!TI || !FI || !TI->hasOneUse() || !FI->hasOneUse()) 826 return nullptr; 827 828 Instruction *AddOp = nullptr, *SubOp = nullptr; 829 if ((TI->getOpcode() == Instruction::Sub && 830 FI->getOpcode() == Instruction::Add) || 831 (TI->getOpcode() == Instruction::FSub && 832 FI->getOpcode() == Instruction::FAdd)) { 833 AddOp = FI; 834 SubOp = TI; 835 } else if ((FI->getOpcode() == Instruction::Sub && 836 TI->getOpcode() == Instruction::Add) || 837 (FI->getOpcode() == Instruction::FSub && 838 TI->getOpcode() == Instruction::FAdd)) { 839 AddOp = TI; 840 SubOp = FI; 841 } 842 843 if (AddOp) { 844 Value *OtherAddOp = nullptr; 845 if (SubOp->getOperand(0) == AddOp->getOperand(0)) { 846 OtherAddOp = AddOp->getOperand(1); 847 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) { 848 OtherAddOp = AddOp->getOperand(0); 849 } 850 851 if (OtherAddOp) { 852 // So at this point we know we have (Y -> OtherAddOp): 853 // select C, (add X, Y), (sub X, Z) 854 Value *NegVal; // Compute -Z 855 if (SI.getType()->isFPOrFPVectorTy()) { 856 NegVal = Builder.CreateFNeg(SubOp->getOperand(1)); 857 if (Instruction *NegInst = dyn_cast<Instruction>(NegVal)) { 858 FastMathFlags Flags = AddOp->getFastMathFlags(); 859 Flags &= SubOp->getFastMathFlags(); 860 NegInst->setFastMathFlags(Flags); 861 } 862 } else { 863 NegVal = Builder.CreateNeg(SubOp->getOperand(1)); 864 } 865 866 Value *NewTrueOp = OtherAddOp; 867 Value *NewFalseOp = NegVal; 868 if (AddOp != TI) 869 std::swap(NewTrueOp, NewFalseOp); 870 Value *NewSel = Builder.CreateSelect(CondVal, NewTrueOp, NewFalseOp, 871 SI.getName() + ".p"); 872 873 if (SI.getType()->isFPOrFPVectorTy()) { 874 Instruction *RI = 875 BinaryOperator::CreateFAdd(SubOp->getOperand(0), NewSel); 876 877 FastMathFlags Flags = AddOp->getFastMathFlags(); 878 Flags &= SubOp->getFastMathFlags(); 879 RI->setFastMathFlags(Flags); 880 return RI; 881 } else 882 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel); 883 } 884 } 885 return nullptr; 886 } 887 888 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) { 889 Value *CondVal = SI.getCondition(); 890 Value *TrueVal = SI.getTrueValue(); 891 Value *FalseVal = SI.getFalseValue(); 892 893 if (Value *V = 894 SimplifySelectInst(CondVal, TrueVal, FalseVal, DL, TLI, DT, AC)) 895 return replaceInstUsesWith(SI, V); 896 897 if (SI.getType()->isIntegerTy(1)) { 898 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) { 899 if (C->getZExtValue()) { 900 // Change: A = select B, true, C --> A = or B, C 901 return BinaryOperator::CreateOr(CondVal, FalseVal); 902 } 903 // Change: A = select B, false, C --> A = and !B, C 904 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 905 return BinaryOperator::CreateAnd(NotCond, FalseVal); 906 } 907 if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) { 908 if (!C->getZExtValue()) { 909 // Change: A = select B, C, false --> A = and B, C 910 return BinaryOperator::CreateAnd(CondVal, TrueVal); 911 } 912 // Change: A = select B, C, true --> A = or !B, C 913 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 914 return BinaryOperator::CreateOr(NotCond, TrueVal); 915 } 916 917 // select a, b, a -> a&b 918 // select a, a, b -> a|b 919 if (CondVal == TrueVal) 920 return BinaryOperator::CreateOr(CondVal, FalseVal); 921 if (CondVal == FalseVal) 922 return BinaryOperator::CreateAnd(CondVal, TrueVal); 923 924 // select a, ~a, b -> (~a)&b 925 // select a, b, ~a -> (~a)|b 926 if (match(TrueVal, m_Not(m_Specific(CondVal)))) 927 return BinaryOperator::CreateAnd(TrueVal, FalseVal); 928 if (match(FalseVal, m_Not(m_Specific(CondVal)))) 929 return BinaryOperator::CreateOr(TrueVal, FalseVal); 930 } 931 932 // Selecting between two integer constants? 933 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal)) 934 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) { 935 // select C, 1, 0 -> zext C to int 936 if (FalseValC->isZero() && TrueValC->getValue() == 1) 937 return new ZExtInst(CondVal, SI.getType()); 938 939 // select C, -1, 0 -> sext C to int 940 if (FalseValC->isZero() && TrueValC->isAllOnesValue()) 941 return new SExtInst(CondVal, SI.getType()); 942 943 // select C, 0, 1 -> zext !C to int 944 if (TrueValC->isZero() && FalseValC->getValue() == 1) { 945 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 946 return new ZExtInst(NotCond, SI.getType()); 947 } 948 949 // select C, 0, -1 -> sext !C to int 950 if (TrueValC->isZero() && FalseValC->isAllOnesValue()) { 951 Value *NotCond = Builder->CreateNot(CondVal, "not."+CondVal->getName()); 952 return new SExtInst(NotCond, SI.getType()); 953 } 954 955 if (Value *V = foldSelectICmpAnd(SI, TrueValC, FalseValC, Builder)) 956 return replaceInstUsesWith(SI, V); 957 } 958 959 // See if we are selecting two values based on a comparison of the two values. 960 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) { 961 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) { 962 // Transform (X == Y) ? X : Y -> Y 963 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 964 // This is not safe in general for floating point: 965 // consider X== -0, Y== +0. 966 // It becomes safe if either operand is a nonzero constant. 967 ConstantFP *CFPt, *CFPf; 968 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 969 !CFPt->getValueAPF().isZero()) || 970 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 971 !CFPf->getValueAPF().isZero())) 972 return replaceInstUsesWith(SI, FalseVal); 973 } 974 // Transform (X une Y) ? X : Y -> X 975 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 976 // This is not safe in general for floating point: 977 // consider X== -0, Y== +0. 978 // It becomes safe if either operand is a nonzero constant. 979 ConstantFP *CFPt, *CFPf; 980 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 981 !CFPt->getValueAPF().isZero()) || 982 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 983 !CFPf->getValueAPF().isZero())) 984 return replaceInstUsesWith(SI, TrueVal); 985 } 986 987 // Canonicalize to use ordered comparisons by swapping the select 988 // operands. 989 // 990 // e.g. 991 // (X ugt Y) ? X : Y -> (X ole Y) ? Y : X 992 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 993 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 994 IRBuilder<>::FastMathFlagGuard FMFG(*Builder); 995 Builder->setFastMathFlags(FCI->getFastMathFlags()); 996 Value *NewCond = Builder->CreateFCmp(InvPred, TrueVal, FalseVal, 997 FCI->getName() + ".inv"); 998 999 return SelectInst::Create(NewCond, FalseVal, TrueVal, 1000 SI.getName() + ".p"); 1001 } 1002 1003 // NOTE: if we wanted to, this is where to detect MIN/MAX 1004 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){ 1005 // Transform (X == Y) ? Y : X -> X 1006 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) { 1007 // This is not safe in general for floating point: 1008 // consider X== -0, Y== +0. 1009 // It becomes safe if either operand is a nonzero constant. 1010 ConstantFP *CFPt, *CFPf; 1011 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 1012 !CFPt->getValueAPF().isZero()) || 1013 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 1014 !CFPf->getValueAPF().isZero())) 1015 return replaceInstUsesWith(SI, FalseVal); 1016 } 1017 // Transform (X une Y) ? Y : X -> Y 1018 if (FCI->getPredicate() == FCmpInst::FCMP_UNE) { 1019 // This is not safe in general for floating point: 1020 // consider X== -0, Y== +0. 1021 // It becomes safe if either operand is a nonzero constant. 1022 ConstantFP *CFPt, *CFPf; 1023 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) && 1024 !CFPt->getValueAPF().isZero()) || 1025 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) && 1026 !CFPf->getValueAPF().isZero())) 1027 return replaceInstUsesWith(SI, TrueVal); 1028 } 1029 1030 // Canonicalize to use ordered comparisons by swapping the select 1031 // operands. 1032 // 1033 // e.g. 1034 // (X ugt Y) ? X : Y -> (X ole Y) ? X : Y 1035 if (FCI->hasOneUse() && FCmpInst::isUnordered(FCI->getPredicate())) { 1036 FCmpInst::Predicate InvPred = FCI->getInversePredicate(); 1037 IRBuilder<>::FastMathFlagGuard FMFG(*Builder); 1038 Builder->setFastMathFlags(FCI->getFastMathFlags()); 1039 Value *NewCond = Builder->CreateFCmp(InvPred, FalseVal, TrueVal, 1040 FCI->getName() + ".inv"); 1041 1042 return SelectInst::Create(NewCond, FalseVal, TrueVal, 1043 SI.getName() + ".p"); 1044 } 1045 1046 // NOTE: if we wanted to, this is where to detect MIN/MAX 1047 } 1048 // NOTE: if we wanted to, this is where to detect ABS 1049 } 1050 1051 // See if we are selecting two values based on a comparison of the two values. 1052 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) 1053 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI)) 1054 return Result; 1055 1056 if (Instruction *Add = foldAddSubSelect(SI, *Builder)) 1057 return Add; 1058 1059 auto *TI = dyn_cast<Instruction>(TrueVal); 1060 auto *FI = dyn_cast<Instruction>(FalseVal); 1061 if (TI && FI && TI->hasOneUse() && FI->hasOneUse()) { 1062 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z)) 1063 if (TI->getOpcode() == FI->getOpcode()) 1064 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI)) 1065 return IV; 1066 } 1067 1068 // See if we can fold the select into one of our operands. 1069 if (SI.getType()->isIntOrIntVectorTy() || SI.getType()->isFPOrFPVectorTy()) { 1070 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal)) 1071 return FoldI; 1072 1073 Value *LHS, *RHS, *LHS2, *RHS2; 1074 Instruction::CastOps CastOp; 1075 SelectPatternResult SPR = matchSelectPattern(&SI, LHS, RHS, &CastOp); 1076 auto SPF = SPR.Flavor; 1077 1078 if (SelectPatternResult::isMinOrMax(SPF)) { 1079 // Canonicalize so that type casts are outside select patterns. 1080 if (LHS->getType()->getPrimitiveSizeInBits() != 1081 SI.getType()->getPrimitiveSizeInBits()) { 1082 CmpInst::Predicate Pred = getCmpPredicateForMinMax(SPF, SPR.Ordered); 1083 1084 Value *Cmp; 1085 if (CmpInst::isIntPredicate(Pred)) { 1086 Cmp = Builder->CreateICmp(Pred, LHS, RHS); 1087 } else { 1088 IRBuilder<>::FastMathFlagGuard FMFG(*Builder); 1089 auto FMF = cast<FPMathOperator>(SI.getCondition())->getFastMathFlags(); 1090 Builder->setFastMathFlags(FMF); 1091 Cmp = Builder->CreateFCmp(Pred, LHS, RHS); 1092 } 1093 1094 Value *NewSI = Builder->CreateCast(CastOp, 1095 Builder->CreateSelect(Cmp, LHS, RHS), 1096 SI.getType()); 1097 return replaceInstUsesWith(SI, NewSI); 1098 } 1099 } 1100 1101 if (SPF) { 1102 // MAX(MAX(a, b), a) -> MAX(a, b) 1103 // MIN(MIN(a, b), a) -> MIN(a, b) 1104 // MAX(MIN(a, b), a) -> a 1105 // MIN(MAX(a, b), a) -> a 1106 // ABS(ABS(a)) -> ABS(a) 1107 // NABS(NABS(a)) -> NABS(a) 1108 if (SelectPatternFlavor SPF2 = matchSelectPattern(LHS, LHS2, RHS2).Flavor) 1109 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2, 1110 SI, SPF, RHS)) 1111 return R; 1112 if (SelectPatternFlavor SPF2 = matchSelectPattern(RHS, LHS2, RHS2).Flavor) 1113 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2, 1114 SI, SPF, LHS)) 1115 return R; 1116 } 1117 1118 // MAX(~a, ~b) -> ~MIN(a, b) 1119 if (SPF == SPF_SMAX || SPF == SPF_UMAX) { 1120 if (IsFreeToInvert(LHS, LHS->hasNUses(2)) && 1121 IsFreeToInvert(RHS, RHS->hasNUses(2))) { 1122 1123 // This transform adds a xor operation and that extra cost needs to be 1124 // justified. We look for simplifications that will result from 1125 // applying this rule: 1126 1127 bool Profitable = 1128 (LHS->hasNUses(2) && match(LHS, m_Not(m_Value()))) || 1129 (RHS->hasNUses(2) && match(RHS, m_Not(m_Value()))) || 1130 (SI.hasOneUse() && match(*SI.user_begin(), m_Not(m_Value()))); 1131 1132 if (Profitable) { 1133 Value *NewLHS = Builder->CreateNot(LHS); 1134 Value *NewRHS = Builder->CreateNot(RHS); 1135 Value *NewCmp = SPF == SPF_SMAX 1136 ? Builder->CreateICmpSLT(NewLHS, NewRHS) 1137 : Builder->CreateICmpULT(NewLHS, NewRHS); 1138 Value *NewSI = 1139 Builder->CreateNot(Builder->CreateSelect(NewCmp, NewLHS, NewRHS)); 1140 return replaceInstUsesWith(SI, NewSI); 1141 } 1142 } 1143 } 1144 1145 // TODO. 1146 // ABS(-X) -> ABS(X) 1147 } 1148 1149 // See if we can fold the select into a phi node if the condition is a select. 1150 if (isa<PHINode>(SI.getCondition())) 1151 // The true/false values have to be live in the PHI predecessor's blocks. 1152 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) && 1153 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI)) 1154 if (Instruction *NV = FoldOpIntoPhi(SI)) 1155 return NV; 1156 1157 if (SelectInst *TrueSI = dyn_cast<SelectInst>(TrueVal)) { 1158 if (TrueSI->getCondition()->getType() == CondVal->getType()) { 1159 // select(C, select(C, a, b), c) -> select(C, a, c) 1160 if (TrueSI->getCondition() == CondVal) { 1161 if (SI.getTrueValue() == TrueSI->getTrueValue()) 1162 return nullptr; 1163 SI.setOperand(1, TrueSI->getTrueValue()); 1164 return &SI; 1165 } 1166 // select(C0, select(C1, a, b), b) -> select(C0&C1, a, b) 1167 // We choose this as normal form to enable folding on the And and shortening 1168 // paths for the values (this helps GetUnderlyingObjects() for example). 1169 if (TrueSI->getFalseValue() == FalseVal && TrueSI->hasOneUse()) { 1170 Value *And = Builder->CreateAnd(CondVal, TrueSI->getCondition()); 1171 SI.setOperand(0, And); 1172 SI.setOperand(1, TrueSI->getTrueValue()); 1173 return &SI; 1174 } 1175 } 1176 } 1177 if (SelectInst *FalseSI = dyn_cast<SelectInst>(FalseVal)) { 1178 if (FalseSI->getCondition()->getType() == CondVal->getType()) { 1179 // select(C, a, select(C, b, c)) -> select(C, a, c) 1180 if (FalseSI->getCondition() == CondVal) { 1181 if (SI.getFalseValue() == FalseSI->getFalseValue()) 1182 return nullptr; 1183 SI.setOperand(2, FalseSI->getFalseValue()); 1184 return &SI; 1185 } 1186 // select(C0, a, select(C1, a, b)) -> select(C0|C1, a, b) 1187 if (FalseSI->getTrueValue() == TrueVal && FalseSI->hasOneUse()) { 1188 Value *Or = Builder->CreateOr(CondVal, FalseSI->getCondition()); 1189 SI.setOperand(0, Or); 1190 SI.setOperand(2, FalseSI->getFalseValue()); 1191 return &SI; 1192 } 1193 } 1194 } 1195 1196 if (BinaryOperator::isNot(CondVal)) { 1197 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal)); 1198 SI.setOperand(1, FalseVal); 1199 SI.setOperand(2, TrueVal); 1200 return &SI; 1201 } 1202 1203 if (VectorType* VecTy = dyn_cast<VectorType>(SI.getType())) { 1204 unsigned VWidth = VecTy->getNumElements(); 1205 APInt UndefElts(VWidth, 0); 1206 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1207 if (Value *V = SimplifyDemandedVectorElts(&SI, AllOnesEltMask, UndefElts)) { 1208 if (V != &SI) 1209 return replaceInstUsesWith(SI, V); 1210 return &SI; 1211 } 1212 1213 if (isa<ConstantAggregateZero>(CondVal)) { 1214 return replaceInstUsesWith(SI, FalseVal); 1215 } 1216 } 1217 1218 // See if we can determine the result of this select based on a dominating 1219 // condition. 1220 BasicBlock *Parent = SI.getParent(); 1221 if (BasicBlock *Dom = Parent->getSinglePredecessor()) { 1222 auto *PBI = dyn_cast_or_null<BranchInst>(Dom->getTerminator()); 1223 if (PBI && PBI->isConditional() && 1224 PBI->getSuccessor(0) != PBI->getSuccessor(1) && 1225 (PBI->getSuccessor(0) == Parent || PBI->getSuccessor(1) == Parent)) { 1226 bool CondIsFalse = PBI->getSuccessor(1) == Parent; 1227 Optional<bool> Implication = isImpliedCondition( 1228 PBI->getCondition(), SI.getCondition(), DL, CondIsFalse); 1229 if (Implication) { 1230 Value *V = *Implication ? TrueVal : FalseVal; 1231 return replaceInstUsesWith(SI, V); 1232 } 1233 } 1234 } 1235 1236 return nullptr; 1237 } 1238