1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===// 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 routines for folding instructions into simpler forms 10 // that do not require creating new instructions. This does constant folding 11 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either 12 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value 13 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been 14 // simplified: This is usually true and assuming it simplifies the logic (if 15 // they have not been simplified then results are correct but maybe suboptimal). 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Analysis/InstructionSimplify.h" 20 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SetVector.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/Statistic.h" 25 #include "llvm/Analysis/AliasAnalysis.h" 26 #include "llvm/Analysis/AssumptionCache.h" 27 #include "llvm/Analysis/CaptureTracking.h" 28 #include "llvm/Analysis/CmpInstAnalysis.h" 29 #include "llvm/Analysis/ConstantFolding.h" 30 #include "llvm/Analysis/LoopAnalysisManager.h" 31 #include "llvm/Analysis/MemoryBuiltins.h" 32 #include "llvm/Analysis/OverflowInstAnalysis.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/Analysis/VectorUtils.h" 35 #include "llvm/IR/ConstantRange.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/Dominators.h" 38 #include "llvm/IR/GetElementPtrTypeIterator.h" 39 #include "llvm/IR/GlobalAlias.h" 40 #include "llvm/IR/InstrTypes.h" 41 #include "llvm/IR/Instructions.h" 42 #include "llvm/IR/Operator.h" 43 #include "llvm/IR/PatternMatch.h" 44 #include "llvm/IR/ValueHandle.h" 45 #include "llvm/Support/KnownBits.h" 46 #include <algorithm> 47 using namespace llvm; 48 using namespace llvm::PatternMatch; 49 50 #define DEBUG_TYPE "instsimplify" 51 52 enum { RecursionLimit = 3 }; 53 54 STATISTIC(NumExpand, "Number of expansions"); 55 STATISTIC(NumReassoc, "Number of reassociations"); 56 57 static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned); 58 static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned); 59 static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &, 60 const SimplifyQuery &, unsigned); 61 static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &, 62 unsigned); 63 static Value *SimplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &, 64 const SimplifyQuery &, unsigned); 65 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &, 66 unsigned); 67 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 68 const SimplifyQuery &Q, unsigned MaxRecurse); 69 static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned); 70 static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned); 71 static Value *SimplifyCastInst(unsigned, Value *, Type *, 72 const SimplifyQuery &, unsigned); 73 static Value *SimplifyGEPInst(Type *, ArrayRef<Value *>, bool, 74 const SimplifyQuery &, unsigned); 75 static Value *SimplifySelectInst(Value *, Value *, Value *, 76 const SimplifyQuery &, unsigned); 77 78 static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal, 79 Value *FalseVal) { 80 BinaryOperator::BinaryOps BinOpCode; 81 if (auto *BO = dyn_cast<BinaryOperator>(Cond)) 82 BinOpCode = BO->getOpcode(); 83 else 84 return nullptr; 85 86 CmpInst::Predicate ExpectedPred, Pred1, Pred2; 87 if (BinOpCode == BinaryOperator::Or) { 88 ExpectedPred = ICmpInst::ICMP_NE; 89 } else if (BinOpCode == BinaryOperator::And) { 90 ExpectedPred = ICmpInst::ICMP_EQ; 91 } else 92 return nullptr; 93 94 // %A = icmp eq %TV, %FV 95 // %B = icmp eq %X, %Y (and one of these is a select operand) 96 // %C = and %A, %B 97 // %D = select %C, %TV, %FV 98 // --> 99 // %FV 100 101 // %A = icmp ne %TV, %FV 102 // %B = icmp ne %X, %Y (and one of these is a select operand) 103 // %C = or %A, %B 104 // %D = select %C, %TV, %FV 105 // --> 106 // %TV 107 Value *X, *Y; 108 if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal), 109 m_Specific(FalseVal)), 110 m_ICmp(Pred2, m_Value(X), m_Value(Y)))) || 111 Pred1 != Pred2 || Pred1 != ExpectedPred) 112 return nullptr; 113 114 if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal) 115 return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal; 116 117 return nullptr; 118 } 119 120 /// For a boolean type or a vector of boolean type, return false or a vector 121 /// with every element false. 122 static Constant *getFalse(Type *Ty) { 123 return ConstantInt::getFalse(Ty); 124 } 125 126 /// For a boolean type or a vector of boolean type, return true or a vector 127 /// with every element true. 128 static Constant *getTrue(Type *Ty) { 129 return ConstantInt::getTrue(Ty); 130 } 131 132 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"? 133 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS, 134 Value *RHS) { 135 CmpInst *Cmp = dyn_cast<CmpInst>(V); 136 if (!Cmp) 137 return false; 138 CmpInst::Predicate CPred = Cmp->getPredicate(); 139 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1); 140 if (CPred == Pred && CLHS == LHS && CRHS == RHS) 141 return true; 142 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS && 143 CRHS == LHS; 144 } 145 146 /// Simplify comparison with true or false branch of select: 147 /// %sel = select i1 %cond, i32 %tv, i32 %fv 148 /// %cmp = icmp sle i32 %sel, %rhs 149 /// Compose new comparison by substituting %sel with either %tv or %fv 150 /// and see if it simplifies. 151 static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS, 152 Value *RHS, Value *Cond, 153 const SimplifyQuery &Q, unsigned MaxRecurse, 154 Constant *TrueOrFalse) { 155 Value *SimplifiedCmp = SimplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse); 156 if (SimplifiedCmp == Cond) { 157 // %cmp simplified to the select condition (%cond). 158 return TrueOrFalse; 159 } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) { 160 // It didn't simplify. However, if composed comparison is equivalent 161 // to the select condition (%cond) then we can replace it. 162 return TrueOrFalse; 163 } 164 return SimplifiedCmp; 165 } 166 167 /// Simplify comparison with true branch of select 168 static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS, 169 Value *RHS, Value *Cond, 170 const SimplifyQuery &Q, 171 unsigned MaxRecurse) { 172 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse, 173 getTrue(Cond->getType())); 174 } 175 176 /// Simplify comparison with false branch of select 177 static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS, 178 Value *RHS, Value *Cond, 179 const SimplifyQuery &Q, 180 unsigned MaxRecurse) { 181 return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse, 182 getFalse(Cond->getType())); 183 } 184 185 /// We know comparison with both branches of select can be simplified, but they 186 /// are not equal. This routine handles some logical simplifications. 187 static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp, 188 Value *Cond, 189 const SimplifyQuery &Q, 190 unsigned MaxRecurse) { 191 // If the false value simplified to false, then the result of the compare 192 // is equal to "Cond && TCmp". This also catches the case when the false 193 // value simplified to false and the true value to true, returning "Cond". 194 // Folding select to and/or isn't poison-safe in general; impliesPoison 195 // checks whether folding it does not convert a well-defined value into 196 // poison. 197 if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond)) 198 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse)) 199 return V; 200 // If the true value simplified to true, then the result of the compare 201 // is equal to "Cond || FCmp". 202 if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond)) 203 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse)) 204 return V; 205 // Finally, if the false value simplified to true and the true value to 206 // false, then the result of the compare is equal to "!Cond". 207 if (match(FCmp, m_One()) && match(TCmp, m_Zero())) 208 if (Value *V = SimplifyXorInst( 209 Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse)) 210 return V; 211 return nullptr; 212 } 213 214 /// Does the given value dominate the specified phi node? 215 static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) { 216 Instruction *I = dyn_cast<Instruction>(V); 217 if (!I) 218 // Arguments and constants dominate all instructions. 219 return true; 220 221 // If we are processing instructions (and/or basic blocks) that have not been 222 // fully added to a function, the parent nodes may still be null. Simply 223 // return the conservative answer in these cases. 224 if (!I->getParent() || !P->getParent() || !I->getFunction()) 225 return false; 226 227 // If we have a DominatorTree then do a precise test. 228 if (DT) 229 return DT->dominates(I, P); 230 231 // Otherwise, if the instruction is in the entry block and is not an invoke, 232 // then it obviously dominates all phi nodes. 233 if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) && 234 !isa<CallBrInst>(I)) 235 return true; 236 237 return false; 238 } 239 240 /// Try to simplify a binary operator of form "V op OtherOp" where V is 241 /// "(B0 opex B1)" by distributing 'op' across 'opex' as 242 /// "(B0 op OtherOp) opex (B1 op OtherOp)". 243 static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V, 244 Value *OtherOp, Instruction::BinaryOps OpcodeToExpand, 245 const SimplifyQuery &Q, unsigned MaxRecurse) { 246 auto *B = dyn_cast<BinaryOperator>(V); 247 if (!B || B->getOpcode() != OpcodeToExpand) 248 return nullptr; 249 Value *B0 = B->getOperand(0), *B1 = B->getOperand(1); 250 Value *L = SimplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), 251 MaxRecurse); 252 if (!L) 253 return nullptr; 254 Value *R = SimplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), 255 MaxRecurse); 256 if (!R) 257 return nullptr; 258 259 // Does the expanded pair of binops simplify to the existing binop? 260 if ((L == B0 && R == B1) || 261 (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) { 262 ++NumExpand; 263 return B; 264 } 265 266 // Otherwise, return "L op' R" if it simplifies. 267 Value *S = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse); 268 if (!S) 269 return nullptr; 270 271 ++NumExpand; 272 return S; 273 } 274 275 /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by 276 /// distributing op over op'. 277 static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, 278 Value *L, Value *R, 279 Instruction::BinaryOps OpcodeToExpand, 280 const SimplifyQuery &Q, 281 unsigned MaxRecurse) { 282 // Recursion is always used, so bail out at once if we already hit the limit. 283 if (!MaxRecurse--) 284 return nullptr; 285 286 if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse)) 287 return V; 288 if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse)) 289 return V; 290 return nullptr; 291 } 292 293 /// Generic simplifications for associative binary operations. 294 /// Returns the simpler value, or null if none was found. 295 static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode, 296 Value *LHS, Value *RHS, 297 const SimplifyQuery &Q, 298 unsigned MaxRecurse) { 299 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!"); 300 301 // Recursion is always used, so bail out at once if we already hit the limit. 302 if (!MaxRecurse--) 303 return nullptr; 304 305 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 306 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 307 308 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely. 309 if (Op0 && Op0->getOpcode() == Opcode) { 310 Value *A = Op0->getOperand(0); 311 Value *B = Op0->getOperand(1); 312 Value *C = RHS; 313 314 // Does "B op C" simplify? 315 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 316 // It does! Return "A op V" if it simplifies or is already available. 317 // If V equals B then "A op V" is just the LHS. 318 if (V == B) return LHS; 319 // Otherwise return "A op V" if it simplifies. 320 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) { 321 ++NumReassoc; 322 return W; 323 } 324 } 325 } 326 327 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely. 328 if (Op1 && Op1->getOpcode() == Opcode) { 329 Value *A = LHS; 330 Value *B = Op1->getOperand(0); 331 Value *C = Op1->getOperand(1); 332 333 // Does "A op B" simplify? 334 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) { 335 // It does! Return "V op C" if it simplifies or is already available. 336 // If V equals B then "V op C" is just the RHS. 337 if (V == B) return RHS; 338 // Otherwise return "V op C" if it simplifies. 339 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) { 340 ++NumReassoc; 341 return W; 342 } 343 } 344 } 345 346 // The remaining transforms require commutativity as well as associativity. 347 if (!Instruction::isCommutative(Opcode)) 348 return nullptr; 349 350 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely. 351 if (Op0 && Op0->getOpcode() == Opcode) { 352 Value *A = Op0->getOperand(0); 353 Value *B = Op0->getOperand(1); 354 Value *C = RHS; 355 356 // Does "C op A" simplify? 357 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 358 // It does! Return "V op B" if it simplifies or is already available. 359 // If V equals A then "V op B" is just the LHS. 360 if (V == A) return LHS; 361 // Otherwise return "V op B" if it simplifies. 362 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) { 363 ++NumReassoc; 364 return W; 365 } 366 } 367 } 368 369 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely. 370 if (Op1 && Op1->getOpcode() == Opcode) { 371 Value *A = LHS; 372 Value *B = Op1->getOperand(0); 373 Value *C = Op1->getOperand(1); 374 375 // Does "C op A" simplify? 376 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 377 // It does! Return "B op V" if it simplifies or is already available. 378 // If V equals C then "B op V" is just the RHS. 379 if (V == C) return RHS; 380 // Otherwise return "B op V" if it simplifies. 381 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) { 382 ++NumReassoc; 383 return W; 384 } 385 } 386 } 387 388 return nullptr; 389 } 390 391 /// In the case of a binary operation with a select instruction as an operand, 392 /// try to simplify the binop by seeing whether evaluating it on both branches 393 /// of the select results in the same value. Returns the common value if so, 394 /// otherwise returns null. 395 static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS, 396 Value *RHS, const SimplifyQuery &Q, 397 unsigned MaxRecurse) { 398 // Recursion is always used, so bail out at once if we already hit the limit. 399 if (!MaxRecurse--) 400 return nullptr; 401 402 SelectInst *SI; 403 if (isa<SelectInst>(LHS)) { 404 SI = cast<SelectInst>(LHS); 405 } else { 406 assert(isa<SelectInst>(RHS) && "No select instruction operand!"); 407 SI = cast<SelectInst>(RHS); 408 } 409 410 // Evaluate the BinOp on the true and false branches of the select. 411 Value *TV; 412 Value *FV; 413 if (SI == LHS) { 414 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse); 415 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse); 416 } else { 417 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse); 418 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse); 419 } 420 421 // If they simplified to the same value, then return the common value. 422 // If they both failed to simplify then return null. 423 if (TV == FV) 424 return TV; 425 426 // If one branch simplified to undef, return the other one. 427 if (TV && Q.isUndefValue(TV)) 428 return FV; 429 if (FV && Q.isUndefValue(FV)) 430 return TV; 431 432 // If applying the operation did not change the true and false select values, 433 // then the result of the binop is the select itself. 434 if (TV == SI->getTrueValue() && FV == SI->getFalseValue()) 435 return SI; 436 437 // If one branch simplified and the other did not, and the simplified 438 // value is equal to the unsimplified one, return the simplified value. 439 // For example, select (cond, X, X & Z) & Z -> X & Z. 440 if ((FV && !TV) || (TV && !FV)) { 441 // Check that the simplified value has the form "X op Y" where "op" is the 442 // same as the original operation. 443 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV); 444 if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) { 445 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS". 446 // We already know that "op" is the same as for the simplified value. See 447 // if the operands match too. If so, return the simplified value. 448 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue(); 449 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS; 450 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch; 451 if (Simplified->getOperand(0) == UnsimplifiedLHS && 452 Simplified->getOperand(1) == UnsimplifiedRHS) 453 return Simplified; 454 if (Simplified->isCommutative() && 455 Simplified->getOperand(1) == UnsimplifiedLHS && 456 Simplified->getOperand(0) == UnsimplifiedRHS) 457 return Simplified; 458 } 459 } 460 461 return nullptr; 462 } 463 464 /// In the case of a comparison with a select instruction, try to simplify the 465 /// comparison by seeing whether both branches of the select result in the same 466 /// value. Returns the common value if so, otherwise returns null. 467 /// For example, if we have: 468 /// %tmp = select i1 %cmp, i32 1, i32 2 469 /// %cmp1 = icmp sle i32 %tmp, 3 470 /// We can simplify %cmp1 to true, because both branches of select are 471 /// less than 3. We compose new comparison by substituting %tmp with both 472 /// branches of select and see if it can be simplified. 473 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS, 474 Value *RHS, const SimplifyQuery &Q, 475 unsigned MaxRecurse) { 476 // Recursion is always used, so bail out at once if we already hit the limit. 477 if (!MaxRecurse--) 478 return nullptr; 479 480 // Make sure the select is on the LHS. 481 if (!isa<SelectInst>(LHS)) { 482 std::swap(LHS, RHS); 483 Pred = CmpInst::getSwappedPredicate(Pred); 484 } 485 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!"); 486 SelectInst *SI = cast<SelectInst>(LHS); 487 Value *Cond = SI->getCondition(); 488 Value *TV = SI->getTrueValue(); 489 Value *FV = SI->getFalseValue(); 490 491 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it. 492 // Does "cmp TV, RHS" simplify? 493 Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse); 494 if (!TCmp) 495 return nullptr; 496 497 // Does "cmp FV, RHS" simplify? 498 Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse); 499 if (!FCmp) 500 return nullptr; 501 502 // If both sides simplified to the same value, then use it as the result of 503 // the original comparison. 504 if (TCmp == FCmp) 505 return TCmp; 506 507 // The remaining cases only make sense if the select condition has the same 508 // type as the result of the comparison, so bail out if this is not so. 509 if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy()) 510 return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse); 511 512 return nullptr; 513 } 514 515 /// In the case of a binary operation with an operand that is a PHI instruction, 516 /// try to simplify the binop by seeing whether evaluating it on the incoming 517 /// phi values yields the same result for every value. If so returns the common 518 /// value, otherwise returns null. 519 static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS, 520 Value *RHS, const SimplifyQuery &Q, 521 unsigned MaxRecurse) { 522 // Recursion is always used, so bail out at once if we already hit the limit. 523 if (!MaxRecurse--) 524 return nullptr; 525 526 PHINode *PI; 527 if (isa<PHINode>(LHS)) { 528 PI = cast<PHINode>(LHS); 529 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 530 if (!valueDominatesPHI(RHS, PI, Q.DT)) 531 return nullptr; 532 } else { 533 assert(isa<PHINode>(RHS) && "No PHI instruction operand!"); 534 PI = cast<PHINode>(RHS); 535 // Bail out if LHS and the phi may be mutually interdependent due to a loop. 536 if (!valueDominatesPHI(LHS, PI, Q.DT)) 537 return nullptr; 538 } 539 540 // Evaluate the BinOp on the incoming phi values. 541 Value *CommonValue = nullptr; 542 for (Value *Incoming : PI->incoming_values()) { 543 // If the incoming value is the phi node itself, it can safely be skipped. 544 if (Incoming == PI) continue; 545 Value *V = PI == LHS ? 546 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) : 547 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse); 548 // If the operation failed to simplify, or simplified to a different value 549 // to previously, then give up. 550 if (!V || (CommonValue && V != CommonValue)) 551 return nullptr; 552 CommonValue = V; 553 } 554 555 return CommonValue; 556 } 557 558 /// In the case of a comparison with a PHI instruction, try to simplify the 559 /// comparison by seeing whether comparing with all of the incoming phi values 560 /// yields the same result every time. If so returns the common result, 561 /// otherwise returns null. 562 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 563 const SimplifyQuery &Q, unsigned MaxRecurse) { 564 // Recursion is always used, so bail out at once if we already hit the limit. 565 if (!MaxRecurse--) 566 return nullptr; 567 568 // Make sure the phi is on the LHS. 569 if (!isa<PHINode>(LHS)) { 570 std::swap(LHS, RHS); 571 Pred = CmpInst::getSwappedPredicate(Pred); 572 } 573 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!"); 574 PHINode *PI = cast<PHINode>(LHS); 575 576 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 577 if (!valueDominatesPHI(RHS, PI, Q.DT)) 578 return nullptr; 579 580 // Evaluate the BinOp on the incoming phi values. 581 Value *CommonValue = nullptr; 582 for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) { 583 Value *Incoming = PI->getIncomingValue(u); 584 Instruction *InTI = PI->getIncomingBlock(u)->getTerminator(); 585 // If the incoming value is the phi node itself, it can safely be skipped. 586 if (Incoming == PI) continue; 587 // Change the context instruction to the "edge" that flows into the phi. 588 // This is important because that is where incoming is actually "evaluated" 589 // even though it is used later somewhere else. 590 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI), 591 MaxRecurse); 592 // If the operation failed to simplify, or simplified to a different value 593 // to previously, then give up. 594 if (!V || (CommonValue && V != CommonValue)) 595 return nullptr; 596 CommonValue = V; 597 } 598 599 return CommonValue; 600 } 601 602 static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode, 603 Value *&Op0, Value *&Op1, 604 const SimplifyQuery &Q) { 605 if (auto *CLHS = dyn_cast<Constant>(Op0)) { 606 if (auto *CRHS = dyn_cast<Constant>(Op1)) 607 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL); 608 609 // Canonicalize the constant to the RHS if this is a commutative operation. 610 if (Instruction::isCommutative(Opcode)) 611 std::swap(Op0, Op1); 612 } 613 return nullptr; 614 } 615 616 /// Given operands for an Add, see if we can fold the result. 617 /// If not, this returns null. 618 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, 619 const SimplifyQuery &Q, unsigned MaxRecurse) { 620 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q)) 621 return C; 622 623 // X + poison -> poison 624 if (isa<PoisonValue>(Op1)) 625 return Op1; 626 627 // X + undef -> undef 628 if (Q.isUndefValue(Op1)) 629 return Op1; 630 631 // X + 0 -> X 632 if (match(Op1, m_Zero())) 633 return Op0; 634 635 // If two operands are negative, return 0. 636 if (isKnownNegation(Op0, Op1)) 637 return Constant::getNullValue(Op0->getType()); 638 639 // X + (Y - X) -> Y 640 // (Y - X) + X -> Y 641 // Eg: X + -X -> 0 642 Value *Y = nullptr; 643 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) || 644 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1)))) 645 return Y; 646 647 // X + ~X -> -1 since ~X = -X-1 648 Type *Ty = Op0->getType(); 649 if (match(Op0, m_Not(m_Specific(Op1))) || 650 match(Op1, m_Not(m_Specific(Op0)))) 651 return Constant::getAllOnesValue(Ty); 652 653 // add nsw/nuw (xor Y, signmask), signmask --> Y 654 // The no-wrapping add guarantees that the top bit will be set by the add. 655 // Therefore, the xor must be clearing the already set sign bit of Y. 656 if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) && 657 match(Op0, m_Xor(m_Value(Y), m_SignMask()))) 658 return Y; 659 660 // add nuw %x, -1 -> -1, because %x can only be 0. 661 if (IsNUW && match(Op1, m_AllOnes())) 662 return Op1; // Which is -1. 663 664 /// i1 add -> xor. 665 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 666 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 667 return V; 668 669 // Try some generic simplifications for associative operations. 670 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, 671 MaxRecurse)) 672 return V; 673 674 // Threading Add over selects and phi nodes is pointless, so don't bother. 675 // Threading over the select in "A + select(cond, B, C)" means evaluating 676 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and 677 // only if B and C are equal. If B and C are equal then (since we assume 678 // that operands have already been simplified) "select(cond, B, C)" should 679 // have been simplified to the common value of B and C already. Analysing 680 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly 681 // for threading over phi nodes. 682 683 return nullptr; 684 } 685 686 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW, 687 const SimplifyQuery &Query) { 688 return ::SimplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit); 689 } 690 691 /// Compute the base pointer and cumulative constant offsets for V. 692 /// 693 /// This strips all constant offsets off of V, leaving it the base pointer, and 694 /// accumulates the total constant offset applied in the returned constant. It 695 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 696 /// no constant offsets applied. 697 /// 698 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't 699 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc. 700 /// folding. 701 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V, 702 bool AllowNonInbounds = false) { 703 assert(V->getType()->isPtrOrPtrVectorTy()); 704 705 APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType())); 706 707 V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds); 708 // As that strip may trace through `addrspacecast`, need to sext or trunc 709 // the offset calculated. 710 Type *IntIdxTy = DL.getIndexType(V->getType())->getScalarType(); 711 Offset = Offset.sextOrTrunc(IntIdxTy->getIntegerBitWidth()); 712 713 Constant *OffsetIntPtr = ConstantInt::get(IntIdxTy, Offset); 714 if (VectorType *VecTy = dyn_cast<VectorType>(V->getType())) 715 return ConstantVector::getSplat(VecTy->getElementCount(), OffsetIntPtr); 716 return OffsetIntPtr; 717 } 718 719 /// Compute the constant difference between two pointer values. 720 /// If the difference is not a constant, returns zero. 721 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS, 722 Value *RHS) { 723 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 724 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 725 726 // If LHS and RHS are not related via constant offsets to the same base 727 // value, there is nothing we can do here. 728 if (LHS != RHS) 729 return nullptr; 730 731 // Otherwise, the difference of LHS - RHS can be computed as: 732 // LHS - RHS 733 // = (LHSOffset + Base) - (RHSOffset + Base) 734 // = LHSOffset - RHSOffset 735 return ConstantExpr::getSub(LHSOffset, RHSOffset); 736 } 737 738 /// Given operands for a Sub, see if we can fold the result. 739 /// If not, this returns null. 740 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 741 const SimplifyQuery &Q, unsigned MaxRecurse) { 742 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q)) 743 return C; 744 745 // X - poison -> poison 746 // poison - X -> poison 747 if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1)) 748 return PoisonValue::get(Op0->getType()); 749 750 // X - undef -> undef 751 // undef - X -> undef 752 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 753 return UndefValue::get(Op0->getType()); 754 755 // X - 0 -> X 756 if (match(Op1, m_Zero())) 757 return Op0; 758 759 // X - X -> 0 760 if (Op0 == Op1) 761 return Constant::getNullValue(Op0->getType()); 762 763 // Is this a negation? 764 if (match(Op0, m_Zero())) { 765 // 0 - X -> 0 if the sub is NUW. 766 if (isNUW) 767 return Constant::getNullValue(Op0->getType()); 768 769 KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 770 if (Known.Zero.isMaxSignedValue()) { 771 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then 772 // Op1 must be 0 because negating the minimum signed value is undefined. 773 if (isNSW) 774 return Constant::getNullValue(Op0->getType()); 775 776 // 0 - X -> X if X is 0 or the minimum signed value. 777 return Op1; 778 } 779 } 780 781 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies. 782 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X 783 Value *X = nullptr, *Y = nullptr, *Z = Op1; 784 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z 785 // See if "V === Y - Z" simplifies. 786 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1)) 787 // It does! Now see if "X + V" simplifies. 788 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) { 789 // It does, we successfully reassociated! 790 ++NumReassoc; 791 return W; 792 } 793 // See if "V === X - Z" simplifies. 794 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 795 // It does! Now see if "Y + V" simplifies. 796 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) { 797 // It does, we successfully reassociated! 798 ++NumReassoc; 799 return W; 800 } 801 } 802 803 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies. 804 // For example, X - (X + 1) -> -1 805 X = Op0; 806 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z) 807 // See if "V === X - Y" simplifies. 808 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 809 // It does! Now see if "V - Z" simplifies. 810 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) { 811 // It does, we successfully reassociated! 812 ++NumReassoc; 813 return W; 814 } 815 // See if "V === X - Z" simplifies. 816 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 817 // It does! Now see if "V - Y" simplifies. 818 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) { 819 // It does, we successfully reassociated! 820 ++NumReassoc; 821 return W; 822 } 823 } 824 825 // Z - (X - Y) -> (Z - X) + Y if everything simplifies. 826 // For example, X - (X - Y) -> Y. 827 Z = Op0; 828 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y) 829 // See if "V === Z - X" simplifies. 830 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1)) 831 // It does! Now see if "V + Y" simplifies. 832 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) { 833 // It does, we successfully reassociated! 834 ++NumReassoc; 835 return W; 836 } 837 838 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies. 839 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) && 840 match(Op1, m_Trunc(m_Value(Y)))) 841 if (X->getType() == Y->getType()) 842 // See if "V === X - Y" simplifies. 843 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 844 // It does! Now see if "trunc V" simplifies. 845 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(), 846 Q, MaxRecurse - 1)) 847 // It does, return the simplified "trunc V". 848 return W; 849 850 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...). 851 if (match(Op0, m_PtrToInt(m_Value(X))) && 852 match(Op1, m_PtrToInt(m_Value(Y)))) 853 if (Constant *Result = computePointerDifference(Q.DL, X, Y)) 854 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true); 855 856 // i1 sub -> xor. 857 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 858 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 859 return V; 860 861 // Threading Sub over selects and phi nodes is pointless, so don't bother. 862 // Threading over the select in "A - select(cond, B, C)" means evaluating 863 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and 864 // only if B and C are equal. If B and C are equal then (since we assume 865 // that operands have already been simplified) "select(cond, B, C)" should 866 // have been simplified to the common value of B and C already. Analysing 867 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly 868 // for threading over phi nodes. 869 870 return nullptr; 871 } 872 873 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 874 const SimplifyQuery &Q) { 875 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); 876 } 877 878 /// Given operands for a Mul, see if we can fold the result. 879 /// If not, this returns null. 880 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 881 unsigned MaxRecurse) { 882 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q)) 883 return C; 884 885 // X * poison -> poison 886 if (isa<PoisonValue>(Op1)) 887 return Op1; 888 889 // X * undef -> 0 890 // X * 0 -> 0 891 if (Q.isUndefValue(Op1) || match(Op1, m_Zero())) 892 return Constant::getNullValue(Op0->getType()); 893 894 // X * 1 -> X 895 if (match(Op1, m_One())) 896 return Op0; 897 898 // (X / Y) * Y -> X if the division is exact. 899 Value *X = nullptr; 900 if (Q.IIQ.UseInstrInfo && 901 (match(Op0, 902 m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y 903 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y) 904 return X; 905 906 // i1 mul -> and. 907 if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1)) 908 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1)) 909 return V; 910 911 // Try some generic simplifications for associative operations. 912 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, 913 MaxRecurse)) 914 return V; 915 916 // Mul distributes over Add. Try some generic simplifications based on this. 917 if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1, 918 Instruction::Add, Q, MaxRecurse)) 919 return V; 920 921 // If the operation is with the result of a select instruction, check whether 922 // operating on either branch of the select always yields the same value. 923 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 924 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, 925 MaxRecurse)) 926 return V; 927 928 // If the operation is with the result of a phi instruction, check whether 929 // operating on all incoming values of the phi always yields the same value. 930 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 931 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, 932 MaxRecurse)) 933 return V; 934 935 return nullptr; 936 } 937 938 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 939 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit); 940 } 941 942 /// Check for common or similar folds of integer division or integer remainder. 943 /// This applies to all 4 opcodes (sdiv/udiv/srem/urem). 944 static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0, 945 Value *Op1, const SimplifyQuery &Q) { 946 bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv); 947 bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem); 948 949 Type *Ty = Op0->getType(); 950 951 // X / undef -> poison 952 // X % undef -> poison 953 if (Q.isUndefValue(Op1)) 954 return PoisonValue::get(Ty); 955 956 // X / 0 -> poison 957 // X % 0 -> poison 958 // We don't need to preserve faults! 959 if (match(Op1, m_Zero())) 960 return PoisonValue::get(Ty); 961 962 // If any element of a constant divisor fixed width vector is zero or undef 963 // the behavior is undefined and we can fold the whole op to poison. 964 auto *Op1C = dyn_cast<Constant>(Op1); 965 auto *VTy = dyn_cast<FixedVectorType>(Ty); 966 if (Op1C && VTy) { 967 unsigned NumElts = VTy->getNumElements(); 968 for (unsigned i = 0; i != NumElts; ++i) { 969 Constant *Elt = Op1C->getAggregateElement(i); 970 if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt))) 971 return PoisonValue::get(Ty); 972 } 973 } 974 975 // poison / X -> poison 976 // poison % X -> poison 977 if (isa<PoisonValue>(Op0)) 978 return Op0; 979 980 // undef / X -> 0 981 // undef % X -> 0 982 if (Q.isUndefValue(Op0)) 983 return Constant::getNullValue(Ty); 984 985 // 0 / X -> 0 986 // 0 % X -> 0 987 if (match(Op0, m_Zero())) 988 return Constant::getNullValue(Op0->getType()); 989 990 // X / X -> 1 991 // X % X -> 0 992 if (Op0 == Op1) 993 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty); 994 995 // X / 1 -> X 996 // X % 1 -> 0 997 // If this is a boolean op (single-bit element type), we can't have 998 // division-by-zero or remainder-by-zero, so assume the divisor is 1. 999 // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1. 1000 Value *X; 1001 if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) || 1002 (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 1003 return IsDiv ? Op0 : Constant::getNullValue(Ty); 1004 1005 // If X * Y does not overflow, then: 1006 // X * Y / Y -> X 1007 // X * Y % Y -> 0 1008 if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) { 1009 auto *Mul = cast<OverflowingBinaryOperator>(Op0); 1010 // The multiplication can't overflow if it is defined not to, or if 1011 // X == A / Y for some A. 1012 if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) || 1013 (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) || 1014 (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) || 1015 (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) { 1016 return IsDiv ? X : Constant::getNullValue(Op0->getType()); 1017 } 1018 } 1019 1020 return nullptr; 1021 } 1022 1023 /// Given a predicate and two operands, return true if the comparison is true. 1024 /// This is a helper for div/rem simplification where we return some other value 1025 /// when we can prove a relationship between the operands. 1026 static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS, 1027 const SimplifyQuery &Q, unsigned MaxRecurse) { 1028 Value *V = SimplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse); 1029 Constant *C = dyn_cast_or_null<Constant>(V); 1030 return (C && C->isAllOnesValue()); 1031 } 1032 1033 /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer 1034 /// to simplify X % Y to X. 1035 static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q, 1036 unsigned MaxRecurse, bool IsSigned) { 1037 // Recursion is always used, so bail out at once if we already hit the limit. 1038 if (!MaxRecurse--) 1039 return false; 1040 1041 if (IsSigned) { 1042 // |X| / |Y| --> 0 1043 // 1044 // We require that 1 operand is a simple constant. That could be extended to 1045 // 2 variables if we computed the sign bit for each. 1046 // 1047 // Make sure that a constant is not the minimum signed value because taking 1048 // the abs() of that is undefined. 1049 Type *Ty = X->getType(); 1050 const APInt *C; 1051 if (match(X, m_APInt(C)) && !C->isMinSignedValue()) { 1052 // Is the variable divisor magnitude always greater than the constant 1053 // dividend magnitude? 1054 // |Y| > |C| --> Y < -abs(C) or Y > abs(C) 1055 Constant *PosDividendC = ConstantInt::get(Ty, C->abs()); 1056 Constant *NegDividendC = ConstantInt::get(Ty, -C->abs()); 1057 if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) || 1058 isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse)) 1059 return true; 1060 } 1061 if (match(Y, m_APInt(C))) { 1062 // Special-case: we can't take the abs() of a minimum signed value. If 1063 // that's the divisor, then all we have to do is prove that the dividend 1064 // is also not the minimum signed value. 1065 if (C->isMinSignedValue()) 1066 return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse); 1067 1068 // Is the variable dividend magnitude always less than the constant 1069 // divisor magnitude? 1070 // |X| < |C| --> X > -abs(C) and X < abs(C) 1071 Constant *PosDivisorC = ConstantInt::get(Ty, C->abs()); 1072 Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs()); 1073 if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) && 1074 isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse)) 1075 return true; 1076 } 1077 return false; 1078 } 1079 1080 // IsSigned == false. 1081 // Is the dividend unsigned less than the divisor? 1082 return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse); 1083 } 1084 1085 /// These are simplifications common to SDiv and UDiv. 1086 static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1087 const SimplifyQuery &Q, unsigned MaxRecurse) { 1088 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1089 return C; 1090 1091 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q)) 1092 return V; 1093 1094 bool IsSigned = Opcode == Instruction::SDiv; 1095 1096 // (X rem Y) / Y -> 0 1097 if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1098 (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1099 return Constant::getNullValue(Op0->getType()); 1100 1101 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow 1102 ConstantInt *C1, *C2; 1103 if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) && 1104 match(Op1, m_ConstantInt(C2))) { 1105 bool Overflow; 1106 (void)C1->getValue().umul_ov(C2->getValue(), Overflow); 1107 if (Overflow) 1108 return Constant::getNullValue(Op0->getType()); 1109 } 1110 1111 // If the operation is with the result of a select instruction, check whether 1112 // operating on either branch of the select always yields the same value. 1113 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1114 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1115 return V; 1116 1117 // If the operation is with the result of a phi instruction, check whether 1118 // operating on all incoming values of the phi always yields the same value. 1119 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1120 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1121 return V; 1122 1123 if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned)) 1124 return Constant::getNullValue(Op0->getType()); 1125 1126 return nullptr; 1127 } 1128 1129 /// These are simplifications common to SRem and URem. 1130 static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1131 const SimplifyQuery &Q, unsigned MaxRecurse) { 1132 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1133 return C; 1134 1135 if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q)) 1136 return V; 1137 1138 // (X % Y) % Y -> X % Y 1139 if ((Opcode == Instruction::SRem && 1140 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1141 (Opcode == Instruction::URem && 1142 match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1143 return Op0; 1144 1145 // (X << Y) % X -> 0 1146 if (Q.IIQ.UseInstrInfo && 1147 ((Opcode == Instruction::SRem && 1148 match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) || 1149 (Opcode == Instruction::URem && 1150 match(Op0, m_NUWShl(m_Specific(Op1), m_Value()))))) 1151 return Constant::getNullValue(Op0->getType()); 1152 1153 // If the operation is with the result of a select instruction, check whether 1154 // operating on either branch of the select always yields the same value. 1155 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1156 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1157 return V; 1158 1159 // If the operation is with the result of a phi instruction, check whether 1160 // operating on all incoming values of the phi always yields the same value. 1161 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1162 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1163 return V; 1164 1165 // If X / Y == 0, then X % Y == X. 1166 if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem)) 1167 return Op0; 1168 1169 return nullptr; 1170 } 1171 1172 /// Given operands for an SDiv, see if we can fold the result. 1173 /// If not, this returns null. 1174 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1175 unsigned MaxRecurse) { 1176 // If two operands are negated and no signed overflow, return -1. 1177 if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true)) 1178 return Constant::getAllOnesValue(Op0->getType()); 1179 1180 return simplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse); 1181 } 1182 1183 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1184 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit); 1185 } 1186 1187 /// Given operands for a UDiv, see if we can fold the result. 1188 /// If not, this returns null. 1189 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1190 unsigned MaxRecurse) { 1191 return simplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse); 1192 } 1193 1194 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1195 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit); 1196 } 1197 1198 /// Given operands for an SRem, see if we can fold the result. 1199 /// If not, this returns null. 1200 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1201 unsigned MaxRecurse) { 1202 // If the divisor is 0, the result is undefined, so assume the divisor is -1. 1203 // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0 1204 Value *X; 1205 if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) 1206 return ConstantInt::getNullValue(Op0->getType()); 1207 1208 // If the two operands are negated, return 0. 1209 if (isKnownNegation(Op0, Op1)) 1210 return ConstantInt::getNullValue(Op0->getType()); 1211 1212 return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse); 1213 } 1214 1215 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1216 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit); 1217 } 1218 1219 /// Given operands for a URem, see if we can fold the result. 1220 /// If not, this returns null. 1221 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 1222 unsigned MaxRecurse) { 1223 return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse); 1224 } 1225 1226 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 1227 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit); 1228 } 1229 1230 /// Returns true if a shift by \c Amount always yields poison. 1231 static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) { 1232 Constant *C = dyn_cast<Constant>(Amount); 1233 if (!C) 1234 return false; 1235 1236 // X shift by undef -> poison because it may shift by the bitwidth. 1237 if (Q.isUndefValue(C)) 1238 return true; 1239 1240 // Shifting by the bitwidth or more is undefined. 1241 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1242 if (CI->getValue().uge(CI->getType()->getScalarSizeInBits())) 1243 return true; 1244 1245 // If all lanes of a vector shift are undefined the whole shift is. 1246 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) { 1247 for (unsigned I = 0, 1248 E = cast<FixedVectorType>(C->getType())->getNumElements(); 1249 I != E; ++I) 1250 if (!isPoisonShift(C->getAggregateElement(I), Q)) 1251 return false; 1252 return true; 1253 } 1254 1255 return false; 1256 } 1257 1258 /// Given operands for an Shl, LShr or AShr, see if we can fold the result. 1259 /// If not, this returns null. 1260 static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0, 1261 Value *Op1, bool IsNSW, const SimplifyQuery &Q, 1262 unsigned MaxRecurse) { 1263 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q)) 1264 return C; 1265 1266 // poison shift by X -> poison 1267 if (isa<PoisonValue>(Op0)) 1268 return Op0; 1269 1270 // 0 shift by X -> 0 1271 if (match(Op0, m_Zero())) 1272 return Constant::getNullValue(Op0->getType()); 1273 1274 // X shift by 0 -> X 1275 // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones 1276 // would be poison. 1277 Value *X; 1278 if (match(Op1, m_Zero()) || 1279 (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))) 1280 return Op0; 1281 1282 // Fold undefined shifts. 1283 if (isPoisonShift(Op1, Q)) 1284 return PoisonValue::get(Op0->getType()); 1285 1286 // If the operation is with the result of a select instruction, check whether 1287 // operating on either branch of the select always yields the same value. 1288 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1289 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1290 return V; 1291 1292 // If the operation is with the result of a phi instruction, check whether 1293 // operating on all incoming values of the phi always yields the same value. 1294 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1295 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1296 return V; 1297 1298 // If any bits in the shift amount make that value greater than or equal to 1299 // the number of bits in the type, the shift is undefined. 1300 KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1301 if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth())) 1302 return PoisonValue::get(Op0->getType()); 1303 1304 // If all valid bits in the shift amount are known zero, the first operand is 1305 // unchanged. 1306 unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth()); 1307 if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits) 1308 return Op0; 1309 1310 // Check for nsw shl leading to a poison value. 1311 if (IsNSW) { 1312 assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction"); 1313 KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1314 KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt); 1315 1316 if (KnownVal.Zero.isSignBitSet()) 1317 KnownShl.Zero.setSignBit(); 1318 if (KnownVal.One.isSignBitSet()) 1319 KnownShl.One.setSignBit(); 1320 1321 if (KnownShl.hasConflict()) 1322 return PoisonValue::get(Op0->getType()); 1323 } 1324 1325 return nullptr; 1326 } 1327 1328 /// Given operands for an Shl, LShr or AShr, see if we can 1329 /// fold the result. If not, this returns null. 1330 static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0, 1331 Value *Op1, bool isExact, const SimplifyQuery &Q, 1332 unsigned MaxRecurse) { 1333 if (Value *V = 1334 SimplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse)) 1335 return V; 1336 1337 // X >> X -> 0 1338 if (Op0 == Op1) 1339 return Constant::getNullValue(Op0->getType()); 1340 1341 // undef >> X -> 0 1342 // undef >> X -> undef (if it's exact) 1343 if (Q.isUndefValue(Op0)) 1344 return isExact ? Op0 : Constant::getNullValue(Op0->getType()); 1345 1346 // The low bit cannot be shifted out of an exact shift if it is set. 1347 if (isExact) { 1348 KnownBits Op0Known = computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT); 1349 if (Op0Known.One[0]) 1350 return Op0; 1351 } 1352 1353 return nullptr; 1354 } 1355 1356 /// Given operands for an Shl, see if we can fold the result. 1357 /// If not, this returns null. 1358 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1359 const SimplifyQuery &Q, unsigned MaxRecurse) { 1360 if (Value *V = 1361 SimplifyShift(Instruction::Shl, Op0, Op1, isNSW, Q, MaxRecurse)) 1362 return V; 1363 1364 // undef << X -> 0 1365 // undef << X -> undef if (if it's NSW/NUW) 1366 if (Q.isUndefValue(Op0)) 1367 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType()); 1368 1369 // (X >> A) << A -> X 1370 Value *X; 1371 if (Q.IIQ.UseInstrInfo && 1372 match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1))))) 1373 return X; 1374 1375 // shl nuw i8 C, %x -> C iff C has sign bit set. 1376 if (isNUW && match(Op0, m_Negative())) 1377 return Op0; 1378 // NOTE: could use computeKnownBits() / LazyValueInfo, 1379 // but the cost-benefit analysis suggests it isn't worth it. 1380 1381 return nullptr; 1382 } 1383 1384 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1385 const SimplifyQuery &Q) { 1386 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit); 1387 } 1388 1389 /// Given operands for an LShr, see if we can fold the result. 1390 /// If not, this returns null. 1391 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1392 const SimplifyQuery &Q, unsigned MaxRecurse) { 1393 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q, 1394 MaxRecurse)) 1395 return V; 1396 1397 // (X << A) >> A -> X 1398 Value *X; 1399 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1)))) 1400 return X; 1401 1402 // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A. 1403 // We can return X as we do in the above case since OR alters no bits in X. 1404 // SimplifyDemandedBits in InstCombine can do more general optimization for 1405 // bit manipulation. This pattern aims to provide opportunities for other 1406 // optimizers by supporting a simple but common case in InstSimplify. 1407 Value *Y; 1408 const APInt *ShRAmt, *ShLAmt; 1409 if (match(Op1, m_APInt(ShRAmt)) && 1410 match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) && 1411 *ShRAmt == *ShLAmt) { 1412 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1413 const unsigned EffWidthY = YKnown.countMaxActiveBits(); 1414 if (ShRAmt->uge(EffWidthY)) 1415 return X; 1416 } 1417 1418 return nullptr; 1419 } 1420 1421 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1422 const SimplifyQuery &Q) { 1423 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit); 1424 } 1425 1426 /// Given operands for an AShr, see if we can fold the result. 1427 /// If not, this returns null. 1428 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1429 const SimplifyQuery &Q, unsigned MaxRecurse) { 1430 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q, 1431 MaxRecurse)) 1432 return V; 1433 1434 // -1 >>a X --> -1 1435 // (-1 << X) a>> X --> -1 1436 // Do not return Op0 because it may contain undef elements if it's a vector. 1437 if (match(Op0, m_AllOnes()) || 1438 match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1)))) 1439 return Constant::getAllOnesValue(Op0->getType()); 1440 1441 // (X << A) >> A -> X 1442 Value *X; 1443 if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1)))) 1444 return X; 1445 1446 // Arithmetic shifting an all-sign-bit value is a no-op. 1447 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 1448 if (NumSignBits == Op0->getType()->getScalarSizeInBits()) 1449 return Op0; 1450 1451 return nullptr; 1452 } 1453 1454 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1455 const SimplifyQuery &Q) { 1456 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit); 1457 } 1458 1459 /// Commuted variants are assumed to be handled by calling this function again 1460 /// with the parameters swapped. 1461 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp, 1462 ICmpInst *UnsignedICmp, bool IsAnd, 1463 const SimplifyQuery &Q) { 1464 Value *X, *Y; 1465 1466 ICmpInst::Predicate EqPred; 1467 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) || 1468 !ICmpInst::isEquality(EqPred)) 1469 return nullptr; 1470 1471 ICmpInst::Predicate UnsignedPred; 1472 1473 Value *A, *B; 1474 // Y = (A - B); 1475 if (match(Y, m_Sub(m_Value(A), m_Value(B)))) { 1476 if (match(UnsignedICmp, 1477 m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) && 1478 ICmpInst::isUnsigned(UnsignedPred)) { 1479 // A >=/<= B || (A - B) != 0 <--> true 1480 if ((UnsignedPred == ICmpInst::ICMP_UGE || 1481 UnsignedPred == ICmpInst::ICMP_ULE) && 1482 EqPred == ICmpInst::ICMP_NE && !IsAnd) 1483 return ConstantInt::getTrue(UnsignedICmp->getType()); 1484 // A </> B && (A - B) == 0 <--> false 1485 if ((UnsignedPred == ICmpInst::ICMP_ULT || 1486 UnsignedPred == ICmpInst::ICMP_UGT) && 1487 EqPred == ICmpInst::ICMP_EQ && IsAnd) 1488 return ConstantInt::getFalse(UnsignedICmp->getType()); 1489 1490 // A </> B && (A - B) != 0 <--> A </> B 1491 // A </> B || (A - B) != 0 <--> (A - B) != 0 1492 if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT || 1493 UnsignedPred == ICmpInst::ICMP_UGT)) 1494 return IsAnd ? UnsignedICmp : ZeroICmp; 1495 1496 // A <=/>= B && (A - B) == 0 <--> (A - B) == 0 1497 // A <=/>= B || (A - B) == 0 <--> A <=/>= B 1498 if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE || 1499 UnsignedPred == ICmpInst::ICMP_UGE)) 1500 return IsAnd ? ZeroICmp : UnsignedICmp; 1501 } 1502 1503 // Given Y = (A - B) 1504 // Y >= A && Y != 0 --> Y >= A iff B != 0 1505 // Y < A || Y == 0 --> Y < A iff B != 0 1506 if (match(UnsignedICmp, 1507 m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) { 1508 if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd && 1509 EqPred == ICmpInst::ICMP_NE && 1510 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1511 return UnsignedICmp; 1512 if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd && 1513 EqPred == ICmpInst::ICMP_EQ && 1514 isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1515 return UnsignedICmp; 1516 } 1517 } 1518 1519 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) && 1520 ICmpInst::isUnsigned(UnsignedPred)) 1521 ; 1522 else if (match(UnsignedICmp, 1523 m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) && 1524 ICmpInst::isUnsigned(UnsignedPred)) 1525 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred); 1526 else 1527 return nullptr; 1528 1529 // X > Y && Y == 0 --> Y == 0 iff X != 0 1530 // X > Y || Y == 0 --> X > Y iff X != 0 1531 if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ && 1532 isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1533 return IsAnd ? ZeroICmp : UnsignedICmp; 1534 1535 // X <= Y && Y != 0 --> X <= Y iff X != 0 1536 // X <= Y || Y != 0 --> Y != 0 iff X != 0 1537 if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE && 1538 isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT)) 1539 return IsAnd ? UnsignedICmp : ZeroICmp; 1540 1541 // The transforms below here are expected to be handled more generally with 1542 // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's 1543 // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap, 1544 // these are candidates for removal. 1545 1546 // X < Y && Y != 0 --> X < Y 1547 // X < Y || Y != 0 --> Y != 0 1548 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE) 1549 return IsAnd ? UnsignedICmp : ZeroICmp; 1550 1551 // X >= Y && Y == 0 --> Y == 0 1552 // X >= Y || Y == 0 --> X >= Y 1553 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ) 1554 return IsAnd ? ZeroICmp : UnsignedICmp; 1555 1556 // X < Y && Y == 0 --> false 1557 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ && 1558 IsAnd) 1559 return getFalse(UnsignedICmp->getType()); 1560 1561 // X >= Y || Y != 0 --> true 1562 if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE && 1563 !IsAnd) 1564 return getTrue(UnsignedICmp->getType()); 1565 1566 return nullptr; 1567 } 1568 1569 /// Commuted variants are assumed to be handled by calling this function again 1570 /// with the parameters swapped. 1571 static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { 1572 ICmpInst::Predicate Pred0, Pred1; 1573 Value *A ,*B; 1574 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || 1575 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) 1576 return nullptr; 1577 1578 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B). 1579 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we 1580 // can eliminate Op1 from this 'and'. 1581 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) 1582 return Op0; 1583 1584 // Check for any combination of predicates that are guaranteed to be disjoint. 1585 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || 1586 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) || 1587 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) || 1588 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)) 1589 return getFalse(Op0->getType()); 1590 1591 return nullptr; 1592 } 1593 1594 /// Commuted variants are assumed to be handled by calling this function again 1595 /// with the parameters swapped. 1596 static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) { 1597 ICmpInst::Predicate Pred0, Pred1; 1598 Value *A ,*B; 1599 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) || 1600 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B)))) 1601 return nullptr; 1602 1603 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B). 1604 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we 1605 // can eliminate Op0 from this 'or'. 1606 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1)) 1607 return Op1; 1608 1609 // Check for any combination of predicates that cover the entire range of 1610 // possibilities. 1611 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) || 1612 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) || 1613 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) || 1614 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE)) 1615 return getTrue(Op0->getType()); 1616 1617 return nullptr; 1618 } 1619 1620 /// Test if a pair of compares with a shared operand and 2 constants has an 1621 /// empty set intersection, full set union, or if one compare is a superset of 1622 /// the other. 1623 static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1, 1624 bool IsAnd) { 1625 // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)). 1626 if (Cmp0->getOperand(0) != Cmp1->getOperand(0)) 1627 return nullptr; 1628 1629 const APInt *C0, *C1; 1630 if (!match(Cmp0->getOperand(1), m_APInt(C0)) || 1631 !match(Cmp1->getOperand(1), m_APInt(C1))) 1632 return nullptr; 1633 1634 auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0); 1635 auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1); 1636 1637 // For and-of-compares, check if the intersection is empty: 1638 // (icmp X, C0) && (icmp X, C1) --> empty set --> false 1639 if (IsAnd && Range0.intersectWith(Range1).isEmptySet()) 1640 return getFalse(Cmp0->getType()); 1641 1642 // For or-of-compares, check if the union is full: 1643 // (icmp X, C0) || (icmp X, C1) --> full set --> true 1644 if (!IsAnd && Range0.unionWith(Range1).isFullSet()) 1645 return getTrue(Cmp0->getType()); 1646 1647 // Is one range a superset of the other? 1648 // If this is and-of-compares, take the smaller set: 1649 // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42 1650 // If this is or-of-compares, take the larger set: 1651 // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4 1652 if (Range0.contains(Range1)) 1653 return IsAnd ? Cmp1 : Cmp0; 1654 if (Range1.contains(Range0)) 1655 return IsAnd ? Cmp0 : Cmp1; 1656 1657 return nullptr; 1658 } 1659 1660 static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1, 1661 bool IsAnd) { 1662 ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate(); 1663 if (!match(Cmp0->getOperand(1), m_Zero()) || 1664 !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1) 1665 return nullptr; 1666 1667 if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ)) 1668 return nullptr; 1669 1670 // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)". 1671 Value *X = Cmp0->getOperand(0); 1672 Value *Y = Cmp1->getOperand(0); 1673 1674 // If one of the compares is a masked version of a (not) null check, then 1675 // that compare implies the other, so we eliminate the other. Optionally, look 1676 // through a pointer-to-int cast to match a null check of a pointer type. 1677 1678 // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0 1679 // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0 1680 // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0 1681 // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0 1682 if (match(Y, m_c_And(m_Specific(X), m_Value())) || 1683 match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value()))) 1684 return Cmp1; 1685 1686 // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0 1687 // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0 1688 // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0 1689 // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0 1690 if (match(X, m_c_And(m_Specific(Y), m_Value())) || 1691 match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value()))) 1692 return Cmp0; 1693 1694 return nullptr; 1695 } 1696 1697 static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, 1698 const InstrInfoQuery &IIQ) { 1699 // (icmp (add V, C0), C1) & (icmp V, C0) 1700 ICmpInst::Predicate Pred0, Pred1; 1701 const APInt *C0, *C1; 1702 Value *V; 1703 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) 1704 return nullptr; 1705 1706 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) 1707 return nullptr; 1708 1709 auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0)); 1710 if (AddInst->getOperand(1) != Op1->getOperand(1)) 1711 return nullptr; 1712 1713 Type *ITy = Op0->getType(); 1714 bool isNSW = IIQ.hasNoSignedWrap(AddInst); 1715 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst); 1716 1717 const APInt Delta = *C1 - *C0; 1718 if (C0->isStrictlyPositive()) { 1719 if (Delta == 2) { 1720 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT) 1721 return getFalse(ITy); 1722 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW) 1723 return getFalse(ITy); 1724 } 1725 if (Delta == 1) { 1726 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT) 1727 return getFalse(ITy); 1728 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW) 1729 return getFalse(ITy); 1730 } 1731 } 1732 if (C0->getBoolValue() && isNUW) { 1733 if (Delta == 2) 1734 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT) 1735 return getFalse(ITy); 1736 if (Delta == 1) 1737 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT) 1738 return getFalse(ITy); 1739 } 1740 1741 return nullptr; 1742 } 1743 1744 /// Try to eliminate compares with signed or unsigned min/max constants. 1745 static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1, 1746 bool IsAnd) { 1747 // Canonicalize an equality compare as Cmp0. 1748 if (Cmp1->isEquality()) 1749 std::swap(Cmp0, Cmp1); 1750 if (!Cmp0->isEquality()) 1751 return nullptr; 1752 1753 // The non-equality compare must include a common operand (X). Canonicalize 1754 // the common operand as operand 0 (the predicate is swapped if the common 1755 // operand was operand 1). 1756 ICmpInst::Predicate Pred0 = Cmp0->getPredicate(); 1757 Value *X = Cmp0->getOperand(0); 1758 ICmpInst::Predicate Pred1; 1759 bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value())); 1760 if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value()))) 1761 return nullptr; 1762 if (ICmpInst::isEquality(Pred1)) 1763 return nullptr; 1764 1765 // The equality compare must be against a constant. Flip bits if we matched 1766 // a bitwise not. Convert a null pointer constant to an integer zero value. 1767 APInt MinMaxC; 1768 const APInt *C; 1769 if (match(Cmp0->getOperand(1), m_APInt(C))) 1770 MinMaxC = HasNotOp ? ~*C : *C; 1771 else if (isa<ConstantPointerNull>(Cmp0->getOperand(1))) 1772 MinMaxC = APInt::getZero(8); 1773 else 1774 return nullptr; 1775 1776 // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1. 1777 if (!IsAnd) { 1778 Pred0 = ICmpInst::getInversePredicate(Pred0); 1779 Pred1 = ICmpInst::getInversePredicate(Pred1); 1780 } 1781 1782 // Normalize to unsigned compare and unsigned min/max value. 1783 // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255 1784 if (ICmpInst::isSigned(Pred1)) { 1785 Pred1 = ICmpInst::getUnsignedPredicate(Pred1); 1786 MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth()); 1787 } 1788 1789 // (X != MAX) && (X < Y) --> X < Y 1790 // (X == MAX) || (X >= Y) --> X >= Y 1791 if (MinMaxC.isMaxValue()) 1792 if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT) 1793 return Cmp1; 1794 1795 // (X != MIN) && (X > Y) --> X > Y 1796 // (X == MIN) || (X <= Y) --> X <= Y 1797 if (MinMaxC.isMinValue()) 1798 if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT) 1799 return Cmp1; 1800 1801 return nullptr; 1802 } 1803 1804 static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1, 1805 const SimplifyQuery &Q) { 1806 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q)) 1807 return X; 1808 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q)) 1809 return X; 1810 1811 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1)) 1812 return X; 1813 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op1, Op0)) 1814 return X; 1815 1816 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true)) 1817 return X; 1818 1819 if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true)) 1820 return X; 1821 1822 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true)) 1823 return X; 1824 1825 if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ)) 1826 return X; 1827 if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ)) 1828 return X; 1829 1830 return nullptr; 1831 } 1832 1833 static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1, 1834 const InstrInfoQuery &IIQ) { 1835 // (icmp (add V, C0), C1) | (icmp V, C0) 1836 ICmpInst::Predicate Pred0, Pred1; 1837 const APInt *C0, *C1; 1838 Value *V; 1839 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1)))) 1840 return nullptr; 1841 1842 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value()))) 1843 return nullptr; 1844 1845 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0)); 1846 if (AddInst->getOperand(1) != Op1->getOperand(1)) 1847 return nullptr; 1848 1849 Type *ITy = Op0->getType(); 1850 bool isNSW = IIQ.hasNoSignedWrap(AddInst); 1851 bool isNUW = IIQ.hasNoUnsignedWrap(AddInst); 1852 1853 const APInt Delta = *C1 - *C0; 1854 if (C0->isStrictlyPositive()) { 1855 if (Delta == 2) { 1856 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE) 1857 return getTrue(ITy); 1858 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW) 1859 return getTrue(ITy); 1860 } 1861 if (Delta == 1) { 1862 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE) 1863 return getTrue(ITy); 1864 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW) 1865 return getTrue(ITy); 1866 } 1867 } 1868 if (C0->getBoolValue() && isNUW) { 1869 if (Delta == 2) 1870 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE) 1871 return getTrue(ITy); 1872 if (Delta == 1) 1873 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE) 1874 return getTrue(ITy); 1875 } 1876 1877 return nullptr; 1878 } 1879 1880 static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1, 1881 const SimplifyQuery &Q) { 1882 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q)) 1883 return X; 1884 if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q)) 1885 return X; 1886 1887 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1)) 1888 return X; 1889 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op1, Op0)) 1890 return X; 1891 1892 if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false)) 1893 return X; 1894 1895 if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false)) 1896 return X; 1897 1898 if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false)) 1899 return X; 1900 1901 if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ)) 1902 return X; 1903 if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ)) 1904 return X; 1905 1906 return nullptr; 1907 } 1908 1909 static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI, 1910 FCmpInst *LHS, FCmpInst *RHS, bool IsAnd) { 1911 Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1); 1912 Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1); 1913 if (LHS0->getType() != RHS0->getType()) 1914 return nullptr; 1915 1916 FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate(); 1917 if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) || 1918 (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) { 1919 // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y 1920 // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X 1921 // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y 1922 // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X 1923 // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y 1924 // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X 1925 // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y 1926 // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X 1927 if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) || 1928 (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1))) 1929 return RHS; 1930 1931 // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y 1932 // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X 1933 // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y 1934 // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X 1935 // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y 1936 // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X 1937 // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y 1938 // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X 1939 if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) || 1940 (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1))) 1941 return LHS; 1942 } 1943 1944 return nullptr; 1945 } 1946 1947 static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, 1948 Value *Op0, Value *Op1, bool IsAnd) { 1949 // Look through casts of the 'and' operands to find compares. 1950 auto *Cast0 = dyn_cast<CastInst>(Op0); 1951 auto *Cast1 = dyn_cast<CastInst>(Op1); 1952 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() && 1953 Cast0->getSrcTy() == Cast1->getSrcTy()) { 1954 Op0 = Cast0->getOperand(0); 1955 Op1 = Cast1->getOperand(0); 1956 } 1957 1958 Value *V = nullptr; 1959 auto *ICmp0 = dyn_cast<ICmpInst>(Op0); 1960 auto *ICmp1 = dyn_cast<ICmpInst>(Op1); 1961 if (ICmp0 && ICmp1) 1962 V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q) 1963 : simplifyOrOfICmps(ICmp0, ICmp1, Q); 1964 1965 auto *FCmp0 = dyn_cast<FCmpInst>(Op0); 1966 auto *FCmp1 = dyn_cast<FCmpInst>(Op1); 1967 if (FCmp0 && FCmp1) 1968 V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd); 1969 1970 if (!V) 1971 return nullptr; 1972 if (!Cast0) 1973 return V; 1974 1975 // If we looked through casts, we can only handle a constant simplification 1976 // because we are not allowed to create a cast instruction here. 1977 if (auto *C = dyn_cast<Constant>(V)) 1978 return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType()); 1979 1980 return nullptr; 1981 } 1982 1983 /// Given a bitwise logic op, check if the operands are add/sub with a common 1984 /// source value and inverted constant (identity: C - X -> ~(X + ~C)). 1985 static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1, 1986 Instruction::BinaryOps Opcode) { 1987 assert(Op0->getType() == Op1->getType() && "Mismatched binop types"); 1988 assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op"); 1989 Value *X; 1990 Constant *C1, *C2; 1991 if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) && 1992 match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) || 1993 (match(Op1, m_Add(m_Value(X), m_Constant(C1))) && 1994 match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) { 1995 if (ConstantExpr::getNot(C1) == C2) { 1996 // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0 1997 // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1 1998 // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1 1999 Type *Ty = Op0->getType(); 2000 return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty) 2001 : ConstantInt::getAllOnesValue(Ty); 2002 } 2003 } 2004 return nullptr; 2005 } 2006 2007 /// Given operands for an And, see if we can fold the result. 2008 /// If not, this returns null. 2009 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 2010 unsigned MaxRecurse) { 2011 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q)) 2012 return C; 2013 2014 // X & poison -> poison 2015 if (isa<PoisonValue>(Op1)) 2016 return Op1; 2017 2018 // X & undef -> 0 2019 if (Q.isUndefValue(Op1)) 2020 return Constant::getNullValue(Op0->getType()); 2021 2022 // X & X = X 2023 if (Op0 == Op1) 2024 return Op0; 2025 2026 // X & 0 = 0 2027 if (match(Op1, m_Zero())) 2028 return Constant::getNullValue(Op0->getType()); 2029 2030 // X & -1 = X 2031 if (match(Op1, m_AllOnes())) 2032 return Op0; 2033 2034 // A & ~A = ~A & A = 0 2035 if (match(Op0, m_Not(m_Specific(Op1))) || 2036 match(Op1, m_Not(m_Specific(Op0)))) 2037 return Constant::getNullValue(Op0->getType()); 2038 2039 // (A | ?) & A = A 2040 if (match(Op0, m_c_Or(m_Specific(Op1), m_Value()))) 2041 return Op1; 2042 2043 // A & (A | ?) = A 2044 if (match(Op1, m_c_Or(m_Specific(Op0), m_Value()))) 2045 return Op0; 2046 2047 // (X | Y) & (X | ~Y) --> X (commuted 8 ways) 2048 Value *X, *Y; 2049 if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) && 2050 match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y)))) 2051 return X; 2052 if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) && 2053 match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y)))) 2054 return X; 2055 2056 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And)) 2057 return V; 2058 2059 // A mask that only clears known zeros of a shifted value is a no-op. 2060 const APInt *Mask; 2061 const APInt *ShAmt; 2062 if (match(Op1, m_APInt(Mask))) { 2063 // If all bits in the inverted and shifted mask are clear: 2064 // and (shl X, ShAmt), Mask --> shl X, ShAmt 2065 if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) && 2066 (~(*Mask)).lshr(*ShAmt).isZero()) 2067 return Op0; 2068 2069 // If all bits in the inverted and shifted mask are clear: 2070 // and (lshr X, ShAmt), Mask --> lshr X, ShAmt 2071 if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) && 2072 (~(*Mask)).shl(*ShAmt).isZero()) 2073 return Op0; 2074 } 2075 2076 // If we have a multiplication overflow check that is being 'and'ed with a 2077 // check that one of the multipliers is not zero, we can omit the 'and', and 2078 // only keep the overflow check. 2079 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true)) 2080 return Op1; 2081 if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true)) 2082 return Op0; 2083 2084 // A & (-A) = A if A is a power of two or zero. 2085 if (match(Op0, m_Neg(m_Specific(Op1))) || 2086 match(Op1, m_Neg(m_Specific(Op0)))) { 2087 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, 2088 Q.DT)) 2089 return Op0; 2090 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, 2091 Q.DT)) 2092 return Op1; 2093 } 2094 2095 // This is a similar pattern used for checking if a value is a power-of-2: 2096 // (A - 1) & A --> 0 (if A is a power-of-2 or 0) 2097 // A & (A - 1) --> 0 (if A is a power-of-2 or 0) 2098 if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) && 2099 isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT)) 2100 return Constant::getNullValue(Op1->getType()); 2101 if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) && 2102 isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT)) 2103 return Constant::getNullValue(Op0->getType()); 2104 2105 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true)) 2106 return V; 2107 2108 // Try some generic simplifications for associative operations. 2109 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, 2110 MaxRecurse)) 2111 return V; 2112 2113 // And distributes over Or. Try some generic simplifications based on this. 2114 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1, 2115 Instruction::Or, Q, MaxRecurse)) 2116 return V; 2117 2118 // And distributes over Xor. Try some generic simplifications based on this. 2119 if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1, 2120 Instruction::Xor, Q, MaxRecurse)) 2121 return V; 2122 2123 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) { 2124 if (Op0->getType()->isIntOrIntVectorTy(1)) { 2125 // A & (A && B) -> A && B 2126 if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero()))) 2127 return Op1; 2128 else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero()))) 2129 return Op0; 2130 } 2131 // If the operation is with the result of a select instruction, check 2132 // whether operating on either branch of the select always yields the same 2133 // value. 2134 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q, 2135 MaxRecurse)) 2136 return V; 2137 } 2138 2139 // If the operation is with the result of a phi instruction, check whether 2140 // operating on all incoming values of the phi always yields the same value. 2141 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 2142 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q, 2143 MaxRecurse)) 2144 return V; 2145 2146 // Assuming the effective width of Y is not larger than A, i.e. all bits 2147 // from X and Y are disjoint in (X << A) | Y, 2148 // if the mask of this AND op covers all bits of X or Y, while it covers 2149 // no bits from the other, we can bypass this AND op. E.g., 2150 // ((X << A) | Y) & Mask -> Y, 2151 // if Mask = ((1 << effective_width_of(Y)) - 1) 2152 // ((X << A) | Y) & Mask -> X << A, 2153 // if Mask = ((1 << effective_width_of(X)) - 1) << A 2154 // SimplifyDemandedBits in InstCombine can optimize the general case. 2155 // This pattern aims to help other passes for a common case. 2156 Value *XShifted; 2157 if (match(Op1, m_APInt(Mask)) && 2158 match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)), 2159 m_Value(XShifted)), 2160 m_Value(Y)))) { 2161 const unsigned Width = Op0->getType()->getScalarSizeInBits(); 2162 const unsigned ShftCnt = ShAmt->getLimitedValue(Width); 2163 const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2164 const unsigned EffWidthY = YKnown.countMaxActiveBits(); 2165 if (EffWidthY <= ShftCnt) { 2166 const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, 2167 Q.DT); 2168 const unsigned EffWidthX = XKnown.countMaxActiveBits(); 2169 const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY); 2170 const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt; 2171 // If the mask is extracting all bits from X or Y as is, we can skip 2172 // this AND op. 2173 if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask)) 2174 return Y; 2175 if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask)) 2176 return XShifted; 2177 } 2178 } 2179 2180 // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0 2181 // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0 2182 BinaryOperator *Or; 2183 if (match(Op0, m_c_Xor(m_Value(X), 2184 m_CombineAnd(m_BinOp(Or), 2185 m_c_Or(m_Deferred(X), m_Value(Y))))) && 2186 match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y)))) 2187 return Constant::getNullValue(Op0->getType()); 2188 2189 return nullptr; 2190 } 2191 2192 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 2193 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit); 2194 } 2195 2196 static Value *simplifyOrLogic(Value *X, Value *Y) { 2197 assert(X->getType() == Y->getType() && "Expected same type for 'or' ops"); 2198 Type *Ty = X->getType(); 2199 2200 // X | ~X --> -1 2201 if (match(Y, m_Not(m_Specific(X)))) 2202 return ConstantInt::getAllOnesValue(Ty); 2203 2204 // X | ~(X & ?) = -1 2205 if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value())))) 2206 return ConstantInt::getAllOnesValue(Ty); 2207 2208 // X | (X & ?) --> X 2209 if (match(Y, m_c_And(m_Specific(X), m_Value()))) 2210 return X; 2211 2212 Value *A, *B; 2213 2214 // (A ^ B) | (A | B) --> A | B 2215 // (A ^ B) | (B | A) --> B | A 2216 if (match(X, m_Xor(m_Value(A), m_Value(B))) && 2217 match(Y, m_c_Or(m_Specific(A), m_Specific(B)))) 2218 return Y; 2219 2220 // ~(A ^ B) | (A | B) --> -1 2221 // ~(A ^ B) | (B | A) --> -1 2222 if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) && 2223 match(Y, m_c_Or(m_Specific(A), m_Specific(B)))) 2224 return ConstantInt::getAllOnesValue(Ty); 2225 2226 // (A & ~B) | (A ^ B) --> A ^ B 2227 // (~B & A) | (A ^ B) --> A ^ B 2228 // (A & ~B) | (B ^ A) --> B ^ A 2229 // (~B & A) | (B ^ A) --> B ^ A 2230 if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) && 2231 match(Y, m_c_Xor(m_Specific(A), m_Specific(B)))) 2232 return Y; 2233 2234 // (~A ^ B) | (A & B) --> ~A ^ B 2235 // (B ^ ~A) | (A & B) --> B ^ ~A 2236 // (~A ^ B) | (B & A) --> ~A ^ B 2237 // (B ^ ~A) | (B & A) --> B ^ ~A 2238 if (match(X, m_c_Xor(m_Not(m_Value(A)), m_Value(B))) && 2239 match(Y, m_c_And(m_Specific(A), m_Specific(B)))) 2240 return X; 2241 2242 // (~A | B) | (A ^ B) --> -1 2243 // (~A | B) | (B ^ A) --> -1 2244 // (B | ~A) | (A ^ B) --> -1 2245 // (B | ~A) | (B ^ A) --> -1 2246 if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) && 2247 match(Y, m_c_Xor(m_Specific(A), m_Specific(B)))) 2248 return ConstantInt::getAllOnesValue(Ty); 2249 2250 // (~A & B) | ~(A | B) --> ~A 2251 // (~A & B) | ~(B | A) --> ~A 2252 // (B & ~A) | ~(A | B) --> ~A 2253 // (B & ~A) | ~(B | A) --> ~A 2254 Value *NotA; 2255 if (match(X, 2256 m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))), 2257 m_Value(B))) && 2258 match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B))))) 2259 return NotA; 2260 2261 // ~(A ^ B) | (A & B) --> ~(A ^ B) 2262 // ~(A ^ B) | (B & A) --> ~(A ^ B) 2263 Value *NotAB; 2264 if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))), 2265 m_Value(NotAB))) && 2266 match(Y, m_c_And(m_Specific(A), m_Specific(B)))) 2267 return NotAB; 2268 2269 // ~(A & B) | (A ^ B) --> ~(A & B) 2270 // ~(A & B) | (B ^ A) --> ~(A & B) 2271 if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))), 2272 m_Value(NotAB))) && 2273 match(Y, m_c_Xor(m_Specific(A), m_Specific(B)))) 2274 return NotAB; 2275 2276 return nullptr; 2277 } 2278 2279 /// Given operands for an Or, see if we can fold the result. 2280 /// If not, this returns null. 2281 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 2282 unsigned MaxRecurse) { 2283 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q)) 2284 return C; 2285 2286 // X | poison -> poison 2287 if (isa<PoisonValue>(Op1)) 2288 return Op1; 2289 2290 // X | undef -> -1 2291 // X | -1 = -1 2292 // Do not return Op1 because it may contain undef elements if it's a vector. 2293 if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes())) 2294 return Constant::getAllOnesValue(Op0->getType()); 2295 2296 // X | X = X 2297 // X | 0 = X 2298 if (Op0 == Op1 || match(Op1, m_Zero())) 2299 return Op0; 2300 2301 if (Value *R = simplifyOrLogic(Op0, Op1)) 2302 return R; 2303 if (Value *R = simplifyOrLogic(Op1, Op0)) 2304 return R; 2305 2306 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or)) 2307 return V; 2308 2309 // Rotated -1 is still -1: 2310 // (-1 << X) | (-1 >> (C - X)) --> -1 2311 // (-1 >> X) | (-1 << (C - X)) --> -1 2312 // ...with C <= bitwidth (and commuted variants). 2313 Value *X, *Y; 2314 if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) && 2315 match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) || 2316 (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) && 2317 match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) { 2318 const APInt *C; 2319 if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) || 2320 match(Y, m_Sub(m_APInt(C), m_Specific(X)))) && 2321 C->ule(X->getType()->getScalarSizeInBits())) { 2322 return ConstantInt::getAllOnesValue(X->getType()); 2323 } 2324 } 2325 2326 if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false)) 2327 return V; 2328 2329 // If we have a multiplication overflow check that is being 'and'ed with a 2330 // check that one of the multipliers is not zero, we can omit the 'and', and 2331 // only keep the overflow check. 2332 if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false)) 2333 return Op1; 2334 if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false)) 2335 return Op0; 2336 2337 // Try some generic simplifications for associative operations. 2338 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, 2339 MaxRecurse)) 2340 return V; 2341 2342 // Or distributes over And. Try some generic simplifications based on this. 2343 if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1, 2344 Instruction::And, Q, MaxRecurse)) 2345 return V; 2346 2347 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) { 2348 if (Op0->getType()->isIntOrIntVectorTy(1)) { 2349 // A | (A || B) -> A || B 2350 if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value()))) 2351 return Op1; 2352 else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value()))) 2353 return Op0; 2354 } 2355 // If the operation is with the result of a select instruction, check 2356 // whether operating on either branch of the select always yields the same 2357 // value. 2358 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, 2359 MaxRecurse)) 2360 return V; 2361 } 2362 2363 // (A & C1)|(B & C2) 2364 Value *A, *B; 2365 const APInt *C1, *C2; 2366 if (match(Op0, m_And(m_Value(A), m_APInt(C1))) && 2367 match(Op1, m_And(m_Value(B), m_APInt(C2)))) { 2368 if (*C1 == ~*C2) { 2369 // (A & C1)|(B & C2) 2370 // If we have: ((V + N) & C1) | (V & C2) 2371 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0 2372 // replace with V+N. 2373 Value *N; 2374 if (C2->isMask() && // C2 == 0+1+ 2375 match(A, m_c_Add(m_Specific(B), m_Value(N)))) { 2376 // Add commutes, try both ways. 2377 if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2378 return A; 2379 } 2380 // Or commutes, try both ways. 2381 if (C1->isMask() && 2382 match(B, m_c_Add(m_Specific(A), m_Value(N)))) { 2383 // Add commutes, try both ways. 2384 if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2385 return B; 2386 } 2387 } 2388 } 2389 2390 // If the operation is with the result of a phi instruction, check whether 2391 // operating on all incoming values of the phi always yields the same value. 2392 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 2393 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse)) 2394 return V; 2395 2396 return nullptr; 2397 } 2398 2399 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 2400 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit); 2401 } 2402 2403 /// Given operands for a Xor, see if we can fold the result. 2404 /// If not, this returns null. 2405 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q, 2406 unsigned MaxRecurse) { 2407 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q)) 2408 return C; 2409 2410 // A ^ undef -> undef 2411 if (Q.isUndefValue(Op1)) 2412 return Op1; 2413 2414 // A ^ 0 = A 2415 if (match(Op1, m_Zero())) 2416 return Op0; 2417 2418 // A ^ A = 0 2419 if (Op0 == Op1) 2420 return Constant::getNullValue(Op0->getType()); 2421 2422 // A ^ ~A = ~A ^ A = -1 2423 if (match(Op0, m_Not(m_Specific(Op1))) || 2424 match(Op1, m_Not(m_Specific(Op0)))) 2425 return Constant::getAllOnesValue(Op0->getType()); 2426 2427 auto foldAndOrNot = [](Value *X, Value *Y) -> Value * { 2428 Value *A, *B; 2429 // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants. 2430 if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) && 2431 match(Y, m_c_Or(m_Specific(A), m_Specific(B)))) 2432 return A; 2433 2434 // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants. 2435 // The 'not' op must contain a complete -1 operand (no undef elements for 2436 // vector) for the transform to be safe. 2437 Value *NotA; 2438 if (match(X, 2439 m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)), 2440 m_Value(B))) && 2441 match(Y, m_c_And(m_Specific(A), m_Specific(B)))) 2442 return NotA; 2443 2444 return nullptr; 2445 }; 2446 if (Value *R = foldAndOrNot(Op0, Op1)) 2447 return R; 2448 if (Value *R = foldAndOrNot(Op1, Op0)) 2449 return R; 2450 2451 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor)) 2452 return V; 2453 2454 // Try some generic simplifications for associative operations. 2455 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, 2456 MaxRecurse)) 2457 return V; 2458 2459 // Threading Xor over selects and phi nodes is pointless, so don't bother. 2460 // Threading over the select in "A ^ select(cond, B, C)" means evaluating 2461 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and 2462 // only if B and C are equal. If B and C are equal then (since we assume 2463 // that operands have already been simplified) "select(cond, B, C)" should 2464 // have been simplified to the common value of B and C already. Analysing 2465 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly 2466 // for threading over phi nodes. 2467 2468 return nullptr; 2469 } 2470 2471 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 2472 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit); 2473 } 2474 2475 2476 static Type *GetCompareTy(Value *Op) { 2477 return CmpInst::makeCmpResultType(Op->getType()); 2478 } 2479 2480 /// Rummage around inside V looking for something equivalent to the comparison 2481 /// "LHS Pred RHS". Return such a value if found, otherwise return null. 2482 /// Helper function for analyzing max/min idioms. 2483 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, 2484 Value *LHS, Value *RHS) { 2485 SelectInst *SI = dyn_cast<SelectInst>(V); 2486 if (!SI) 2487 return nullptr; 2488 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 2489 if (!Cmp) 2490 return nullptr; 2491 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); 2492 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) 2493 return Cmp; 2494 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && 2495 LHS == CmpRHS && RHS == CmpLHS) 2496 return Cmp; 2497 return nullptr; 2498 } 2499 2500 // A significant optimization not implemented here is assuming that alloca 2501 // addresses are not equal to incoming argument values. They don't *alias*, 2502 // as we say, but that doesn't mean they aren't equal, so we take a 2503 // conservative approach. 2504 // 2505 // This is inspired in part by C++11 5.10p1: 2506 // "Two pointers of the same type compare equal if and only if they are both 2507 // null, both point to the same function, or both represent the same 2508 // address." 2509 // 2510 // This is pretty permissive. 2511 // 2512 // It's also partly due to C11 6.5.9p6: 2513 // "Two pointers compare equal if and only if both are null pointers, both are 2514 // pointers to the same object (including a pointer to an object and a 2515 // subobject at its beginning) or function, both are pointers to one past the 2516 // last element of the same array object, or one is a pointer to one past the 2517 // end of one array object and the other is a pointer to the start of a 2518 // different array object that happens to immediately follow the first array 2519 // object in the address space.) 2520 // 2521 // C11's version is more restrictive, however there's no reason why an argument 2522 // couldn't be a one-past-the-end value for a stack object in the caller and be 2523 // equal to the beginning of a stack object in the callee. 2524 // 2525 // If the C and C++ standards are ever made sufficiently restrictive in this 2526 // area, it may be possible to update LLVM's semantics accordingly and reinstate 2527 // this optimization. 2528 static Constant * 2529 computePointerICmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 2530 const SimplifyQuery &Q) { 2531 const DataLayout &DL = Q.DL; 2532 const TargetLibraryInfo *TLI = Q.TLI; 2533 const DominatorTree *DT = Q.DT; 2534 const Instruction *CxtI = Q.CxtI; 2535 const InstrInfoQuery &IIQ = Q.IIQ; 2536 2537 // First, skip past any trivial no-ops. 2538 LHS = LHS->stripPointerCasts(); 2539 RHS = RHS->stripPointerCasts(); 2540 2541 // A non-null pointer is not equal to a null pointer. 2542 if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) && 2543 llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr, 2544 IIQ.UseInstrInfo)) 2545 return ConstantInt::get(GetCompareTy(LHS), 2546 !CmpInst::isTrueWhenEqual(Pred)); 2547 2548 // We can only fold certain predicates on pointer comparisons. 2549 switch (Pred) { 2550 default: 2551 return nullptr; 2552 2553 // Equality comaprisons are easy to fold. 2554 case CmpInst::ICMP_EQ: 2555 case CmpInst::ICMP_NE: 2556 break; 2557 2558 // We can only handle unsigned relational comparisons because 'inbounds' on 2559 // a GEP only protects against unsigned wrapping. 2560 case CmpInst::ICMP_UGT: 2561 case CmpInst::ICMP_UGE: 2562 case CmpInst::ICMP_ULT: 2563 case CmpInst::ICMP_ULE: 2564 // However, we have to switch them to their signed variants to handle 2565 // negative indices from the base pointer. 2566 Pred = ICmpInst::getSignedPredicate(Pred); 2567 break; 2568 } 2569 2570 // Strip off any constant offsets so that we can reason about them. 2571 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets 2572 // here and compare base addresses like AliasAnalysis does, however there are 2573 // numerous hazards. AliasAnalysis and its utilities rely on special rules 2574 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis 2575 // doesn't need to guarantee pointer inequality when it says NoAlias. 2576 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 2577 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 2578 2579 // If LHS and RHS are related via constant offsets to the same base 2580 // value, we can replace it with an icmp which just compares the offsets. 2581 if (LHS == RHS) 2582 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); 2583 2584 // Various optimizations for (in)equality comparisons. 2585 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { 2586 // Different non-empty allocations that exist at the same time have 2587 // different addresses (if the program can tell). Global variables always 2588 // exist, so they always exist during the lifetime of each other and all 2589 // allocas. Two different allocas usually have different addresses... 2590 // 2591 // However, if there's an @llvm.stackrestore dynamically in between two 2592 // allocas, they may have the same address. It's tempting to reduce the 2593 // scope of the problem by only looking at *static* allocas here. That would 2594 // cover the majority of allocas while significantly reducing the likelihood 2595 // of having an @llvm.stackrestore pop up in the middle. However, it's not 2596 // actually impossible for an @llvm.stackrestore to pop up in the middle of 2597 // an entry block. Also, if we have a block that's not attached to a 2598 // function, we can't tell if it's "static" under the current definition. 2599 // Theoretically, this problem could be fixed by creating a new kind of 2600 // instruction kind specifically for static allocas. Such a new instruction 2601 // could be required to be at the top of the entry block, thus preventing it 2602 // from being subject to a @llvm.stackrestore. Instcombine could even 2603 // convert regular allocas into these special allocas. It'd be nifty. 2604 // However, until then, this problem remains open. 2605 // 2606 // So, we'll assume that two non-empty allocas have different addresses 2607 // for now. 2608 // 2609 // With all that, if the offsets are within the bounds of their allocations 2610 // (and not one-past-the-end! so we can't use inbounds!), and their 2611 // allocations aren't the same, the pointers are not equal. 2612 // 2613 // Note that it's not necessary to check for LHS being a global variable 2614 // address, due to canonicalization and constant folding. 2615 if (isa<AllocaInst>(LHS) && 2616 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { 2617 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); 2618 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); 2619 uint64_t LHSSize, RHSSize; 2620 ObjectSizeOpts Opts; 2621 Opts.NullIsUnknownSize = 2622 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction()); 2623 if (LHSOffsetCI && RHSOffsetCI && 2624 getObjectSize(LHS, LHSSize, DL, TLI, Opts) && 2625 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) { 2626 const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); 2627 const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); 2628 if (!LHSOffsetValue.isNegative() && 2629 !RHSOffsetValue.isNegative() && 2630 LHSOffsetValue.ult(LHSSize) && 2631 RHSOffsetValue.ult(RHSSize)) { 2632 return ConstantInt::get(GetCompareTy(LHS), 2633 !CmpInst::isTrueWhenEqual(Pred)); 2634 } 2635 } 2636 2637 // Repeat the above check but this time without depending on DataLayout 2638 // or being able to compute a precise size. 2639 if (!cast<PointerType>(LHS->getType())->isEmptyTy() && 2640 !cast<PointerType>(RHS->getType())->isEmptyTy() && 2641 LHSOffset->isNullValue() && 2642 RHSOffset->isNullValue()) 2643 return ConstantInt::get(GetCompareTy(LHS), 2644 !CmpInst::isTrueWhenEqual(Pred)); 2645 } 2646 2647 // Even if an non-inbounds GEP occurs along the path we can still optimize 2648 // equality comparisons concerning the result. We avoid walking the whole 2649 // chain again by starting where the last calls to 2650 // stripAndComputeConstantOffsets left off and accumulate the offsets. 2651 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true); 2652 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true); 2653 if (LHS == RHS) 2654 return ConstantExpr::getICmp(Pred, 2655 ConstantExpr::getAdd(LHSOffset, LHSNoBound), 2656 ConstantExpr::getAdd(RHSOffset, RHSNoBound)); 2657 2658 // If one side of the equality comparison must come from a noalias call 2659 // (meaning a system memory allocation function), and the other side must 2660 // come from a pointer that cannot overlap with dynamically-allocated 2661 // memory within the lifetime of the current function (allocas, byval 2662 // arguments, globals), then determine the comparison result here. 2663 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs; 2664 getUnderlyingObjects(LHS, LHSUObjs); 2665 getUnderlyingObjects(RHS, RHSUObjs); 2666 2667 // Is the set of underlying objects all noalias calls? 2668 auto IsNAC = [](ArrayRef<const Value *> Objects) { 2669 return all_of(Objects, isNoAliasCall); 2670 }; 2671 2672 // Is the set of underlying objects all things which must be disjoint from 2673 // noalias calls. For allocas, we consider only static ones (dynamic 2674 // allocas might be transformed into calls to malloc not simultaneously 2675 // live with the compared-to allocation). For globals, we exclude symbols 2676 // that might be resolve lazily to symbols in another dynamically-loaded 2677 // library (and, thus, could be malloc'ed by the implementation). 2678 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) { 2679 return all_of(Objects, [](const Value *V) { 2680 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) 2681 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca(); 2682 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 2683 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() || 2684 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) && 2685 !GV->isThreadLocal(); 2686 if (const Argument *A = dyn_cast<Argument>(V)) 2687 return A->hasByValAttr(); 2688 return false; 2689 }); 2690 }; 2691 2692 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) || 2693 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs))) 2694 return ConstantInt::get(GetCompareTy(LHS), 2695 !CmpInst::isTrueWhenEqual(Pred)); 2696 2697 // Fold comparisons for non-escaping pointer even if the allocation call 2698 // cannot be elided. We cannot fold malloc comparison to null. Also, the 2699 // dynamic allocation call could be either of the operands. 2700 Value *MI = nullptr; 2701 if (isAllocLikeFn(LHS, TLI) && 2702 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT)) 2703 MI = LHS; 2704 else if (isAllocLikeFn(RHS, TLI) && 2705 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT)) 2706 MI = RHS; 2707 // FIXME: We should also fold the compare when the pointer escapes, but the 2708 // compare dominates the pointer escape 2709 if (MI && !PointerMayBeCaptured(MI, true, true)) 2710 return ConstantInt::get(GetCompareTy(LHS), 2711 CmpInst::isFalseWhenEqual(Pred)); 2712 } 2713 2714 // Otherwise, fail. 2715 return nullptr; 2716 } 2717 2718 /// Fold an icmp when its operands have i1 scalar type. 2719 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS, 2720 Value *RHS, const SimplifyQuery &Q) { 2721 Type *ITy = GetCompareTy(LHS); // The return type. 2722 Type *OpTy = LHS->getType(); // The operand type. 2723 if (!OpTy->isIntOrIntVectorTy(1)) 2724 return nullptr; 2725 2726 // A boolean compared to true/false can be reduced in 14 out of the 20 2727 // (10 predicates * 2 constants) possible combinations. The other 2728 // 6 cases require a 'not' of the LHS. 2729 2730 auto ExtractNotLHS = [](Value *V) -> Value * { 2731 Value *X; 2732 if (match(V, m_Not(m_Value(X)))) 2733 return X; 2734 return nullptr; 2735 }; 2736 2737 if (match(RHS, m_Zero())) { 2738 switch (Pred) { 2739 case CmpInst::ICMP_NE: // X != 0 -> X 2740 case CmpInst::ICMP_UGT: // X >u 0 -> X 2741 case CmpInst::ICMP_SLT: // X <s 0 -> X 2742 return LHS; 2743 2744 case CmpInst::ICMP_EQ: // not(X) == 0 -> X != 0 -> X 2745 case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X 2746 case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X 2747 if (Value *X = ExtractNotLHS(LHS)) 2748 return X; 2749 break; 2750 2751 case CmpInst::ICMP_ULT: // X <u 0 -> false 2752 case CmpInst::ICMP_SGT: // X >s 0 -> false 2753 return getFalse(ITy); 2754 2755 case CmpInst::ICMP_UGE: // X >=u 0 -> true 2756 case CmpInst::ICMP_SLE: // X <=s 0 -> true 2757 return getTrue(ITy); 2758 2759 default: break; 2760 } 2761 } else if (match(RHS, m_One())) { 2762 switch (Pred) { 2763 case CmpInst::ICMP_EQ: // X == 1 -> X 2764 case CmpInst::ICMP_UGE: // X >=u 1 -> X 2765 case CmpInst::ICMP_SLE: // X <=s -1 -> X 2766 return LHS; 2767 2768 case CmpInst::ICMP_NE: // not(X) != 1 -> X == 1 -> X 2769 case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u 1 -> X 2770 case CmpInst::ICMP_SGT: // not(X) >s 1 -> X <=s -1 -> X 2771 if (Value *X = ExtractNotLHS(LHS)) 2772 return X; 2773 break; 2774 2775 case CmpInst::ICMP_UGT: // X >u 1 -> false 2776 case CmpInst::ICMP_SLT: // X <s -1 -> false 2777 return getFalse(ITy); 2778 2779 case CmpInst::ICMP_ULE: // X <=u 1 -> true 2780 case CmpInst::ICMP_SGE: // X >=s -1 -> true 2781 return getTrue(ITy); 2782 2783 default: break; 2784 } 2785 } 2786 2787 switch (Pred) { 2788 default: 2789 break; 2790 case ICmpInst::ICMP_UGE: 2791 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false)) 2792 return getTrue(ITy); 2793 break; 2794 case ICmpInst::ICMP_SGE: 2795 /// For signed comparison, the values for an i1 are 0 and -1 2796 /// respectively. This maps into a truth table of: 2797 /// LHS | RHS | LHS >=s RHS | LHS implies RHS 2798 /// 0 | 0 | 1 (0 >= 0) | 1 2799 /// 0 | 1 | 1 (0 >= -1) | 1 2800 /// 1 | 0 | 0 (-1 >= 0) | 0 2801 /// 1 | 1 | 1 (-1 >= -1) | 1 2802 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2803 return getTrue(ITy); 2804 break; 2805 case ICmpInst::ICMP_ULE: 2806 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2807 return getTrue(ITy); 2808 break; 2809 } 2810 2811 return nullptr; 2812 } 2813 2814 /// Try hard to fold icmp with zero RHS because this is a common case. 2815 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS, 2816 Value *RHS, const SimplifyQuery &Q) { 2817 if (!match(RHS, m_Zero())) 2818 return nullptr; 2819 2820 Type *ITy = GetCompareTy(LHS); // The return type. 2821 switch (Pred) { 2822 default: 2823 llvm_unreachable("Unknown ICmp predicate!"); 2824 case ICmpInst::ICMP_ULT: 2825 return getFalse(ITy); 2826 case ICmpInst::ICMP_UGE: 2827 return getTrue(ITy); 2828 case ICmpInst::ICMP_EQ: 2829 case ICmpInst::ICMP_ULE: 2830 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) 2831 return getFalse(ITy); 2832 break; 2833 case ICmpInst::ICMP_NE: 2834 case ICmpInst::ICMP_UGT: 2835 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) 2836 return getTrue(ITy); 2837 break; 2838 case ICmpInst::ICMP_SLT: { 2839 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2840 if (LHSKnown.isNegative()) 2841 return getTrue(ITy); 2842 if (LHSKnown.isNonNegative()) 2843 return getFalse(ITy); 2844 break; 2845 } 2846 case ICmpInst::ICMP_SLE: { 2847 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2848 if (LHSKnown.isNegative()) 2849 return getTrue(ITy); 2850 if (LHSKnown.isNonNegative() && 2851 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2852 return getFalse(ITy); 2853 break; 2854 } 2855 case ICmpInst::ICMP_SGE: { 2856 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2857 if (LHSKnown.isNegative()) 2858 return getFalse(ITy); 2859 if (LHSKnown.isNonNegative()) 2860 return getTrue(ITy); 2861 break; 2862 } 2863 case ICmpInst::ICMP_SGT: { 2864 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2865 if (LHSKnown.isNegative()) 2866 return getFalse(ITy); 2867 if (LHSKnown.isNonNegative() && 2868 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2869 return getTrue(ITy); 2870 break; 2871 } 2872 } 2873 2874 return nullptr; 2875 } 2876 2877 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS, 2878 Value *RHS, const InstrInfoQuery &IIQ) { 2879 Type *ITy = GetCompareTy(RHS); // The return type. 2880 2881 Value *X; 2882 // Sign-bit checks can be optimized to true/false after unsigned 2883 // floating-point casts: 2884 // icmp slt (bitcast (uitofp X)), 0 --> false 2885 // icmp sgt (bitcast (uitofp X)), -1 --> true 2886 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) { 2887 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero())) 2888 return ConstantInt::getFalse(ITy); 2889 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes())) 2890 return ConstantInt::getTrue(ITy); 2891 } 2892 2893 const APInt *C; 2894 if (!match(RHS, m_APIntAllowUndef(C))) 2895 return nullptr; 2896 2897 // Rule out tautological comparisons (eg., ult 0 or uge 0). 2898 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C); 2899 if (RHS_CR.isEmptySet()) 2900 return ConstantInt::getFalse(ITy); 2901 if (RHS_CR.isFullSet()) 2902 return ConstantInt::getTrue(ITy); 2903 2904 ConstantRange LHS_CR = 2905 computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo); 2906 if (!LHS_CR.isFullSet()) { 2907 if (RHS_CR.contains(LHS_CR)) 2908 return ConstantInt::getTrue(ITy); 2909 if (RHS_CR.inverse().contains(LHS_CR)) 2910 return ConstantInt::getFalse(ITy); 2911 } 2912 2913 // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC) 2914 // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC) 2915 const APInt *MulC; 2916 if (ICmpInst::isEquality(Pred) && 2917 ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) && 2918 *MulC != 0 && C->urem(*MulC) != 0) || 2919 (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) && 2920 *MulC != 0 && C->srem(*MulC) != 0))) 2921 return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE); 2922 2923 return nullptr; 2924 } 2925 2926 static Value *simplifyICmpWithBinOpOnLHS( 2927 CmpInst::Predicate Pred, BinaryOperator *LBO, Value *RHS, 2928 const SimplifyQuery &Q, unsigned MaxRecurse) { 2929 Type *ITy = GetCompareTy(RHS); // The return type. 2930 2931 Value *Y = nullptr; 2932 // icmp pred (or X, Y), X 2933 if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) { 2934 if (Pred == ICmpInst::ICMP_ULT) 2935 return getFalse(ITy); 2936 if (Pred == ICmpInst::ICMP_UGE) 2937 return getTrue(ITy); 2938 2939 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) { 2940 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2941 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2942 if (RHSKnown.isNonNegative() && YKnown.isNegative()) 2943 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy); 2944 if (RHSKnown.isNegative() || YKnown.isNonNegative()) 2945 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy); 2946 } 2947 } 2948 2949 // icmp pred (and X, Y), X 2950 if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) { 2951 if (Pred == ICmpInst::ICMP_UGT) 2952 return getFalse(ITy); 2953 if (Pred == ICmpInst::ICMP_ULE) 2954 return getTrue(ITy); 2955 } 2956 2957 // icmp pred (urem X, Y), Y 2958 if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { 2959 switch (Pred) { 2960 default: 2961 break; 2962 case ICmpInst::ICMP_SGT: 2963 case ICmpInst::ICMP_SGE: { 2964 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2965 if (!Known.isNonNegative()) 2966 break; 2967 LLVM_FALLTHROUGH; 2968 } 2969 case ICmpInst::ICMP_EQ: 2970 case ICmpInst::ICMP_UGT: 2971 case ICmpInst::ICMP_UGE: 2972 return getFalse(ITy); 2973 case ICmpInst::ICMP_SLT: 2974 case ICmpInst::ICMP_SLE: { 2975 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2976 if (!Known.isNonNegative()) 2977 break; 2978 LLVM_FALLTHROUGH; 2979 } 2980 case ICmpInst::ICMP_NE: 2981 case ICmpInst::ICMP_ULT: 2982 case ICmpInst::ICMP_ULE: 2983 return getTrue(ITy); 2984 } 2985 } 2986 2987 // icmp pred (urem X, Y), X 2988 if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) { 2989 if (Pred == ICmpInst::ICMP_ULE) 2990 return getTrue(ITy); 2991 if (Pred == ICmpInst::ICMP_UGT) 2992 return getFalse(ITy); 2993 } 2994 2995 // x >>u y <=u x --> true. 2996 // x >>u y >u x --> false. 2997 // x udiv y <=u x --> true. 2998 // x udiv y >u x --> false. 2999 if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) || 3000 match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) { 3001 // icmp pred (X op Y), X 3002 if (Pred == ICmpInst::ICMP_UGT) 3003 return getFalse(ITy); 3004 if (Pred == ICmpInst::ICMP_ULE) 3005 return getTrue(ITy); 3006 } 3007 3008 // If x is nonzero: 3009 // x >>u C <u x --> true for C != 0. 3010 // x >>u C != x --> true for C != 0. 3011 // x >>u C >=u x --> false for C != 0. 3012 // x >>u C == x --> false for C != 0. 3013 // x udiv C <u x --> true for C != 1. 3014 // x udiv C != x --> true for C != 1. 3015 // x udiv C >=u x --> false for C != 1. 3016 // x udiv C == x --> false for C != 1. 3017 // TODO: allow non-constant shift amount/divisor 3018 const APInt *C; 3019 if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) || 3020 (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) { 3021 if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) { 3022 switch (Pred) { 3023 default: 3024 break; 3025 case ICmpInst::ICMP_EQ: 3026 case ICmpInst::ICMP_UGE: 3027 return getFalse(ITy); 3028 case ICmpInst::ICMP_NE: 3029 case ICmpInst::ICMP_ULT: 3030 return getTrue(ITy); 3031 case ICmpInst::ICMP_UGT: 3032 case ICmpInst::ICMP_ULE: 3033 // UGT/ULE are handled by the more general case just above 3034 llvm_unreachable("Unexpected UGT/ULE, should have been handled"); 3035 } 3036 } 3037 } 3038 3039 // (x*C1)/C2 <= x for C1 <= C2. 3040 // This holds even if the multiplication overflows: Assume that x != 0 and 3041 // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and 3042 // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x. 3043 // 3044 // Additionally, either the multiplication and division might be represented 3045 // as shifts: 3046 // (x*C1)>>C2 <= x for C1 < 2**C2. 3047 // (x<<C1)/C2 <= x for 2**C1 < C2. 3048 const APInt *C1, *C2; 3049 if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 3050 C1->ule(*C2)) || 3051 (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 3052 C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) || 3053 (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 3054 (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) { 3055 if (Pred == ICmpInst::ICMP_UGT) 3056 return getFalse(ITy); 3057 if (Pred == ICmpInst::ICMP_ULE) 3058 return getTrue(ITy); 3059 } 3060 3061 return nullptr; 3062 } 3063 3064 3065 // If only one of the icmp's operands has NSW flags, try to prove that: 3066 // 3067 // icmp slt (x + C1), (x +nsw C2) 3068 // 3069 // is equivalent to: 3070 // 3071 // icmp slt C1, C2 3072 // 3073 // which is true if x + C2 has the NSW flags set and: 3074 // *) C1 < C2 && C1 >= 0, or 3075 // *) C2 < C1 && C1 <= 0. 3076 // 3077 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS, 3078 Value *RHS) { 3079 // TODO: only support icmp slt for now. 3080 if (Pred != CmpInst::ICMP_SLT) 3081 return false; 3082 3083 // Canonicalize nsw add as RHS. 3084 if (!match(RHS, m_NSWAdd(m_Value(), m_Value()))) 3085 std::swap(LHS, RHS); 3086 if (!match(RHS, m_NSWAdd(m_Value(), m_Value()))) 3087 return false; 3088 3089 Value *X; 3090 const APInt *C1, *C2; 3091 if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) || 3092 !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2)))) 3093 return false; 3094 3095 return (C1->slt(*C2) && C1->isNonNegative()) || 3096 (C2->slt(*C1) && C1->isNonPositive()); 3097 } 3098 3099 3100 /// TODO: A large part of this logic is duplicated in InstCombine's 3101 /// foldICmpBinOp(). We should be able to share that and avoid the code 3102 /// duplication. 3103 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, 3104 Value *RHS, const SimplifyQuery &Q, 3105 unsigned MaxRecurse) { 3106 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); 3107 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); 3108 if (MaxRecurse && (LBO || RBO)) { 3109 // Analyze the case when either LHS or RHS is an add instruction. 3110 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 3111 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). 3112 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; 3113 if (LBO && LBO->getOpcode() == Instruction::Add) { 3114 A = LBO->getOperand(0); 3115 B = LBO->getOperand(1); 3116 NoLHSWrapProblem = 3117 ICmpInst::isEquality(Pred) || 3118 (CmpInst::isUnsigned(Pred) && 3119 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) || 3120 (CmpInst::isSigned(Pred) && 3121 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO))); 3122 } 3123 if (RBO && RBO->getOpcode() == Instruction::Add) { 3124 C = RBO->getOperand(0); 3125 D = RBO->getOperand(1); 3126 NoRHSWrapProblem = 3127 ICmpInst::isEquality(Pred) || 3128 (CmpInst::isUnsigned(Pred) && 3129 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) || 3130 (CmpInst::isSigned(Pred) && 3131 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO))); 3132 } 3133 3134 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 3135 if ((A == RHS || B == RHS) && NoLHSWrapProblem) 3136 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, 3137 Constant::getNullValue(RHS->getType()), Q, 3138 MaxRecurse - 1)) 3139 return V; 3140 3141 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 3142 if ((C == LHS || D == LHS) && NoRHSWrapProblem) 3143 if (Value *V = 3144 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()), 3145 C == LHS ? D : C, Q, MaxRecurse - 1)) 3146 return V; 3147 3148 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. 3149 bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) || 3150 trySimplifyICmpWithAdds(Pred, LHS, RHS); 3151 if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) { 3152 // Determine Y and Z in the form icmp (X+Y), (X+Z). 3153 Value *Y, *Z; 3154 if (A == C) { 3155 // C + B == C + D -> B == D 3156 Y = B; 3157 Z = D; 3158 } else if (A == D) { 3159 // D + B == C + D -> B == C 3160 Y = B; 3161 Z = C; 3162 } else if (B == C) { 3163 // A + C == C + D -> A == D 3164 Y = A; 3165 Z = D; 3166 } else { 3167 assert(B == D); 3168 // A + D == C + D -> A == C 3169 Y = A; 3170 Z = C; 3171 } 3172 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1)) 3173 return V; 3174 } 3175 } 3176 3177 if (LBO) 3178 if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse)) 3179 return V; 3180 3181 if (RBO) 3182 if (Value *V = simplifyICmpWithBinOpOnLHS( 3183 ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse)) 3184 return V; 3185 3186 // 0 - (zext X) pred C 3187 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) { 3188 const APInt *C; 3189 if (match(RHS, m_APInt(C))) { 3190 if (C->isStrictlyPositive()) { 3191 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE) 3192 return ConstantInt::getTrue(GetCompareTy(RHS)); 3193 if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ) 3194 return ConstantInt::getFalse(GetCompareTy(RHS)); 3195 } 3196 if (C->isNonNegative()) { 3197 if (Pred == ICmpInst::ICMP_SLE) 3198 return ConstantInt::getTrue(GetCompareTy(RHS)); 3199 if (Pred == ICmpInst::ICMP_SGT) 3200 return ConstantInt::getFalse(GetCompareTy(RHS)); 3201 } 3202 } 3203 } 3204 3205 // If C2 is a power-of-2 and C is not: 3206 // (C2 << X) == C --> false 3207 // (C2 << X) != C --> true 3208 const APInt *C; 3209 if (match(LHS, m_Shl(m_Power2(), m_Value())) && 3210 match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) { 3211 // C2 << X can equal zero in some circumstances. 3212 // This simplification might be unsafe if C is zero. 3213 // 3214 // We know it is safe if: 3215 // - The shift is nsw. We can't shift out the one bit. 3216 // - The shift is nuw. We can't shift out the one bit. 3217 // - C2 is one. 3218 // - C isn't zero. 3219 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) || 3220 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) || 3221 match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) { 3222 if (Pred == ICmpInst::ICMP_EQ) 3223 return ConstantInt::getFalse(GetCompareTy(RHS)); 3224 if (Pred == ICmpInst::ICMP_NE) 3225 return ConstantInt::getTrue(GetCompareTy(RHS)); 3226 } 3227 } 3228 3229 // TODO: This is overly constrained. LHS can be any power-of-2. 3230 // (1 << X) >u 0x8000 --> false 3231 // (1 << X) <=u 0x8000 --> true 3232 if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) { 3233 if (Pred == ICmpInst::ICMP_UGT) 3234 return ConstantInt::getFalse(GetCompareTy(RHS)); 3235 if (Pred == ICmpInst::ICMP_ULE) 3236 return ConstantInt::getTrue(GetCompareTy(RHS)); 3237 } 3238 3239 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && 3240 LBO->getOperand(1) == RBO->getOperand(1)) { 3241 switch (LBO->getOpcode()) { 3242 default: 3243 break; 3244 case Instruction::UDiv: 3245 case Instruction::LShr: 3246 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) || 3247 !Q.IIQ.isExact(RBO)) 3248 break; 3249 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3250 RBO->getOperand(0), Q, MaxRecurse - 1)) 3251 return V; 3252 break; 3253 case Instruction::SDiv: 3254 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) || 3255 !Q.IIQ.isExact(RBO)) 3256 break; 3257 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3258 RBO->getOperand(0), Q, MaxRecurse - 1)) 3259 return V; 3260 break; 3261 case Instruction::AShr: 3262 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO)) 3263 break; 3264 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3265 RBO->getOperand(0), Q, MaxRecurse - 1)) 3266 return V; 3267 break; 3268 case Instruction::Shl: { 3269 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO); 3270 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO); 3271 if (!NUW && !NSW) 3272 break; 3273 if (!NSW && ICmpInst::isSigned(Pred)) 3274 break; 3275 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3276 RBO->getOperand(0), Q, MaxRecurse - 1)) 3277 return V; 3278 break; 3279 } 3280 } 3281 } 3282 return nullptr; 3283 } 3284 3285 /// Simplify integer comparisons where at least one operand of the compare 3286 /// matches an integer min/max idiom. 3287 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS, 3288 Value *RHS, const SimplifyQuery &Q, 3289 unsigned MaxRecurse) { 3290 Type *ITy = GetCompareTy(LHS); // The return type. 3291 Value *A, *B; 3292 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; 3293 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". 3294 3295 // Signed variants on "max(a,b)>=a -> true". 3296 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 3297 if (A != RHS) 3298 std::swap(A, B); // smax(A, B) pred A. 3299 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 3300 // We analyze this as smax(A, B) pred A. 3301 P = Pred; 3302 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && 3303 (A == LHS || B == LHS)) { 3304 if (A != LHS) 3305 std::swap(A, B); // A pred smax(A, B). 3306 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 3307 // We analyze this as smax(A, B) swapped-pred A. 3308 P = CmpInst::getSwappedPredicate(Pred); 3309 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 3310 (A == RHS || B == RHS)) { 3311 if (A != RHS) 3312 std::swap(A, B); // smin(A, B) pred A. 3313 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 3314 // We analyze this as smax(-A, -B) swapped-pred -A. 3315 // Note that we do not need to actually form -A or -B thanks to EqP. 3316 P = CmpInst::getSwappedPredicate(Pred); 3317 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && 3318 (A == LHS || B == LHS)) { 3319 if (A != LHS) 3320 std::swap(A, B); // A pred smin(A, B). 3321 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 3322 // We analyze this as smax(-A, -B) pred -A. 3323 // Note that we do not need to actually form -A or -B thanks to EqP. 3324 P = Pred; 3325 } 3326 if (P != CmpInst::BAD_ICMP_PREDICATE) { 3327 // Cases correspond to "max(A, B) p A". 3328 switch (P) { 3329 default: 3330 break; 3331 case CmpInst::ICMP_EQ: 3332 case CmpInst::ICMP_SLE: 3333 // Equivalent to "A EqP B". This may be the same as the condition tested 3334 // in the max/min; if so, we can just return that. 3335 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 3336 return V; 3337 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 3338 return V; 3339 // Otherwise, see if "A EqP B" simplifies. 3340 if (MaxRecurse) 3341 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 3342 return V; 3343 break; 3344 case CmpInst::ICMP_NE: 3345 case CmpInst::ICMP_SGT: { 3346 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 3347 // Equivalent to "A InvEqP B". This may be the same as the condition 3348 // tested in the max/min; if so, we can just return that. 3349 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 3350 return V; 3351 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 3352 return V; 3353 // Otherwise, see if "A InvEqP B" simplifies. 3354 if (MaxRecurse) 3355 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 3356 return V; 3357 break; 3358 } 3359 case CmpInst::ICMP_SGE: 3360 // Always true. 3361 return getTrue(ITy); 3362 case CmpInst::ICMP_SLT: 3363 // Always false. 3364 return getFalse(ITy); 3365 } 3366 } 3367 3368 // Unsigned variants on "max(a,b)>=a -> true". 3369 P = CmpInst::BAD_ICMP_PREDICATE; 3370 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 3371 if (A != RHS) 3372 std::swap(A, B); // umax(A, B) pred A. 3373 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 3374 // We analyze this as umax(A, B) pred A. 3375 P = Pred; 3376 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && 3377 (A == LHS || B == LHS)) { 3378 if (A != LHS) 3379 std::swap(A, B); // A pred umax(A, B). 3380 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 3381 // We analyze this as umax(A, B) swapped-pred A. 3382 P = CmpInst::getSwappedPredicate(Pred); 3383 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 3384 (A == RHS || B == RHS)) { 3385 if (A != RHS) 3386 std::swap(A, B); // umin(A, B) pred A. 3387 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 3388 // We analyze this as umax(-A, -B) swapped-pred -A. 3389 // Note that we do not need to actually form -A or -B thanks to EqP. 3390 P = CmpInst::getSwappedPredicate(Pred); 3391 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && 3392 (A == LHS || B == LHS)) { 3393 if (A != LHS) 3394 std::swap(A, B); // A pred umin(A, B). 3395 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 3396 // We analyze this as umax(-A, -B) pred -A. 3397 // Note that we do not need to actually form -A or -B thanks to EqP. 3398 P = Pred; 3399 } 3400 if (P != CmpInst::BAD_ICMP_PREDICATE) { 3401 // Cases correspond to "max(A, B) p A". 3402 switch (P) { 3403 default: 3404 break; 3405 case CmpInst::ICMP_EQ: 3406 case CmpInst::ICMP_ULE: 3407 // Equivalent to "A EqP B". This may be the same as the condition tested 3408 // in the max/min; if so, we can just return that. 3409 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 3410 return V; 3411 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 3412 return V; 3413 // Otherwise, see if "A EqP B" simplifies. 3414 if (MaxRecurse) 3415 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 3416 return V; 3417 break; 3418 case CmpInst::ICMP_NE: 3419 case CmpInst::ICMP_UGT: { 3420 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 3421 // Equivalent to "A InvEqP B". This may be the same as the condition 3422 // tested in the max/min; if so, we can just return that. 3423 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 3424 return V; 3425 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 3426 return V; 3427 // Otherwise, see if "A InvEqP B" simplifies. 3428 if (MaxRecurse) 3429 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 3430 return V; 3431 break; 3432 } 3433 case CmpInst::ICMP_UGE: 3434 return getTrue(ITy); 3435 case CmpInst::ICMP_ULT: 3436 return getFalse(ITy); 3437 } 3438 } 3439 3440 // Comparing 1 each of min/max with a common operand? 3441 // Canonicalize min operand to RHS. 3442 if (match(LHS, m_UMin(m_Value(), m_Value())) || 3443 match(LHS, m_SMin(m_Value(), m_Value()))) { 3444 std::swap(LHS, RHS); 3445 Pred = ICmpInst::getSwappedPredicate(Pred); 3446 } 3447 3448 Value *C, *D; 3449 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && 3450 match(RHS, m_SMin(m_Value(C), m_Value(D))) && 3451 (A == C || A == D || B == C || B == D)) { 3452 // smax(A, B) >=s smin(A, D) --> true 3453 if (Pred == CmpInst::ICMP_SGE) 3454 return getTrue(ITy); 3455 // smax(A, B) <s smin(A, D) --> false 3456 if (Pred == CmpInst::ICMP_SLT) 3457 return getFalse(ITy); 3458 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && 3459 match(RHS, m_UMin(m_Value(C), m_Value(D))) && 3460 (A == C || A == D || B == C || B == D)) { 3461 // umax(A, B) >=u umin(A, D) --> true 3462 if (Pred == CmpInst::ICMP_UGE) 3463 return getTrue(ITy); 3464 // umax(A, B) <u umin(A, D) --> false 3465 if (Pred == CmpInst::ICMP_ULT) 3466 return getFalse(ITy); 3467 } 3468 3469 return nullptr; 3470 } 3471 3472 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate, 3473 Value *LHS, Value *RHS, 3474 const SimplifyQuery &Q) { 3475 // Gracefully handle instructions that have not been inserted yet. 3476 if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent()) 3477 return nullptr; 3478 3479 for (Value *AssumeBaseOp : {LHS, RHS}) { 3480 for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) { 3481 if (!AssumeVH) 3482 continue; 3483 3484 CallInst *Assume = cast<CallInst>(AssumeVH); 3485 if (Optional<bool> Imp = 3486 isImpliedCondition(Assume->getArgOperand(0), Predicate, LHS, RHS, 3487 Q.DL)) 3488 if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT)) 3489 return ConstantInt::get(GetCompareTy(LHS), *Imp); 3490 } 3491 } 3492 3493 return nullptr; 3494 } 3495 3496 /// Given operands for an ICmpInst, see if we can fold the result. 3497 /// If not, this returns null. 3498 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3499 const SimplifyQuery &Q, unsigned MaxRecurse) { 3500 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3501 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!"); 3502 3503 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3504 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3505 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3506 3507 // If we have a constant, make sure it is on the RHS. 3508 std::swap(LHS, RHS); 3509 Pred = CmpInst::getSwappedPredicate(Pred); 3510 } 3511 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X"); 3512 3513 Type *ITy = GetCompareTy(LHS); // The return type. 3514 3515 // icmp poison, X -> poison 3516 if (isa<PoisonValue>(RHS)) 3517 return PoisonValue::get(ITy); 3518 3519 // For EQ and NE, we can always pick a value for the undef to make the 3520 // predicate pass or fail, so we can return undef. 3521 // Matches behavior in llvm::ConstantFoldCompareInstruction. 3522 if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred)) 3523 return UndefValue::get(ITy); 3524 3525 // icmp X, X -> true/false 3526 // icmp X, undef -> true/false because undef could be X. 3527 if (LHS == RHS || Q.isUndefValue(RHS)) 3528 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); 3529 3530 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q)) 3531 return V; 3532 3533 // TODO: Sink/common this with other potentially expensive calls that use 3534 // ValueTracking? See comment below for isKnownNonEqual(). 3535 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q)) 3536 return V; 3537 3538 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ)) 3539 return V; 3540 3541 // If both operands have range metadata, use the metadata 3542 // to simplify the comparison. 3543 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) { 3544 auto RHS_Instr = cast<Instruction>(RHS); 3545 auto LHS_Instr = cast<Instruction>(LHS); 3546 3547 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) && 3548 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) { 3549 auto RHS_CR = getConstantRangeFromMetadata( 3550 *RHS_Instr->getMetadata(LLVMContext::MD_range)); 3551 auto LHS_CR = getConstantRangeFromMetadata( 3552 *LHS_Instr->getMetadata(LLVMContext::MD_range)); 3553 3554 if (LHS_CR.icmp(Pred, RHS_CR)) 3555 return ConstantInt::getTrue(RHS->getContext()); 3556 3557 if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR)) 3558 return ConstantInt::getFalse(RHS->getContext()); 3559 } 3560 } 3561 3562 // Compare of cast, for example (zext X) != 0 -> X != 0 3563 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { 3564 Instruction *LI = cast<CastInst>(LHS); 3565 Value *SrcOp = LI->getOperand(0); 3566 Type *SrcTy = SrcOp->getType(); 3567 Type *DstTy = LI->getType(); 3568 3569 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input 3570 // if the integer type is the same size as the pointer type. 3571 if (MaxRecurse && isa<PtrToIntInst>(LI) && 3572 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) { 3573 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 3574 // Transfer the cast to the constant. 3575 if (Value *V = SimplifyICmpInst(Pred, SrcOp, 3576 ConstantExpr::getIntToPtr(RHSC, SrcTy), 3577 Q, MaxRecurse-1)) 3578 return V; 3579 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { 3580 if (RI->getOperand(0)->getType() == SrcTy) 3581 // Compare without the cast. 3582 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3583 Q, MaxRecurse-1)) 3584 return V; 3585 } 3586 } 3587 3588 if (isa<ZExtInst>(LHS)) { 3589 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the 3590 // same type. 3591 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 3592 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3593 // Compare X and Y. Note that signed predicates become unsigned. 3594 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3595 SrcOp, RI->getOperand(0), Q, 3596 MaxRecurse-1)) 3597 return V; 3598 } 3599 // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true. 3600 else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 3601 if (SrcOp == RI->getOperand(0)) { 3602 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE) 3603 return ConstantInt::getTrue(ITy); 3604 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT) 3605 return ConstantInt::getFalse(ITy); 3606 } 3607 } 3608 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended 3609 // too. If not, then try to deduce the result of the comparison. 3610 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3611 // Compute the constant that would happen if we truncated to SrcTy then 3612 // reextended to DstTy. 3613 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3614 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); 3615 3616 // If the re-extended constant didn't change then this is effectively 3617 // also a case of comparing two zero-extended values. 3618 if (RExt == CI && MaxRecurse) 3619 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3620 SrcOp, Trunc, Q, MaxRecurse-1)) 3621 return V; 3622 3623 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit 3624 // there. Use this to work out the result of the comparison. 3625 if (RExt != CI) { 3626 switch (Pred) { 3627 default: llvm_unreachable("Unknown ICmp predicate!"); 3628 // LHS <u RHS. 3629 case ICmpInst::ICMP_EQ: 3630 case ICmpInst::ICMP_UGT: 3631 case ICmpInst::ICMP_UGE: 3632 return ConstantInt::getFalse(CI->getContext()); 3633 3634 case ICmpInst::ICMP_NE: 3635 case ICmpInst::ICMP_ULT: 3636 case ICmpInst::ICMP_ULE: 3637 return ConstantInt::getTrue(CI->getContext()); 3638 3639 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS 3640 // is non-negative then LHS <s RHS. 3641 case ICmpInst::ICMP_SGT: 3642 case ICmpInst::ICMP_SGE: 3643 return CI->getValue().isNegative() ? 3644 ConstantInt::getTrue(CI->getContext()) : 3645 ConstantInt::getFalse(CI->getContext()); 3646 3647 case ICmpInst::ICMP_SLT: 3648 case ICmpInst::ICMP_SLE: 3649 return CI->getValue().isNegative() ? 3650 ConstantInt::getFalse(CI->getContext()) : 3651 ConstantInt::getTrue(CI->getContext()); 3652 } 3653 } 3654 } 3655 } 3656 3657 if (isa<SExtInst>(LHS)) { 3658 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the 3659 // same type. 3660 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 3661 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3662 // Compare X and Y. Note that the predicate does not change. 3663 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3664 Q, MaxRecurse-1)) 3665 return V; 3666 } 3667 // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true. 3668 else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 3669 if (SrcOp == RI->getOperand(0)) { 3670 if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE) 3671 return ConstantInt::getTrue(ITy); 3672 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT) 3673 return ConstantInt::getFalse(ITy); 3674 } 3675 } 3676 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended 3677 // too. If not, then try to deduce the result of the comparison. 3678 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3679 // Compute the constant that would happen if we truncated to SrcTy then 3680 // reextended to DstTy. 3681 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3682 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); 3683 3684 // If the re-extended constant didn't change then this is effectively 3685 // also a case of comparing two sign-extended values. 3686 if (RExt == CI && MaxRecurse) 3687 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) 3688 return V; 3689 3690 // Otherwise the upper bits of LHS are all equal, while RHS has varying 3691 // bits there. Use this to work out the result of the comparison. 3692 if (RExt != CI) { 3693 switch (Pred) { 3694 default: llvm_unreachable("Unknown ICmp predicate!"); 3695 case ICmpInst::ICMP_EQ: 3696 return ConstantInt::getFalse(CI->getContext()); 3697 case ICmpInst::ICMP_NE: 3698 return ConstantInt::getTrue(CI->getContext()); 3699 3700 // If RHS is non-negative then LHS <s RHS. If RHS is negative then 3701 // LHS >s RHS. 3702 case ICmpInst::ICMP_SGT: 3703 case ICmpInst::ICMP_SGE: 3704 return CI->getValue().isNegative() ? 3705 ConstantInt::getTrue(CI->getContext()) : 3706 ConstantInt::getFalse(CI->getContext()); 3707 case ICmpInst::ICMP_SLT: 3708 case ICmpInst::ICMP_SLE: 3709 return CI->getValue().isNegative() ? 3710 ConstantInt::getFalse(CI->getContext()) : 3711 ConstantInt::getTrue(CI->getContext()); 3712 3713 // If LHS is non-negative then LHS <u RHS. If LHS is negative then 3714 // LHS >u RHS. 3715 case ICmpInst::ICMP_UGT: 3716 case ICmpInst::ICMP_UGE: 3717 // Comparison is true iff the LHS <s 0. 3718 if (MaxRecurse) 3719 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, 3720 Constant::getNullValue(SrcTy), 3721 Q, MaxRecurse-1)) 3722 return V; 3723 break; 3724 case ICmpInst::ICMP_ULT: 3725 case ICmpInst::ICMP_ULE: 3726 // Comparison is true iff the LHS >=s 0. 3727 if (MaxRecurse) 3728 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, 3729 Constant::getNullValue(SrcTy), 3730 Q, MaxRecurse-1)) 3731 return V; 3732 break; 3733 } 3734 } 3735 } 3736 } 3737 } 3738 3739 // icmp eq|ne X, Y -> false|true if X != Y 3740 // This is potentially expensive, and we have already computedKnownBits for 3741 // compares with 0 above here, so only try this for a non-zero compare. 3742 if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) && 3743 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) { 3744 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy); 3745 } 3746 3747 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse)) 3748 return V; 3749 3750 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse)) 3751 return V; 3752 3753 if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q)) 3754 return V; 3755 3756 // Simplify comparisons of related pointers using a powerful, recursive 3757 // GEP-walk when we have target data available.. 3758 if (LHS->getType()->isPointerTy()) 3759 if (auto *C = computePointerICmp(Pred, LHS, RHS, Q)) 3760 return C; 3761 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS)) 3762 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS)) 3763 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) == 3764 Q.DL.getTypeSizeInBits(CLHS->getType()) && 3765 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) == 3766 Q.DL.getTypeSizeInBits(CRHS->getType())) 3767 if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(), 3768 CRHS->getPointerOperand(), Q)) 3769 return C; 3770 3771 // If the comparison is with the result of a select instruction, check whether 3772 // comparing with either branch of the select always yields the same value. 3773 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3774 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3775 return V; 3776 3777 // If the comparison is with the result of a phi instruction, check whether 3778 // doing the compare with each incoming phi value yields a common result. 3779 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3780 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 3781 return V; 3782 3783 return nullptr; 3784 } 3785 3786 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3787 const SimplifyQuery &Q) { 3788 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 3789 } 3790 3791 /// Given operands for an FCmpInst, see if we can fold the result. 3792 /// If not, this returns null. 3793 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3794 FastMathFlags FMF, const SimplifyQuery &Q, 3795 unsigned MaxRecurse) { 3796 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3797 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!"); 3798 3799 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3800 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3801 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3802 3803 // If we have a constant, make sure it is on the RHS. 3804 std::swap(LHS, RHS); 3805 Pred = CmpInst::getSwappedPredicate(Pred); 3806 } 3807 3808 // Fold trivial predicates. 3809 Type *RetTy = GetCompareTy(LHS); 3810 if (Pred == FCmpInst::FCMP_FALSE) 3811 return getFalse(RetTy); 3812 if (Pred == FCmpInst::FCMP_TRUE) 3813 return getTrue(RetTy); 3814 3815 // Fold (un)ordered comparison if we can determine there are no NaNs. 3816 if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD) 3817 if (FMF.noNaNs() || 3818 (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI))) 3819 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD); 3820 3821 // NaN is unordered; NaN is not ordered. 3822 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && 3823 "Comparison must be either ordered or unordered"); 3824 if (match(RHS, m_NaN())) 3825 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3826 3827 // fcmp pred x, poison and fcmp pred poison, x 3828 // fold to poison 3829 if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS)) 3830 return PoisonValue::get(RetTy); 3831 3832 // fcmp pred x, undef and fcmp pred undef, x 3833 // fold to true if unordered, false if ordered 3834 if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) { 3835 // Choosing NaN for the undef will always make unordered comparison succeed 3836 // and ordered comparison fail. 3837 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3838 } 3839 3840 // fcmp x,x -> true/false. Not all compares are foldable. 3841 if (LHS == RHS) { 3842 if (CmpInst::isTrueWhenEqual(Pred)) 3843 return getTrue(RetTy); 3844 if (CmpInst::isFalseWhenEqual(Pred)) 3845 return getFalse(RetTy); 3846 } 3847 3848 // Handle fcmp with constant RHS. 3849 // TODO: Use match with a specific FP value, so these work with vectors with 3850 // undef lanes. 3851 const APFloat *C; 3852 if (match(RHS, m_APFloat(C))) { 3853 // Check whether the constant is an infinity. 3854 if (C->isInfinity()) { 3855 if (C->isNegative()) { 3856 switch (Pred) { 3857 case FCmpInst::FCMP_OLT: 3858 // No value is ordered and less than negative infinity. 3859 return getFalse(RetTy); 3860 case FCmpInst::FCMP_UGE: 3861 // All values are unordered with or at least negative infinity. 3862 return getTrue(RetTy); 3863 default: 3864 break; 3865 } 3866 } else { 3867 switch (Pred) { 3868 case FCmpInst::FCMP_OGT: 3869 // No value is ordered and greater than infinity. 3870 return getFalse(RetTy); 3871 case FCmpInst::FCMP_ULE: 3872 // All values are unordered with and at most infinity. 3873 return getTrue(RetTy); 3874 default: 3875 break; 3876 } 3877 } 3878 3879 // LHS == Inf 3880 if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI)) 3881 return getFalse(RetTy); 3882 // LHS != Inf 3883 if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI)) 3884 return getTrue(RetTy); 3885 // LHS == Inf || LHS == NaN 3886 if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) && 3887 isKnownNeverNaN(LHS, Q.TLI)) 3888 return getFalse(RetTy); 3889 // LHS != Inf && LHS != NaN 3890 if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) && 3891 isKnownNeverNaN(LHS, Q.TLI)) 3892 return getTrue(RetTy); 3893 } 3894 if (C->isNegative() && !C->isNegZero()) { 3895 assert(!C->isNaN() && "Unexpected NaN constant!"); 3896 // TODO: We can catch more cases by using a range check rather than 3897 // relying on CannotBeOrderedLessThanZero. 3898 switch (Pred) { 3899 case FCmpInst::FCMP_UGE: 3900 case FCmpInst::FCMP_UGT: 3901 case FCmpInst::FCMP_UNE: 3902 // (X >= 0) implies (X > C) when (C < 0) 3903 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3904 return getTrue(RetTy); 3905 break; 3906 case FCmpInst::FCMP_OEQ: 3907 case FCmpInst::FCMP_OLE: 3908 case FCmpInst::FCMP_OLT: 3909 // (X >= 0) implies !(X < C) when (C < 0) 3910 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3911 return getFalse(RetTy); 3912 break; 3913 default: 3914 break; 3915 } 3916 } 3917 3918 // Check comparison of [minnum/maxnum with constant] with other constant. 3919 const APFloat *C2; 3920 if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) && 3921 *C2 < *C) || 3922 (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) && 3923 *C2 > *C)) { 3924 bool IsMaxNum = 3925 cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum; 3926 // The ordered relationship and minnum/maxnum guarantee that we do not 3927 // have NaN constants, so ordered/unordered preds are handled the same. 3928 switch (Pred) { 3929 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ: 3930 // minnum(X, LesserC) == C --> false 3931 // maxnum(X, GreaterC) == C --> false 3932 return getFalse(RetTy); 3933 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE: 3934 // minnum(X, LesserC) != C --> true 3935 // maxnum(X, GreaterC) != C --> true 3936 return getTrue(RetTy); 3937 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE: 3938 case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT: 3939 // minnum(X, LesserC) >= C --> false 3940 // minnum(X, LesserC) > C --> false 3941 // maxnum(X, GreaterC) >= C --> true 3942 // maxnum(X, GreaterC) > C --> true 3943 return ConstantInt::get(RetTy, IsMaxNum); 3944 case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE: 3945 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT: 3946 // minnum(X, LesserC) <= C --> true 3947 // minnum(X, LesserC) < C --> true 3948 // maxnum(X, GreaterC) <= C --> false 3949 // maxnum(X, GreaterC) < C --> false 3950 return ConstantInt::get(RetTy, !IsMaxNum); 3951 default: 3952 // TRUE/FALSE/ORD/UNO should be handled before this. 3953 llvm_unreachable("Unexpected fcmp predicate"); 3954 } 3955 } 3956 } 3957 3958 if (match(RHS, m_AnyZeroFP())) { 3959 switch (Pred) { 3960 case FCmpInst::FCMP_OGE: 3961 case FCmpInst::FCMP_ULT: 3962 // Positive or zero X >= 0.0 --> true 3963 // Positive or zero X < 0.0 --> false 3964 if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) && 3965 CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3966 return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy); 3967 break; 3968 case FCmpInst::FCMP_UGE: 3969 case FCmpInst::FCMP_OLT: 3970 // Positive or zero or nan X >= 0.0 --> true 3971 // Positive or zero or nan X < 0.0 --> false 3972 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3973 return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy); 3974 break; 3975 default: 3976 break; 3977 } 3978 } 3979 3980 // If the comparison is with the result of a select instruction, check whether 3981 // comparing with either branch of the select always yields the same value. 3982 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3983 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3984 return V; 3985 3986 // If the comparison is with the result of a phi instruction, check whether 3987 // doing the compare with each incoming phi value yields a common result. 3988 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3989 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 3990 return V; 3991 3992 return nullptr; 3993 } 3994 3995 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3996 FastMathFlags FMF, const SimplifyQuery &Q) { 3997 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit); 3998 } 3999 4000 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 4001 const SimplifyQuery &Q, 4002 bool AllowRefinement, 4003 unsigned MaxRecurse) { 4004 assert(!Op->getType()->isVectorTy() && "This is not safe for vectors"); 4005 4006 // Trivial replacement. 4007 if (V == Op) 4008 return RepOp; 4009 4010 // We cannot replace a constant, and shouldn't even try. 4011 if (isa<Constant>(Op)) 4012 return nullptr; 4013 4014 auto *I = dyn_cast<Instruction>(V); 4015 if (!I || !is_contained(I->operands(), Op)) 4016 return nullptr; 4017 4018 // Replace Op with RepOp in instruction operands. 4019 SmallVector<Value *, 8> NewOps(I->getNumOperands()); 4020 transform(I->operands(), NewOps.begin(), 4021 [&](Value *V) { return V == Op ? RepOp : V; }); 4022 4023 if (!AllowRefinement) { 4024 // General InstSimplify functions may refine the result, e.g. by returning 4025 // a constant for a potentially poison value. To avoid this, implement only 4026 // a few non-refining but profitable transforms here. 4027 4028 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 4029 unsigned Opcode = BO->getOpcode(); 4030 // id op x -> x, x op id -> x 4031 if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType())) 4032 return NewOps[1]; 4033 if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(), 4034 /* RHS */ true)) 4035 return NewOps[0]; 4036 4037 // x & x -> x, x | x -> x 4038 if ((Opcode == Instruction::And || Opcode == Instruction::Or) && 4039 NewOps[0] == NewOps[1]) 4040 return NewOps[0]; 4041 } 4042 4043 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 4044 // getelementptr x, 0 -> x 4045 if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) && 4046 !GEP->isInBounds()) 4047 return NewOps[0]; 4048 } 4049 } else if (MaxRecurse) { 4050 // The simplification queries below may return the original value. Consider: 4051 // %div = udiv i32 %arg, %arg2 4052 // %mul = mul nsw i32 %div, %arg2 4053 // %cmp = icmp eq i32 %mul, %arg 4054 // %sel = select i1 %cmp, i32 %div, i32 undef 4055 // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which 4056 // simplifies back to %arg. This can only happen because %mul does not 4057 // dominate %div. To ensure a consistent return value contract, we make sure 4058 // that this case returns nullptr as well. 4059 auto PreventSelfSimplify = [V](Value *Simplified) { 4060 return Simplified != V ? Simplified : nullptr; 4061 }; 4062 4063 if (auto *B = dyn_cast<BinaryOperator>(I)) 4064 return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), NewOps[0], 4065 NewOps[1], Q, MaxRecurse - 1)); 4066 4067 if (CmpInst *C = dyn_cast<CmpInst>(I)) 4068 return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), NewOps[0], 4069 NewOps[1], Q, MaxRecurse - 1)); 4070 4071 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) 4072 return PreventSelfSimplify(SimplifyGEPInst(GEP->getSourceElementType(), 4073 NewOps, GEP->isInBounds(), Q, 4074 MaxRecurse - 1)); 4075 4076 if (isa<SelectInst>(I)) 4077 return PreventSelfSimplify( 4078 SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q, 4079 MaxRecurse - 1)); 4080 // TODO: We could hand off more cases to instsimplify here. 4081 } 4082 4083 // If all operands are constant after substituting Op for RepOp then we can 4084 // constant fold the instruction. 4085 SmallVector<Constant *, 8> ConstOps; 4086 for (Value *NewOp : NewOps) { 4087 if (Constant *ConstOp = dyn_cast<Constant>(NewOp)) 4088 ConstOps.push_back(ConstOp); 4089 else 4090 return nullptr; 4091 } 4092 4093 // Consider: 4094 // %cmp = icmp eq i32 %x, 2147483647 4095 // %add = add nsw i32 %x, 1 4096 // %sel = select i1 %cmp, i32 -2147483648, i32 %add 4097 // 4098 // We can't replace %sel with %add unless we strip away the flags (which 4099 // will be done in InstCombine). 4100 // TODO: This may be unsound, because it only catches some forms of 4101 // refinement. 4102 if (!AllowRefinement && canCreatePoison(cast<Operator>(I))) 4103 return nullptr; 4104 4105 if (CmpInst *C = dyn_cast<CmpInst>(I)) 4106 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0], 4107 ConstOps[1], Q.DL, Q.TLI); 4108 4109 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 4110 if (!LI->isVolatile()) 4111 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL); 4112 4113 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI); 4114 } 4115 4116 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 4117 const SimplifyQuery &Q, 4118 bool AllowRefinement) { 4119 return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement, 4120 RecursionLimit); 4121 } 4122 4123 /// Try to simplify a select instruction when its condition operand is an 4124 /// integer comparison where one operand of the compare is a constant. 4125 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X, 4126 const APInt *Y, bool TrueWhenUnset) { 4127 const APInt *C; 4128 4129 // (X & Y) == 0 ? X & ~Y : X --> X 4130 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y 4131 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) && 4132 *Y == ~*C) 4133 return TrueWhenUnset ? FalseVal : TrueVal; 4134 4135 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y 4136 // (X & Y) != 0 ? X : X & ~Y --> X 4137 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) && 4138 *Y == ~*C) 4139 return TrueWhenUnset ? FalseVal : TrueVal; 4140 4141 if (Y->isPowerOf2()) { 4142 // (X & Y) == 0 ? X | Y : X --> X | Y 4143 // (X & Y) != 0 ? X | Y : X --> X 4144 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) && 4145 *Y == *C) 4146 return TrueWhenUnset ? TrueVal : FalseVal; 4147 4148 // (X & Y) == 0 ? X : X | Y --> X 4149 // (X & Y) != 0 ? X : X | Y --> X | Y 4150 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) && 4151 *Y == *C) 4152 return TrueWhenUnset ? TrueVal : FalseVal; 4153 } 4154 4155 return nullptr; 4156 } 4157 4158 /// An alternative way to test if a bit is set or not uses sgt/slt instead of 4159 /// eq/ne. 4160 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS, 4161 ICmpInst::Predicate Pred, 4162 Value *TrueVal, Value *FalseVal) { 4163 Value *X; 4164 APInt Mask; 4165 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask)) 4166 return nullptr; 4167 4168 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask, 4169 Pred == ICmpInst::ICMP_EQ); 4170 } 4171 4172 /// Try to simplify a select instruction when its condition operand is an 4173 /// integer comparison. 4174 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal, 4175 Value *FalseVal, const SimplifyQuery &Q, 4176 unsigned MaxRecurse) { 4177 ICmpInst::Predicate Pred; 4178 Value *CmpLHS, *CmpRHS; 4179 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)))) 4180 return nullptr; 4181 4182 // Canonicalize ne to eq predicate. 4183 if (Pred == ICmpInst::ICMP_NE) { 4184 Pred = ICmpInst::ICMP_EQ; 4185 std::swap(TrueVal, FalseVal); 4186 } 4187 4188 // Check for integer min/max with a limit constant: 4189 // X > MIN_INT ? X : MIN_INT --> X 4190 // X < MAX_INT ? X : MAX_INT --> X 4191 if (TrueVal->getType()->isIntOrIntVectorTy()) { 4192 Value *X, *Y; 4193 SelectPatternFlavor SPF = 4194 matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal, 4195 X, Y).Flavor; 4196 if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) { 4197 APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF), 4198 X->getType()->getScalarSizeInBits()); 4199 if (match(Y, m_SpecificInt(LimitC))) 4200 return X; 4201 } 4202 } 4203 4204 if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) { 4205 Value *X; 4206 const APInt *Y; 4207 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y)))) 4208 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y, 4209 /*TrueWhenUnset=*/true)) 4210 return V; 4211 4212 // Test for a bogus zero-shift-guard-op around funnel-shift or rotate. 4213 Value *ShAmt; 4214 auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)), 4215 m_FShr(m_Value(), m_Value(X), m_Value(ShAmt))); 4216 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X 4217 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X 4218 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt) 4219 return X; 4220 4221 // Test for a zero-shift-guard-op around rotates. These are used to 4222 // avoid UB from oversized shifts in raw IR rotate patterns, but the 4223 // intrinsics do not have that problem. 4224 // We do not allow this transform for the general funnel shift case because 4225 // that would not preserve the poison safety of the original code. 4226 auto isRotate = 4227 m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)), 4228 m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt))); 4229 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt) 4230 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt) 4231 if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt && 4232 Pred == ICmpInst::ICMP_EQ) 4233 return FalseVal; 4234 4235 // X == 0 ? abs(X) : -abs(X) --> -abs(X) 4236 // X == 0 ? -abs(X) : abs(X) --> abs(X) 4237 if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) && 4238 match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))) 4239 return FalseVal; 4240 if (match(TrueVal, 4241 m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) && 4242 match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) 4243 return FalseVal; 4244 } 4245 4246 // Check for other compares that behave like bit test. 4247 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, 4248 TrueVal, FalseVal)) 4249 return V; 4250 4251 // If we have a scalar equality comparison, then we know the value in one of 4252 // the arms of the select. See if substituting this value into the arm and 4253 // simplifying the result yields the same value as the other arm. 4254 // Note that the equivalence/replacement opportunity does not hold for vectors 4255 // because each element of a vector select is chosen independently. 4256 if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) { 4257 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, 4258 /* AllowRefinement */ false, MaxRecurse) == 4259 TrueVal || 4260 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, 4261 /* AllowRefinement */ false, MaxRecurse) == 4262 TrueVal) 4263 return FalseVal; 4264 if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, 4265 /* AllowRefinement */ true, MaxRecurse) == 4266 FalseVal || 4267 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, 4268 /* AllowRefinement */ true, MaxRecurse) == 4269 FalseVal) 4270 return FalseVal; 4271 } 4272 4273 return nullptr; 4274 } 4275 4276 /// Try to simplify a select instruction when its condition operand is a 4277 /// floating-point comparison. 4278 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F, 4279 const SimplifyQuery &Q) { 4280 FCmpInst::Predicate Pred; 4281 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) && 4282 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T)))) 4283 return nullptr; 4284 4285 // This transform is safe if we do not have (do not care about) -0.0 or if 4286 // at least one operand is known to not be -0.0. Otherwise, the select can 4287 // change the sign of a zero operand. 4288 bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) && 4289 Q.CxtI->hasNoSignedZeros(); 4290 const APFloat *C; 4291 if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) || 4292 (match(F, m_APFloat(C)) && C->isNonZero())) { 4293 // (T == F) ? T : F --> F 4294 // (F == T) ? T : F --> F 4295 if (Pred == FCmpInst::FCMP_OEQ) 4296 return F; 4297 4298 // (T != F) ? T : F --> T 4299 // (F != T) ? T : F --> T 4300 if (Pred == FCmpInst::FCMP_UNE) 4301 return T; 4302 } 4303 4304 return nullptr; 4305 } 4306 4307 /// Given operands for a SelectInst, see if we can fold the result. 4308 /// If not, this returns null. 4309 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 4310 const SimplifyQuery &Q, unsigned MaxRecurse) { 4311 if (auto *CondC = dyn_cast<Constant>(Cond)) { 4312 if (auto *TrueC = dyn_cast<Constant>(TrueVal)) 4313 if (auto *FalseC = dyn_cast<Constant>(FalseVal)) 4314 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC); 4315 4316 // select poison, X, Y -> poison 4317 if (isa<PoisonValue>(CondC)) 4318 return PoisonValue::get(TrueVal->getType()); 4319 4320 // select undef, X, Y -> X or Y 4321 if (Q.isUndefValue(CondC)) 4322 return isa<Constant>(FalseVal) ? FalseVal : TrueVal; 4323 4324 // select true, X, Y --> X 4325 // select false, X, Y --> Y 4326 // For vectors, allow undef/poison elements in the condition to match the 4327 // defined elements, so we can eliminate the select. 4328 if (match(CondC, m_One())) 4329 return TrueVal; 4330 if (match(CondC, m_Zero())) 4331 return FalseVal; 4332 } 4333 4334 assert(Cond->getType()->isIntOrIntVectorTy(1) && 4335 "Select must have bool or bool vector condition"); 4336 assert(TrueVal->getType() == FalseVal->getType() && 4337 "Select must have same types for true/false ops"); 4338 4339 if (Cond->getType() == TrueVal->getType()) { 4340 // select i1 Cond, i1 true, i1 false --> i1 Cond 4341 if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt())) 4342 return Cond; 4343 4344 // (X || Y) && (X || !Y) --> X (commuted 8 ways) 4345 Value *X, *Y; 4346 if (match(FalseVal, m_ZeroInt())) { 4347 if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) && 4348 match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y)))) 4349 return X; 4350 if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) && 4351 match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y)))) 4352 return X; 4353 } 4354 } 4355 4356 // select ?, X, X -> X 4357 if (TrueVal == FalseVal) 4358 return TrueVal; 4359 4360 // If the true or false value is poison, we can fold to the other value. 4361 // If the true or false value is undef, we can fold to the other value as 4362 // long as the other value isn't poison. 4363 // select ?, poison, X -> X 4364 // select ?, undef, X -> X 4365 if (isa<PoisonValue>(TrueVal) || 4366 (Q.isUndefValue(TrueVal) && 4367 isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT))) 4368 return FalseVal; 4369 // select ?, X, poison -> X 4370 // select ?, X, undef -> X 4371 if (isa<PoisonValue>(FalseVal) || 4372 (Q.isUndefValue(FalseVal) && 4373 isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT))) 4374 return TrueVal; 4375 4376 // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC'' 4377 Constant *TrueC, *FalseC; 4378 if (isa<FixedVectorType>(TrueVal->getType()) && 4379 match(TrueVal, m_Constant(TrueC)) && 4380 match(FalseVal, m_Constant(FalseC))) { 4381 unsigned NumElts = 4382 cast<FixedVectorType>(TrueC->getType())->getNumElements(); 4383 SmallVector<Constant *, 16> NewC; 4384 for (unsigned i = 0; i != NumElts; ++i) { 4385 // Bail out on incomplete vector constants. 4386 Constant *TEltC = TrueC->getAggregateElement(i); 4387 Constant *FEltC = FalseC->getAggregateElement(i); 4388 if (!TEltC || !FEltC) 4389 break; 4390 4391 // If the elements match (undef or not), that value is the result. If only 4392 // one element is undef, choose the defined element as the safe result. 4393 if (TEltC == FEltC) 4394 NewC.push_back(TEltC); 4395 else if (isa<PoisonValue>(TEltC) || 4396 (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC))) 4397 NewC.push_back(FEltC); 4398 else if (isa<PoisonValue>(FEltC) || 4399 (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC))) 4400 NewC.push_back(TEltC); 4401 else 4402 break; 4403 } 4404 if (NewC.size() == NumElts) 4405 return ConstantVector::get(NewC); 4406 } 4407 4408 if (Value *V = 4409 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse)) 4410 return V; 4411 4412 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q)) 4413 return V; 4414 4415 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal)) 4416 return V; 4417 4418 Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL); 4419 if (Imp) 4420 return *Imp ? TrueVal : FalseVal; 4421 4422 return nullptr; 4423 } 4424 4425 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 4426 const SimplifyQuery &Q) { 4427 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit); 4428 } 4429 4430 /// Given operands for an GetElementPtrInst, see if we can fold the result. 4431 /// If not, this returns null. 4432 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, bool InBounds, 4433 const SimplifyQuery &Q, unsigned) { 4434 // The type of the GEP pointer operand. 4435 unsigned AS = 4436 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace(); 4437 4438 // getelementptr P -> P. 4439 if (Ops.size() == 1) 4440 return Ops[0]; 4441 4442 // Compute the (pointer) type returned by the GEP instruction. 4443 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1)); 4444 Type *GEPTy = PointerType::get(LastType, AS); 4445 for (Value *Op : Ops) { 4446 // If one of the operands is a vector, the result type is a vector of 4447 // pointers. All vector operands must have the same number of elements. 4448 if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) { 4449 GEPTy = VectorType::get(GEPTy, VT->getElementCount()); 4450 break; 4451 } 4452 } 4453 4454 // getelementptr poison, idx -> poison 4455 // getelementptr baseptr, poison -> poison 4456 if (any_of(Ops, [](const auto *V) { return isa<PoisonValue>(V); })) 4457 return PoisonValue::get(GEPTy); 4458 4459 if (Q.isUndefValue(Ops[0])) 4460 return UndefValue::get(GEPTy); 4461 4462 bool IsScalableVec = 4463 isa<ScalableVectorType>(SrcTy) || any_of(Ops, [](const Value *V) { 4464 return isa<ScalableVectorType>(V->getType()); 4465 }); 4466 4467 if (Ops.size() == 2) { 4468 // getelementptr P, 0 -> P. 4469 if (match(Ops[1], m_Zero()) && Ops[0]->getType() == GEPTy) 4470 return Ops[0]; 4471 4472 Type *Ty = SrcTy; 4473 if (!IsScalableVec && Ty->isSized()) { 4474 Value *P; 4475 uint64_t C; 4476 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty); 4477 // getelementptr P, N -> P if P points to a type of zero size. 4478 if (TyAllocSize == 0 && Ops[0]->getType() == GEPTy) 4479 return Ops[0]; 4480 4481 // The following transforms are only safe if the ptrtoint cast 4482 // doesn't truncate the pointers. 4483 if (Ops[1]->getType()->getScalarSizeInBits() == 4484 Q.DL.getPointerSizeInBits(AS)) { 4485 auto CanSimplify = [GEPTy, &P, V = Ops[0]]() -> bool { 4486 return P->getType() == GEPTy && 4487 getUnderlyingObject(P) == getUnderlyingObject(V); 4488 }; 4489 // getelementptr V, (sub P, V) -> P if P points to a type of size 1. 4490 if (TyAllocSize == 1 && 4491 match(Ops[1], m_Sub(m_PtrToInt(m_Value(P)), 4492 m_PtrToInt(m_Specific(Ops[0])))) && 4493 CanSimplify()) 4494 return P; 4495 4496 // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of 4497 // size 1 << C. 4498 if (match(Ops[1], m_AShr(m_Sub(m_PtrToInt(m_Value(P)), 4499 m_PtrToInt(m_Specific(Ops[0]))), 4500 m_ConstantInt(C))) && 4501 TyAllocSize == 1ULL << C && CanSimplify()) 4502 return P; 4503 4504 // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of 4505 // size C. 4506 if (match(Ops[1], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)), 4507 m_PtrToInt(m_Specific(Ops[0]))), 4508 m_SpecificInt(TyAllocSize))) && 4509 CanSimplify()) 4510 return P; 4511 } 4512 } 4513 } 4514 4515 if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 && 4516 all_of(Ops.slice(1).drop_back(1), 4517 [](Value *Idx) { return match(Idx, m_Zero()); })) { 4518 unsigned IdxWidth = 4519 Q.DL.getIndexSizeInBits(Ops[0]->getType()->getPointerAddressSpace()); 4520 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == IdxWidth) { 4521 APInt BasePtrOffset(IdxWidth, 0); 4522 Value *StrippedBasePtr = 4523 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL, 4524 BasePtrOffset); 4525 4526 // Avoid creating inttoptr of zero here: While LLVMs treatment of 4527 // inttoptr is generally conservative, this particular case is folded to 4528 // a null pointer, which will have incorrect provenance. 4529 4530 // gep (gep V, C), (sub 0, V) -> C 4531 if (match(Ops.back(), 4532 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) && 4533 !BasePtrOffset.isZero()) { 4534 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset); 4535 return ConstantExpr::getIntToPtr(CI, GEPTy); 4536 } 4537 // gep (gep V, C), (xor V, -1) -> C-1 4538 if (match(Ops.back(), 4539 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) && 4540 !BasePtrOffset.isOne()) { 4541 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1); 4542 return ConstantExpr::getIntToPtr(CI, GEPTy); 4543 } 4544 } 4545 } 4546 4547 // Check to see if this is constant foldable. 4548 if (!all_of(Ops, [](Value *V) { return isa<Constant>(V); })) 4549 return nullptr; 4550 4551 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]), 4552 Ops.slice(1), InBounds); 4553 return ConstantFoldConstant(CE, Q.DL); 4554 } 4555 4556 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops, bool InBounds, 4557 const SimplifyQuery &Q) { 4558 return ::SimplifyGEPInst(SrcTy, Ops, InBounds, Q, RecursionLimit); 4559 } 4560 4561 /// Given operands for an InsertValueInst, see if we can fold the result. 4562 /// If not, this returns null. 4563 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, 4564 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q, 4565 unsigned) { 4566 if (Constant *CAgg = dyn_cast<Constant>(Agg)) 4567 if (Constant *CVal = dyn_cast<Constant>(Val)) 4568 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); 4569 4570 // insertvalue x, undef, n -> x 4571 if (Q.isUndefValue(Val)) 4572 return Agg; 4573 4574 // insertvalue x, (extractvalue y, n), n 4575 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) 4576 if (EV->getAggregateOperand()->getType() == Agg->getType() && 4577 EV->getIndices() == Idxs) { 4578 // insertvalue undef, (extractvalue y, n), n -> y 4579 if (Q.isUndefValue(Agg)) 4580 return EV->getAggregateOperand(); 4581 4582 // insertvalue y, (extractvalue y, n), n -> y 4583 if (Agg == EV->getAggregateOperand()) 4584 return Agg; 4585 } 4586 4587 return nullptr; 4588 } 4589 4590 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, 4591 ArrayRef<unsigned> Idxs, 4592 const SimplifyQuery &Q) { 4593 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit); 4594 } 4595 4596 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx, 4597 const SimplifyQuery &Q) { 4598 // Try to constant fold. 4599 auto *VecC = dyn_cast<Constant>(Vec); 4600 auto *ValC = dyn_cast<Constant>(Val); 4601 auto *IdxC = dyn_cast<Constant>(Idx); 4602 if (VecC && ValC && IdxC) 4603 return ConstantExpr::getInsertElement(VecC, ValC, IdxC); 4604 4605 // For fixed-length vector, fold into poison if index is out of bounds. 4606 if (auto *CI = dyn_cast<ConstantInt>(Idx)) { 4607 if (isa<FixedVectorType>(Vec->getType()) && 4608 CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements())) 4609 return PoisonValue::get(Vec->getType()); 4610 } 4611 4612 // If index is undef, it might be out of bounds (see above case) 4613 if (Q.isUndefValue(Idx)) 4614 return PoisonValue::get(Vec->getType()); 4615 4616 // If the scalar is poison, or it is undef and there is no risk of 4617 // propagating poison from the vector value, simplify to the vector value. 4618 if (isa<PoisonValue>(Val) || 4619 (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec))) 4620 return Vec; 4621 4622 // If we are extracting a value from a vector, then inserting it into the same 4623 // place, that's the input vector: 4624 // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec 4625 if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx)))) 4626 return Vec; 4627 4628 return nullptr; 4629 } 4630 4631 /// Given operands for an ExtractValueInst, see if we can fold the result. 4632 /// If not, this returns null. 4633 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 4634 const SimplifyQuery &, unsigned) { 4635 if (auto *CAgg = dyn_cast<Constant>(Agg)) 4636 return ConstantFoldExtractValueInstruction(CAgg, Idxs); 4637 4638 // extractvalue x, (insertvalue y, elt, n), n -> elt 4639 unsigned NumIdxs = Idxs.size(); 4640 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr; 4641 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) { 4642 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices(); 4643 unsigned NumInsertValueIdxs = InsertValueIdxs.size(); 4644 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs); 4645 if (InsertValueIdxs.slice(0, NumCommonIdxs) == 4646 Idxs.slice(0, NumCommonIdxs)) { 4647 if (NumIdxs == NumInsertValueIdxs) 4648 return IVI->getInsertedValueOperand(); 4649 break; 4650 } 4651 } 4652 4653 return nullptr; 4654 } 4655 4656 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 4657 const SimplifyQuery &Q) { 4658 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit); 4659 } 4660 4661 /// Given operands for an ExtractElementInst, see if we can fold the result. 4662 /// If not, this returns null. 4663 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, 4664 const SimplifyQuery &Q, unsigned) { 4665 auto *VecVTy = cast<VectorType>(Vec->getType()); 4666 if (auto *CVec = dyn_cast<Constant>(Vec)) { 4667 if (auto *CIdx = dyn_cast<Constant>(Idx)) 4668 return ConstantExpr::getExtractElement(CVec, CIdx); 4669 4670 if (Q.isUndefValue(Vec)) 4671 return UndefValue::get(VecVTy->getElementType()); 4672 } 4673 4674 // An undef extract index can be arbitrarily chosen to be an out-of-range 4675 // index value, which would result in the instruction being poison. 4676 if (Q.isUndefValue(Idx)) 4677 return PoisonValue::get(VecVTy->getElementType()); 4678 4679 // If extracting a specified index from the vector, see if we can recursively 4680 // find a previously computed scalar that was inserted into the vector. 4681 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) { 4682 // For fixed-length vector, fold into undef if index is out of bounds. 4683 unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue(); 4684 if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts)) 4685 return PoisonValue::get(VecVTy->getElementType()); 4686 // Handle case where an element is extracted from a splat. 4687 if (IdxC->getValue().ult(MinNumElts)) 4688 if (auto *Splat = getSplatValue(Vec)) 4689 return Splat; 4690 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue())) 4691 return Elt; 4692 } else { 4693 // The index is not relevant if our vector is a splat. 4694 if (Value *Splat = getSplatValue(Vec)) 4695 return Splat; 4696 } 4697 return nullptr; 4698 } 4699 4700 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx, 4701 const SimplifyQuery &Q) { 4702 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit); 4703 } 4704 4705 /// See if we can fold the given phi. If not, returns null. 4706 static Value *SimplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues, 4707 const SimplifyQuery &Q) { 4708 // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE 4709 // here, because the PHI we may succeed simplifying to was not 4710 // def-reachable from the original PHI! 4711 4712 // If all of the PHI's incoming values are the same then replace the PHI node 4713 // with the common value. 4714 Value *CommonValue = nullptr; 4715 bool HasUndefInput = false; 4716 for (Value *Incoming : IncomingValues) { 4717 // If the incoming value is the phi node itself, it can safely be skipped. 4718 if (Incoming == PN) continue; 4719 if (Q.isUndefValue(Incoming)) { 4720 // Remember that we saw an undef value, but otherwise ignore them. 4721 HasUndefInput = true; 4722 continue; 4723 } 4724 if (CommonValue && Incoming != CommonValue) 4725 return nullptr; // Not the same, bail out. 4726 CommonValue = Incoming; 4727 } 4728 4729 // If CommonValue is null then all of the incoming values were either undef or 4730 // equal to the phi node itself. 4731 if (!CommonValue) 4732 return UndefValue::get(PN->getType()); 4733 4734 // If we have a PHI node like phi(X, undef, X), where X is defined by some 4735 // instruction, we cannot return X as the result of the PHI node unless it 4736 // dominates the PHI block. 4737 if (HasUndefInput) 4738 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr; 4739 4740 return CommonValue; 4741 } 4742 4743 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op, 4744 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) { 4745 if (auto *C = dyn_cast<Constant>(Op)) 4746 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL); 4747 4748 if (auto *CI = dyn_cast<CastInst>(Op)) { 4749 auto *Src = CI->getOperand(0); 4750 Type *SrcTy = Src->getType(); 4751 Type *MidTy = CI->getType(); 4752 Type *DstTy = Ty; 4753 if (Src->getType() == Ty) { 4754 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode()); 4755 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc); 4756 Type *SrcIntPtrTy = 4757 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr; 4758 Type *MidIntPtrTy = 4759 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr; 4760 Type *DstIntPtrTy = 4761 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr; 4762 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy, 4763 SrcIntPtrTy, MidIntPtrTy, 4764 DstIntPtrTy) == Instruction::BitCast) 4765 return Src; 4766 } 4767 } 4768 4769 // bitcast x -> x 4770 if (CastOpc == Instruction::BitCast) 4771 if (Op->getType() == Ty) 4772 return Op; 4773 4774 return nullptr; 4775 } 4776 4777 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, 4778 const SimplifyQuery &Q) { 4779 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit); 4780 } 4781 4782 /// For the given destination element of a shuffle, peek through shuffles to 4783 /// match a root vector source operand that contains that element in the same 4784 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s). 4785 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, 4786 int MaskVal, Value *RootVec, 4787 unsigned MaxRecurse) { 4788 if (!MaxRecurse--) 4789 return nullptr; 4790 4791 // Bail out if any mask value is undefined. That kind of shuffle may be 4792 // simplified further based on demanded bits or other folds. 4793 if (MaskVal == -1) 4794 return nullptr; 4795 4796 // The mask value chooses which source operand we need to look at next. 4797 int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements(); 4798 int RootElt = MaskVal; 4799 Value *SourceOp = Op0; 4800 if (MaskVal >= InVecNumElts) { 4801 RootElt = MaskVal - InVecNumElts; 4802 SourceOp = Op1; 4803 } 4804 4805 // If the source operand is a shuffle itself, look through it to find the 4806 // matching root vector. 4807 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) { 4808 return foldIdentityShuffles( 4809 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1), 4810 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse); 4811 } 4812 4813 // TODO: Look through bitcasts? What if the bitcast changes the vector element 4814 // size? 4815 4816 // The source operand is not a shuffle. Initialize the root vector value for 4817 // this shuffle if that has not been done yet. 4818 if (!RootVec) 4819 RootVec = SourceOp; 4820 4821 // Give up as soon as a source operand does not match the existing root value. 4822 if (RootVec != SourceOp) 4823 return nullptr; 4824 4825 // The element must be coming from the same lane in the source vector 4826 // (although it may have crossed lanes in intermediate shuffles). 4827 if (RootElt != DestElt) 4828 return nullptr; 4829 4830 return RootVec; 4831 } 4832 4833 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, 4834 ArrayRef<int> Mask, Type *RetTy, 4835 const SimplifyQuery &Q, 4836 unsigned MaxRecurse) { 4837 if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; })) 4838 return UndefValue::get(RetTy); 4839 4840 auto *InVecTy = cast<VectorType>(Op0->getType()); 4841 unsigned MaskNumElts = Mask.size(); 4842 ElementCount InVecEltCount = InVecTy->getElementCount(); 4843 4844 bool Scalable = InVecEltCount.isScalable(); 4845 4846 SmallVector<int, 32> Indices; 4847 Indices.assign(Mask.begin(), Mask.end()); 4848 4849 // Canonicalization: If mask does not select elements from an input vector, 4850 // replace that input vector with poison. 4851 if (!Scalable) { 4852 bool MaskSelects0 = false, MaskSelects1 = false; 4853 unsigned InVecNumElts = InVecEltCount.getKnownMinValue(); 4854 for (unsigned i = 0; i != MaskNumElts; ++i) { 4855 if (Indices[i] == -1) 4856 continue; 4857 if ((unsigned)Indices[i] < InVecNumElts) 4858 MaskSelects0 = true; 4859 else 4860 MaskSelects1 = true; 4861 } 4862 if (!MaskSelects0) 4863 Op0 = PoisonValue::get(InVecTy); 4864 if (!MaskSelects1) 4865 Op1 = PoisonValue::get(InVecTy); 4866 } 4867 4868 auto *Op0Const = dyn_cast<Constant>(Op0); 4869 auto *Op1Const = dyn_cast<Constant>(Op1); 4870 4871 // If all operands are constant, constant fold the shuffle. This 4872 // transformation depends on the value of the mask which is not known at 4873 // compile time for scalable vectors 4874 if (Op0Const && Op1Const) 4875 return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask); 4876 4877 // Canonicalization: if only one input vector is constant, it shall be the 4878 // second one. This transformation depends on the value of the mask which 4879 // is not known at compile time for scalable vectors 4880 if (!Scalable && Op0Const && !Op1Const) { 4881 std::swap(Op0, Op1); 4882 ShuffleVectorInst::commuteShuffleMask(Indices, 4883 InVecEltCount.getKnownMinValue()); 4884 } 4885 4886 // A splat of an inserted scalar constant becomes a vector constant: 4887 // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...> 4888 // NOTE: We may have commuted above, so analyze the updated Indices, not the 4889 // original mask constant. 4890 // NOTE: This transformation depends on the value of the mask which is not 4891 // known at compile time for scalable vectors 4892 Constant *C; 4893 ConstantInt *IndexC; 4894 if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C), 4895 m_ConstantInt(IndexC)))) { 4896 // Match a splat shuffle mask of the insert index allowing undef elements. 4897 int InsertIndex = IndexC->getZExtValue(); 4898 if (all_of(Indices, [InsertIndex](int MaskElt) { 4899 return MaskElt == InsertIndex || MaskElt == -1; 4900 })) { 4901 assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat"); 4902 4903 // Shuffle mask undefs become undefined constant result elements. 4904 SmallVector<Constant *, 16> VecC(MaskNumElts, C); 4905 for (unsigned i = 0; i != MaskNumElts; ++i) 4906 if (Indices[i] == -1) 4907 VecC[i] = UndefValue::get(C->getType()); 4908 return ConstantVector::get(VecC); 4909 } 4910 } 4911 4912 // A shuffle of a splat is always the splat itself. Legal if the shuffle's 4913 // value type is same as the input vectors' type. 4914 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0)) 4915 if (Q.isUndefValue(Op1) && RetTy == InVecTy && 4916 is_splat(OpShuf->getShuffleMask())) 4917 return Op0; 4918 4919 // All remaining transformation depend on the value of the mask, which is 4920 // not known at compile time for scalable vectors. 4921 if (Scalable) 4922 return nullptr; 4923 4924 // Don't fold a shuffle with undef mask elements. This may get folded in a 4925 // better way using demanded bits or other analysis. 4926 // TODO: Should we allow this? 4927 if (is_contained(Indices, -1)) 4928 return nullptr; 4929 4930 // Check if every element of this shuffle can be mapped back to the 4931 // corresponding element of a single root vector. If so, we don't need this 4932 // shuffle. This handles simple identity shuffles as well as chains of 4933 // shuffles that may widen/narrow and/or move elements across lanes and back. 4934 Value *RootVec = nullptr; 4935 for (unsigned i = 0; i != MaskNumElts; ++i) { 4936 // Note that recursion is limited for each vector element, so if any element 4937 // exceeds the limit, this will fail to simplify. 4938 RootVec = 4939 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse); 4940 4941 // We can't replace a widening/narrowing shuffle with one of its operands. 4942 if (!RootVec || RootVec->getType() != RetTy) 4943 return nullptr; 4944 } 4945 return RootVec; 4946 } 4947 4948 /// Given operands for a ShuffleVectorInst, fold the result or return null. 4949 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, 4950 ArrayRef<int> Mask, Type *RetTy, 4951 const SimplifyQuery &Q) { 4952 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit); 4953 } 4954 4955 static Constant *foldConstant(Instruction::UnaryOps Opcode, 4956 Value *&Op, const SimplifyQuery &Q) { 4957 if (auto *C = dyn_cast<Constant>(Op)) 4958 return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL); 4959 return nullptr; 4960 } 4961 4962 /// Given the operand for an FNeg, see if we can fold the result. If not, this 4963 /// returns null. 4964 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF, 4965 const SimplifyQuery &Q, unsigned MaxRecurse) { 4966 if (Constant *C = foldConstant(Instruction::FNeg, Op, Q)) 4967 return C; 4968 4969 Value *X; 4970 // fneg (fneg X) ==> X 4971 if (match(Op, m_FNeg(m_Value(X)))) 4972 return X; 4973 4974 return nullptr; 4975 } 4976 4977 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF, 4978 const SimplifyQuery &Q) { 4979 return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit); 4980 } 4981 4982 static Constant *propagateNaN(Constant *In) { 4983 // If the input is a vector with undef elements, just return a default NaN. 4984 if (!In->isNaN()) 4985 return ConstantFP::getNaN(In->getType()); 4986 4987 // Propagate the existing NaN constant when possible. 4988 // TODO: Should we quiet a signaling NaN? 4989 return In; 4990 } 4991 4992 /// Perform folds that are common to any floating-point operation. This implies 4993 /// transforms based on poison/undef/NaN because the operation itself makes no 4994 /// difference to the result. 4995 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF, 4996 const SimplifyQuery &Q, 4997 fp::ExceptionBehavior ExBehavior, 4998 RoundingMode Rounding) { 4999 // Poison is independent of anything else. It always propagates from an 5000 // operand to a math result. 5001 if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); })) 5002 return PoisonValue::get(Ops[0]->getType()); 5003 5004 for (Value *V : Ops) { 5005 bool IsNan = match(V, m_NaN()); 5006 bool IsInf = match(V, m_Inf()); 5007 bool IsUndef = Q.isUndefValue(V); 5008 5009 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 5010 // (an undef operand can be chosen to be Nan/Inf), then the result of 5011 // this operation is poison. 5012 if (FMF.noNaNs() && (IsNan || IsUndef)) 5013 return PoisonValue::get(V->getType()); 5014 if (FMF.noInfs() && (IsInf || IsUndef)) 5015 return PoisonValue::get(V->getType()); 5016 5017 if (isDefaultFPEnvironment(ExBehavior, Rounding)) { 5018 if (IsUndef || IsNan) 5019 return propagateNaN(cast<Constant>(V)); 5020 } else if (ExBehavior != fp::ebStrict) { 5021 if (IsNan) 5022 return propagateNaN(cast<Constant>(V)); 5023 } 5024 } 5025 return nullptr; 5026 } 5027 5028 // TODO: Move this out to a header file: 5029 static inline bool canIgnoreSNaN(fp::ExceptionBehavior EB, FastMathFlags FMF) { 5030 return (EB == fp::ebIgnore || FMF.noNaNs()); 5031 } 5032 5033 /// Given operands for an FAdd, see if we can fold the result. If not, this 5034 /// returns null. 5035 static Value * 5036 SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5037 const SimplifyQuery &Q, unsigned MaxRecurse, 5038 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5039 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5040 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5041 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q)) 5042 return C; 5043 5044 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5045 return C; 5046 5047 // fadd X, -0 ==> X 5048 // With strict/constrained FP, we have these possible edge cases that do 5049 // not simplify to Op0: 5050 // fadd SNaN, -0.0 --> QNaN 5051 // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative) 5052 if (canIgnoreSNaN(ExBehavior, FMF) && 5053 (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) || 5054 FMF.noSignedZeros())) 5055 if (match(Op1, m_NegZeroFP())) 5056 return Op0; 5057 5058 // fadd X, 0 ==> X, when we know X is not -0 5059 if (canIgnoreSNaN(ExBehavior, FMF)) 5060 if (match(Op1, m_PosZeroFP()) && 5061 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 5062 return Op0; 5063 5064 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5065 return nullptr; 5066 5067 // With nnan: -X + X --> 0.0 (and commuted variant) 5068 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN. 5069 // Negative zeros are allowed because we always end up with positive zero: 5070 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 5071 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 5072 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0 5073 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0 5074 if (FMF.noNaNs()) { 5075 if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) || 5076 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))) 5077 return ConstantFP::getNullValue(Op0->getType()); 5078 5079 if (match(Op0, m_FNeg(m_Specific(Op1))) || 5080 match(Op1, m_FNeg(m_Specific(Op0)))) 5081 return ConstantFP::getNullValue(Op0->getType()); 5082 } 5083 5084 // (X - Y) + Y --> X 5085 // Y + (X - Y) --> X 5086 Value *X; 5087 if (FMF.noSignedZeros() && FMF.allowReassoc() && 5088 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) || 5089 match(Op1, m_FSub(m_Value(X), m_Specific(Op0))))) 5090 return X; 5091 5092 return nullptr; 5093 } 5094 5095 /// Given operands for an FSub, see if we can fold the result. If not, this 5096 /// returns null. 5097 static Value * 5098 SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5099 const SimplifyQuery &Q, unsigned MaxRecurse, 5100 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5101 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5102 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5103 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q)) 5104 return C; 5105 5106 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5107 return C; 5108 5109 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5110 return nullptr; 5111 5112 // fsub X, +0 ==> X 5113 if (match(Op1, m_PosZeroFP())) 5114 return Op0; 5115 5116 // fsub X, -0 ==> X, when we know X is not -0 5117 if (match(Op1, m_NegZeroFP()) && 5118 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 5119 return Op0; 5120 5121 // fsub -0.0, (fsub -0.0, X) ==> X 5122 // fsub -0.0, (fneg X) ==> X 5123 Value *X; 5124 if (match(Op0, m_NegZeroFP()) && 5125 match(Op1, m_FNeg(m_Value(X)))) 5126 return X; 5127 5128 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored. 5129 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored. 5130 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) && 5131 (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) || 5132 match(Op1, m_FNeg(m_Value(X))))) 5133 return X; 5134 5135 // fsub nnan x, x ==> 0.0 5136 if (FMF.noNaNs() && Op0 == Op1) 5137 return Constant::getNullValue(Op0->getType()); 5138 5139 // Y - (Y - X) --> X 5140 // (X + Y) - Y --> X 5141 if (FMF.noSignedZeros() && FMF.allowReassoc() && 5142 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) || 5143 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X))))) 5144 return X; 5145 5146 return nullptr; 5147 } 5148 5149 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF, 5150 const SimplifyQuery &Q, unsigned MaxRecurse, 5151 fp::ExceptionBehavior ExBehavior, 5152 RoundingMode Rounding) { 5153 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5154 return C; 5155 5156 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5157 return nullptr; 5158 5159 // fmul X, 1.0 ==> X 5160 if (match(Op1, m_FPOne())) 5161 return Op0; 5162 5163 // fmul 1.0, X ==> X 5164 if (match(Op0, m_FPOne())) 5165 return Op1; 5166 5167 // fmul nnan nsz X, 0 ==> 0 5168 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP())) 5169 return ConstantFP::getNullValue(Op0->getType()); 5170 5171 // fmul nnan nsz 0, X ==> 0 5172 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) 5173 return ConstantFP::getNullValue(Op1->getType()); 5174 5175 // sqrt(X) * sqrt(X) --> X, if we can: 5176 // 1. Remove the intermediate rounding (reassociate). 5177 // 2. Ignore non-zero negative numbers because sqrt would produce NAN. 5178 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0. 5179 Value *X; 5180 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && 5181 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros()) 5182 return X; 5183 5184 return nullptr; 5185 } 5186 5187 /// Given the operands for an FMul, see if we can fold the result 5188 static Value * 5189 SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5190 const SimplifyQuery &Q, unsigned MaxRecurse, 5191 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5192 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5193 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5194 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q)) 5195 return C; 5196 5197 // Now apply simplifications that do not require rounding. 5198 return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding); 5199 } 5200 5201 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5202 const SimplifyQuery &Q, 5203 fp::ExceptionBehavior ExBehavior, 5204 RoundingMode Rounding) { 5205 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5206 Rounding); 5207 } 5208 5209 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5210 const SimplifyQuery &Q, 5211 fp::ExceptionBehavior ExBehavior, 5212 RoundingMode Rounding) { 5213 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5214 Rounding); 5215 } 5216 5217 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5218 const SimplifyQuery &Q, 5219 fp::ExceptionBehavior ExBehavior, 5220 RoundingMode Rounding) { 5221 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5222 Rounding); 5223 } 5224 5225 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF, 5226 const SimplifyQuery &Q, 5227 fp::ExceptionBehavior ExBehavior, 5228 RoundingMode Rounding) { 5229 return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5230 Rounding); 5231 } 5232 5233 static Value * 5234 SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5235 const SimplifyQuery &Q, unsigned, 5236 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5237 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5238 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5239 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q)) 5240 return C; 5241 5242 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5243 return C; 5244 5245 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5246 return nullptr; 5247 5248 // X / 1.0 -> X 5249 if (match(Op1, m_FPOne())) 5250 return Op0; 5251 5252 // 0 / X -> 0 5253 // Requires that NaNs are off (X could be zero) and signed zeroes are 5254 // ignored (X could be positive or negative, so the output sign is unknown). 5255 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) 5256 return ConstantFP::getNullValue(Op0->getType()); 5257 5258 if (FMF.noNaNs()) { 5259 // X / X -> 1.0 is legal when NaNs are ignored. 5260 // We can ignore infinities because INF/INF is NaN. 5261 if (Op0 == Op1) 5262 return ConstantFP::get(Op0->getType(), 1.0); 5263 5264 // (X * Y) / Y --> X if we can reassociate to the above form. 5265 Value *X; 5266 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1)))) 5267 return X; 5268 5269 // -X / X -> -1.0 and 5270 // X / -X -> -1.0 are legal when NaNs are ignored. 5271 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored. 5272 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) || 5273 match(Op1, m_FNegNSZ(m_Specific(Op0)))) 5274 return ConstantFP::get(Op0->getType(), -1.0); 5275 } 5276 5277 return nullptr; 5278 } 5279 5280 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5281 const SimplifyQuery &Q, 5282 fp::ExceptionBehavior ExBehavior, 5283 RoundingMode Rounding) { 5284 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5285 Rounding); 5286 } 5287 5288 static Value * 5289 SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5290 const SimplifyQuery &Q, unsigned, 5291 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5292 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5293 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5294 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q)) 5295 return C; 5296 5297 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5298 return C; 5299 5300 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5301 return nullptr; 5302 5303 // Unlike fdiv, the result of frem always matches the sign of the dividend. 5304 // The constant match may include undef elements in a vector, so return a full 5305 // zero constant as the result. 5306 if (FMF.noNaNs()) { 5307 // +0 % X -> 0 5308 if (match(Op0, m_PosZeroFP())) 5309 return ConstantFP::getNullValue(Op0->getType()); 5310 // -0 % X -> -0 5311 if (match(Op0, m_NegZeroFP())) 5312 return ConstantFP::getNegativeZero(Op0->getType()); 5313 } 5314 5315 return nullptr; 5316 } 5317 5318 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5319 const SimplifyQuery &Q, 5320 fp::ExceptionBehavior ExBehavior, 5321 RoundingMode Rounding) { 5322 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5323 Rounding); 5324 } 5325 5326 //=== Helper functions for higher up the class hierarchy. 5327 5328 /// Given the operand for a UnaryOperator, see if we can fold the result. 5329 /// If not, this returns null. 5330 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q, 5331 unsigned MaxRecurse) { 5332 switch (Opcode) { 5333 case Instruction::FNeg: 5334 return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse); 5335 default: 5336 llvm_unreachable("Unexpected opcode"); 5337 } 5338 } 5339 5340 /// Given the operand for a UnaryOperator, see if we can fold the result. 5341 /// If not, this returns null. 5342 /// Try to use FastMathFlags when folding the result. 5343 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op, 5344 const FastMathFlags &FMF, 5345 const SimplifyQuery &Q, unsigned MaxRecurse) { 5346 switch (Opcode) { 5347 case Instruction::FNeg: 5348 return simplifyFNegInst(Op, FMF, Q, MaxRecurse); 5349 default: 5350 return simplifyUnOp(Opcode, Op, Q, MaxRecurse); 5351 } 5352 } 5353 5354 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) { 5355 return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit); 5356 } 5357 5358 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF, 5359 const SimplifyQuery &Q) { 5360 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit); 5361 } 5362 5363 /// Given operands for a BinaryOperator, see if we can fold the result. 5364 /// If not, this returns null. 5365 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5366 const SimplifyQuery &Q, unsigned MaxRecurse) { 5367 switch (Opcode) { 5368 case Instruction::Add: 5369 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse); 5370 case Instruction::Sub: 5371 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse); 5372 case Instruction::Mul: 5373 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse); 5374 case Instruction::SDiv: 5375 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); 5376 case Instruction::UDiv: 5377 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); 5378 case Instruction::SRem: 5379 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); 5380 case Instruction::URem: 5381 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); 5382 case Instruction::Shl: 5383 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse); 5384 case Instruction::LShr: 5385 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse); 5386 case Instruction::AShr: 5387 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse); 5388 case Instruction::And: 5389 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); 5390 case Instruction::Or: 5391 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse); 5392 case Instruction::Xor: 5393 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); 5394 case Instruction::FAdd: 5395 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5396 case Instruction::FSub: 5397 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5398 case Instruction::FMul: 5399 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5400 case Instruction::FDiv: 5401 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5402 case Instruction::FRem: 5403 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5404 default: 5405 llvm_unreachable("Unexpected opcode"); 5406 } 5407 } 5408 5409 /// Given operands for a BinaryOperator, see if we can fold the result. 5410 /// If not, this returns null. 5411 /// Try to use FastMathFlags when folding the result. 5412 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5413 const FastMathFlags &FMF, const SimplifyQuery &Q, 5414 unsigned MaxRecurse) { 5415 switch (Opcode) { 5416 case Instruction::FAdd: 5417 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse); 5418 case Instruction::FSub: 5419 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse); 5420 case Instruction::FMul: 5421 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse); 5422 case Instruction::FDiv: 5423 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse); 5424 default: 5425 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse); 5426 } 5427 } 5428 5429 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5430 const SimplifyQuery &Q) { 5431 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit); 5432 } 5433 5434 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5435 FastMathFlags FMF, const SimplifyQuery &Q) { 5436 return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit); 5437 } 5438 5439 /// Given operands for a CmpInst, see if we can fold the result. 5440 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 5441 const SimplifyQuery &Q, unsigned MaxRecurse) { 5442 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) 5443 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 5444 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5445 } 5446 5447 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 5448 const SimplifyQuery &Q) { 5449 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 5450 } 5451 5452 static bool IsIdempotent(Intrinsic::ID ID) { 5453 switch (ID) { 5454 default: return false; 5455 5456 // Unary idempotent: f(f(x)) = f(x) 5457 case Intrinsic::fabs: 5458 case Intrinsic::floor: 5459 case Intrinsic::ceil: 5460 case Intrinsic::trunc: 5461 case Intrinsic::rint: 5462 case Intrinsic::nearbyint: 5463 case Intrinsic::round: 5464 case Intrinsic::roundeven: 5465 case Intrinsic::canonicalize: 5466 return true; 5467 } 5468 } 5469 5470 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset, 5471 const DataLayout &DL) { 5472 GlobalValue *PtrSym; 5473 APInt PtrOffset; 5474 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL)) 5475 return nullptr; 5476 5477 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext()); 5478 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext()); 5479 Type *Int32PtrTy = Int32Ty->getPointerTo(); 5480 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext()); 5481 5482 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset); 5483 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64) 5484 return nullptr; 5485 5486 uint64_t OffsetInt = OffsetConstInt->getSExtValue(); 5487 if (OffsetInt % 4 != 0) 5488 return nullptr; 5489 5490 Constant *C = ConstantExpr::getGetElementPtr( 5491 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy), 5492 ConstantInt::get(Int64Ty, OffsetInt / 4)); 5493 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL); 5494 if (!Loaded) 5495 return nullptr; 5496 5497 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded); 5498 if (!LoadedCE) 5499 return nullptr; 5500 5501 if (LoadedCE->getOpcode() == Instruction::Trunc) { 5502 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 5503 if (!LoadedCE) 5504 return nullptr; 5505 } 5506 5507 if (LoadedCE->getOpcode() != Instruction::Sub) 5508 return nullptr; 5509 5510 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 5511 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt) 5512 return nullptr; 5513 auto *LoadedLHSPtr = LoadedLHS->getOperand(0); 5514 5515 Constant *LoadedRHS = LoadedCE->getOperand(1); 5516 GlobalValue *LoadedRHSSym; 5517 APInt LoadedRHSOffset; 5518 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset, 5519 DL) || 5520 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset) 5521 return nullptr; 5522 5523 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy); 5524 } 5525 5526 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0, 5527 const SimplifyQuery &Q) { 5528 // Idempotent functions return the same result when called repeatedly. 5529 Intrinsic::ID IID = F->getIntrinsicID(); 5530 if (IsIdempotent(IID)) 5531 if (auto *II = dyn_cast<IntrinsicInst>(Op0)) 5532 if (II->getIntrinsicID() == IID) 5533 return II; 5534 5535 Value *X; 5536 switch (IID) { 5537 case Intrinsic::fabs: 5538 if (SignBitMustBeZero(Op0, Q.TLI)) return Op0; 5539 break; 5540 case Intrinsic::bswap: 5541 // bswap(bswap(x)) -> x 5542 if (match(Op0, m_BSwap(m_Value(X)))) return X; 5543 break; 5544 case Intrinsic::bitreverse: 5545 // bitreverse(bitreverse(x)) -> x 5546 if (match(Op0, m_BitReverse(m_Value(X)))) return X; 5547 break; 5548 case Intrinsic::ctpop: { 5549 // If everything but the lowest bit is zero, that bit is the pop-count. Ex: 5550 // ctpop(and X, 1) --> and X, 1 5551 unsigned BitWidth = Op0->getType()->getScalarSizeInBits(); 5552 if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1), 5553 Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 5554 return Op0; 5555 break; 5556 } 5557 case Intrinsic::exp: 5558 // exp(log(x)) -> x 5559 if (Q.CxtI->hasAllowReassoc() && 5560 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X; 5561 break; 5562 case Intrinsic::exp2: 5563 // exp2(log2(x)) -> x 5564 if (Q.CxtI->hasAllowReassoc() && 5565 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X; 5566 break; 5567 case Intrinsic::log: 5568 // log(exp(x)) -> x 5569 if (Q.CxtI->hasAllowReassoc() && 5570 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X; 5571 break; 5572 case Intrinsic::log2: 5573 // log2(exp2(x)) -> x 5574 if (Q.CxtI->hasAllowReassoc() && 5575 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) || 5576 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), 5577 m_Value(X))))) return X; 5578 break; 5579 case Intrinsic::log10: 5580 // log10(pow(10.0, x)) -> x 5581 if (Q.CxtI->hasAllowReassoc() && 5582 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), 5583 m_Value(X)))) return X; 5584 break; 5585 case Intrinsic::floor: 5586 case Intrinsic::trunc: 5587 case Intrinsic::ceil: 5588 case Intrinsic::round: 5589 case Intrinsic::roundeven: 5590 case Intrinsic::nearbyint: 5591 case Intrinsic::rint: { 5592 // floor (sitofp x) -> sitofp x 5593 // floor (uitofp x) -> uitofp x 5594 // 5595 // Converting from int always results in a finite integral number or 5596 // infinity. For either of those inputs, these rounding functions always 5597 // return the same value, so the rounding can be eliminated. 5598 if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value()))) 5599 return Op0; 5600 break; 5601 } 5602 case Intrinsic::experimental_vector_reverse: 5603 // experimental.vector.reverse(experimental.vector.reverse(x)) -> x 5604 if (match(Op0, 5605 m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X)))) 5606 return X; 5607 // experimental.vector.reverse(splat(X)) -> splat(X) 5608 if (isSplatValue(Op0)) 5609 return Op0; 5610 break; 5611 default: 5612 break; 5613 } 5614 5615 return nullptr; 5616 } 5617 5618 /// Given a min/max intrinsic, see if it can be removed based on having an 5619 /// operand that is another min/max intrinsic with shared operand(s). The caller 5620 /// is expected to swap the operand arguments to handle commutation. 5621 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) { 5622 Value *X, *Y; 5623 if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y)))) 5624 return nullptr; 5625 5626 auto *MM0 = dyn_cast<IntrinsicInst>(Op0); 5627 if (!MM0) 5628 return nullptr; 5629 Intrinsic::ID IID0 = MM0->getIntrinsicID(); 5630 5631 if (Op1 == X || Op1 == Y || 5632 match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) { 5633 // max (max X, Y), X --> max X, Y 5634 if (IID0 == IID) 5635 return MM0; 5636 // max (min X, Y), X --> X 5637 if (IID0 == getInverseMinMaxIntrinsic(IID)) 5638 return Op1; 5639 } 5640 return nullptr; 5641 } 5642 5643 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1, 5644 const SimplifyQuery &Q) { 5645 Intrinsic::ID IID = F->getIntrinsicID(); 5646 Type *ReturnType = F->getReturnType(); 5647 unsigned BitWidth = ReturnType->getScalarSizeInBits(); 5648 switch (IID) { 5649 case Intrinsic::abs: 5650 // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here. 5651 // It is always ok to pick the earlier abs. We'll just lose nsw if its only 5652 // on the outer abs. 5653 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value()))) 5654 return Op0; 5655 break; 5656 5657 case Intrinsic::cttz: { 5658 Value *X; 5659 if (match(Op0, m_Shl(m_One(), m_Value(X)))) 5660 return X; 5661 break; 5662 } 5663 case Intrinsic::ctlz: { 5664 Value *X; 5665 if (match(Op0, m_LShr(m_Negative(), m_Value(X)))) 5666 return X; 5667 if (match(Op0, m_AShr(m_Negative(), m_Value()))) 5668 return Constant::getNullValue(ReturnType); 5669 break; 5670 } 5671 case Intrinsic::smax: 5672 case Intrinsic::smin: 5673 case Intrinsic::umax: 5674 case Intrinsic::umin: { 5675 // If the arguments are the same, this is a no-op. 5676 if (Op0 == Op1) 5677 return Op0; 5678 5679 // Canonicalize constant operand as Op1. 5680 if (isa<Constant>(Op0)) 5681 std::swap(Op0, Op1); 5682 5683 // Assume undef is the limit value. 5684 if (Q.isUndefValue(Op1)) 5685 return ConstantInt::get( 5686 ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth)); 5687 5688 const APInt *C; 5689 if (match(Op1, m_APIntAllowUndef(C))) { 5690 // Clamp to limit value. For example: 5691 // umax(i8 %x, i8 255) --> 255 5692 if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth)) 5693 return ConstantInt::get(ReturnType, *C); 5694 5695 // If the constant op is the opposite of the limit value, the other must 5696 // be larger/smaller or equal. For example: 5697 // umin(i8 %x, i8 255) --> %x 5698 if (*C == MinMaxIntrinsic::getSaturationPoint( 5699 getInverseMinMaxIntrinsic(IID), BitWidth)) 5700 return Op0; 5701 5702 // Remove nested call if constant operands allow it. Example: 5703 // max (max X, 7), 5 -> max X, 7 5704 auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0); 5705 if (MinMax0 && MinMax0->getIntrinsicID() == IID) { 5706 // TODO: loosen undef/splat restrictions for vector constants. 5707 Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1); 5708 const APInt *InnerC; 5709 if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) && 5710 ICmpInst::compare(*InnerC, *C, 5711 ICmpInst::getNonStrictPredicate( 5712 MinMaxIntrinsic::getPredicate(IID)))) 5713 return Op0; 5714 } 5715 } 5716 5717 if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1)) 5718 return V; 5719 if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0)) 5720 return V; 5721 5722 ICmpInst::Predicate Pred = 5723 ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID)); 5724 if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit)) 5725 return Op0; 5726 if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit)) 5727 return Op1; 5728 5729 if (Optional<bool> Imp = 5730 isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL)) 5731 return *Imp ? Op0 : Op1; 5732 if (Optional<bool> Imp = 5733 isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL)) 5734 return *Imp ? Op1 : Op0; 5735 5736 break; 5737 } 5738 case Intrinsic::usub_with_overflow: 5739 case Intrinsic::ssub_with_overflow: 5740 // X - X -> { 0, false } 5741 // X - undef -> { 0, false } 5742 // undef - X -> { 0, false } 5743 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5744 return Constant::getNullValue(ReturnType); 5745 break; 5746 case Intrinsic::uadd_with_overflow: 5747 case Intrinsic::sadd_with_overflow: 5748 // X + undef -> { -1, false } 5749 // undef + x -> { -1, false } 5750 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) { 5751 return ConstantStruct::get( 5752 cast<StructType>(ReturnType), 5753 {Constant::getAllOnesValue(ReturnType->getStructElementType(0)), 5754 Constant::getNullValue(ReturnType->getStructElementType(1))}); 5755 } 5756 break; 5757 case Intrinsic::umul_with_overflow: 5758 case Intrinsic::smul_with_overflow: 5759 // 0 * X -> { 0, false } 5760 // X * 0 -> { 0, false } 5761 if (match(Op0, m_Zero()) || match(Op1, m_Zero())) 5762 return Constant::getNullValue(ReturnType); 5763 // undef * X -> { 0, false } 5764 // X * undef -> { 0, false } 5765 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5766 return Constant::getNullValue(ReturnType); 5767 break; 5768 case Intrinsic::uadd_sat: 5769 // sat(MAX + X) -> MAX 5770 // sat(X + MAX) -> MAX 5771 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes())) 5772 return Constant::getAllOnesValue(ReturnType); 5773 LLVM_FALLTHROUGH; 5774 case Intrinsic::sadd_sat: 5775 // sat(X + undef) -> -1 5776 // sat(undef + X) -> -1 5777 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1). 5778 // For signed: Assume undef is ~X, in which case X + ~X = -1. 5779 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5780 return Constant::getAllOnesValue(ReturnType); 5781 5782 // X + 0 -> X 5783 if (match(Op1, m_Zero())) 5784 return Op0; 5785 // 0 + X -> X 5786 if (match(Op0, m_Zero())) 5787 return Op1; 5788 break; 5789 case Intrinsic::usub_sat: 5790 // sat(0 - X) -> 0, sat(X - MAX) -> 0 5791 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes())) 5792 return Constant::getNullValue(ReturnType); 5793 LLVM_FALLTHROUGH; 5794 case Intrinsic::ssub_sat: 5795 // X - X -> 0, X - undef -> 0, undef - X -> 0 5796 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5797 return Constant::getNullValue(ReturnType); 5798 // X - 0 -> X 5799 if (match(Op1, m_Zero())) 5800 return Op0; 5801 break; 5802 case Intrinsic::load_relative: 5803 if (auto *C0 = dyn_cast<Constant>(Op0)) 5804 if (auto *C1 = dyn_cast<Constant>(Op1)) 5805 return SimplifyRelativeLoad(C0, C1, Q.DL); 5806 break; 5807 case Intrinsic::powi: 5808 if (auto *Power = dyn_cast<ConstantInt>(Op1)) { 5809 // powi(x, 0) -> 1.0 5810 if (Power->isZero()) 5811 return ConstantFP::get(Op0->getType(), 1.0); 5812 // powi(x, 1) -> x 5813 if (Power->isOne()) 5814 return Op0; 5815 } 5816 break; 5817 case Intrinsic::copysign: 5818 // copysign X, X --> X 5819 if (Op0 == Op1) 5820 return Op0; 5821 // copysign -X, X --> X 5822 // copysign X, -X --> -X 5823 if (match(Op0, m_FNeg(m_Specific(Op1))) || 5824 match(Op1, m_FNeg(m_Specific(Op0)))) 5825 return Op1; 5826 break; 5827 case Intrinsic::maxnum: 5828 case Intrinsic::minnum: 5829 case Intrinsic::maximum: 5830 case Intrinsic::minimum: { 5831 // If the arguments are the same, this is a no-op. 5832 if (Op0 == Op1) return Op0; 5833 5834 // Canonicalize constant operand as Op1. 5835 if (isa<Constant>(Op0)) 5836 std::swap(Op0, Op1); 5837 5838 // If an argument is undef, return the other argument. 5839 if (Q.isUndefValue(Op1)) 5840 return Op0; 5841 5842 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum; 5843 bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum; 5844 5845 // minnum(X, nan) -> X 5846 // maxnum(X, nan) -> X 5847 // minimum(X, nan) -> nan 5848 // maximum(X, nan) -> nan 5849 if (match(Op1, m_NaN())) 5850 return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0; 5851 5852 // In the following folds, inf can be replaced with the largest finite 5853 // float, if the ninf flag is set. 5854 const APFloat *C; 5855 if (match(Op1, m_APFloat(C)) && 5856 (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) { 5857 // minnum(X, -inf) -> -inf 5858 // maxnum(X, +inf) -> +inf 5859 // minimum(X, -inf) -> -inf if nnan 5860 // maximum(X, +inf) -> +inf if nnan 5861 if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs())) 5862 return ConstantFP::get(ReturnType, *C); 5863 5864 // minnum(X, +inf) -> X if nnan 5865 // maxnum(X, -inf) -> X if nnan 5866 // minimum(X, +inf) -> X 5867 // maximum(X, -inf) -> X 5868 if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs())) 5869 return Op0; 5870 } 5871 5872 // Min/max of the same operation with common operand: 5873 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants) 5874 if (auto *M0 = dyn_cast<IntrinsicInst>(Op0)) 5875 if (M0->getIntrinsicID() == IID && 5876 (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1)) 5877 return Op0; 5878 if (auto *M1 = dyn_cast<IntrinsicInst>(Op1)) 5879 if (M1->getIntrinsicID() == IID && 5880 (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0)) 5881 return Op1; 5882 5883 break; 5884 } 5885 case Intrinsic::experimental_vector_extract: { 5886 Type *ReturnType = F->getReturnType(); 5887 5888 // (extract_vector (insert_vector _, X, 0), 0) -> X 5889 unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue(); 5890 Value *X = nullptr; 5891 if (match(Op0, m_Intrinsic<Intrinsic::experimental_vector_insert>( 5892 m_Value(), m_Value(X), m_Zero())) && 5893 IdxN == 0 && X->getType() == ReturnType) 5894 return X; 5895 5896 break; 5897 } 5898 default: 5899 break; 5900 } 5901 5902 return nullptr; 5903 } 5904 5905 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) { 5906 5907 unsigned NumOperands = Call->arg_size(); 5908 Function *F = cast<Function>(Call->getCalledFunction()); 5909 Intrinsic::ID IID = F->getIntrinsicID(); 5910 5911 // Most of the intrinsics with no operands have some kind of side effect. 5912 // Don't simplify. 5913 if (!NumOperands) { 5914 switch (IID) { 5915 case Intrinsic::vscale: { 5916 // Call may not be inserted into the IR yet at point of calling simplify. 5917 if (!Call->getParent() || !Call->getParent()->getParent()) 5918 return nullptr; 5919 auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange); 5920 if (!Attr.isValid()) 5921 return nullptr; 5922 unsigned VScaleMin = Attr.getVScaleRangeMin(); 5923 Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax(); 5924 if (VScaleMax && VScaleMin == VScaleMax) 5925 return ConstantInt::get(F->getReturnType(), VScaleMin); 5926 return nullptr; 5927 } 5928 default: 5929 return nullptr; 5930 } 5931 } 5932 5933 if (NumOperands == 1) 5934 return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q); 5935 5936 if (NumOperands == 2) 5937 return simplifyBinaryIntrinsic(F, Call->getArgOperand(0), 5938 Call->getArgOperand(1), Q); 5939 5940 // Handle intrinsics with 3 or more arguments. 5941 switch (IID) { 5942 case Intrinsic::masked_load: 5943 case Intrinsic::masked_gather: { 5944 Value *MaskArg = Call->getArgOperand(2); 5945 Value *PassthruArg = Call->getArgOperand(3); 5946 // If the mask is all zeros or undef, the "passthru" argument is the result. 5947 if (maskIsAllZeroOrUndef(MaskArg)) 5948 return PassthruArg; 5949 return nullptr; 5950 } 5951 case Intrinsic::fshl: 5952 case Intrinsic::fshr: { 5953 Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1), 5954 *ShAmtArg = Call->getArgOperand(2); 5955 5956 // If both operands are undef, the result is undef. 5957 if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1)) 5958 return UndefValue::get(F->getReturnType()); 5959 5960 // If shift amount is undef, assume it is zero. 5961 if (Q.isUndefValue(ShAmtArg)) 5962 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1); 5963 5964 const APInt *ShAmtC; 5965 if (match(ShAmtArg, m_APInt(ShAmtC))) { 5966 // If there's effectively no shift, return the 1st arg or 2nd arg. 5967 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth()); 5968 if (ShAmtC->urem(BitWidth).isZero()) 5969 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1); 5970 } 5971 5972 // Rotating zero by anything is zero. 5973 if (match(Op0, m_Zero()) && match(Op1, m_Zero())) 5974 return ConstantInt::getNullValue(F->getReturnType()); 5975 5976 // Rotating -1 by anything is -1. 5977 if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes())) 5978 return ConstantInt::getAllOnesValue(F->getReturnType()); 5979 5980 return nullptr; 5981 } 5982 case Intrinsic::experimental_constrained_fma: { 5983 Value *Op0 = Call->getArgOperand(0); 5984 Value *Op1 = Call->getArgOperand(1); 5985 Value *Op2 = Call->getArgOperand(2); 5986 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 5987 if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, 5988 FPI->getExceptionBehavior().getValue(), 5989 FPI->getRoundingMode().getValue())) 5990 return V; 5991 return nullptr; 5992 } 5993 case Intrinsic::fma: 5994 case Intrinsic::fmuladd: { 5995 Value *Op0 = Call->getArgOperand(0); 5996 Value *Op1 = Call->getArgOperand(1); 5997 Value *Op2 = Call->getArgOperand(2); 5998 if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore, 5999 RoundingMode::NearestTiesToEven)) 6000 return V; 6001 return nullptr; 6002 } 6003 case Intrinsic::smul_fix: 6004 case Intrinsic::smul_fix_sat: { 6005 Value *Op0 = Call->getArgOperand(0); 6006 Value *Op1 = Call->getArgOperand(1); 6007 Value *Op2 = Call->getArgOperand(2); 6008 Type *ReturnType = F->getReturnType(); 6009 6010 // Canonicalize constant operand as Op1 (ConstantFolding handles the case 6011 // when both Op0 and Op1 are constant so we do not care about that special 6012 // case here). 6013 if (isa<Constant>(Op0)) 6014 std::swap(Op0, Op1); 6015 6016 // X * 0 -> 0 6017 if (match(Op1, m_Zero())) 6018 return Constant::getNullValue(ReturnType); 6019 6020 // X * undef -> 0 6021 if (Q.isUndefValue(Op1)) 6022 return Constant::getNullValue(ReturnType); 6023 6024 // X * (1 << Scale) -> X 6025 APInt ScaledOne = 6026 APInt::getOneBitSet(ReturnType->getScalarSizeInBits(), 6027 cast<ConstantInt>(Op2)->getZExtValue()); 6028 if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne))) 6029 return Op0; 6030 6031 return nullptr; 6032 } 6033 case Intrinsic::experimental_vector_insert: { 6034 Value *Vec = Call->getArgOperand(0); 6035 Value *SubVec = Call->getArgOperand(1); 6036 Value *Idx = Call->getArgOperand(2); 6037 Type *ReturnType = F->getReturnType(); 6038 6039 // (insert_vector Y, (extract_vector X, 0), 0) -> X 6040 // where: Y is X, or Y is undef 6041 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 6042 Value *X = nullptr; 6043 if (match(SubVec, m_Intrinsic<Intrinsic::experimental_vector_extract>( 6044 m_Value(X), m_Zero())) && 6045 (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 && 6046 X->getType() == ReturnType) 6047 return X; 6048 6049 return nullptr; 6050 } 6051 case Intrinsic::experimental_constrained_fadd: { 6052 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6053 return SimplifyFAddInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 6054 FPI->getFastMathFlags(), Q, 6055 FPI->getExceptionBehavior().getValue(), 6056 FPI->getRoundingMode().getValue()); 6057 break; 6058 } 6059 case Intrinsic::experimental_constrained_fsub: { 6060 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6061 return SimplifyFSubInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 6062 FPI->getFastMathFlags(), Q, 6063 FPI->getExceptionBehavior().getValue(), 6064 FPI->getRoundingMode().getValue()); 6065 break; 6066 } 6067 case Intrinsic::experimental_constrained_fmul: { 6068 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6069 return SimplifyFMulInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 6070 FPI->getFastMathFlags(), Q, 6071 FPI->getExceptionBehavior().getValue(), 6072 FPI->getRoundingMode().getValue()); 6073 break; 6074 } 6075 case Intrinsic::experimental_constrained_fdiv: { 6076 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6077 return SimplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 6078 FPI->getFastMathFlags(), Q, 6079 FPI->getExceptionBehavior().getValue(), 6080 FPI->getRoundingMode().getValue()); 6081 break; 6082 } 6083 case Intrinsic::experimental_constrained_frem: { 6084 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6085 return SimplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 6086 FPI->getFastMathFlags(), Q, 6087 FPI->getExceptionBehavior().getValue(), 6088 FPI->getRoundingMode().getValue()); 6089 break; 6090 } 6091 default: 6092 return nullptr; 6093 } 6094 } 6095 6096 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) { 6097 auto *F = dyn_cast<Function>(Call->getCalledOperand()); 6098 if (!F || !canConstantFoldCallTo(Call, F)) 6099 return nullptr; 6100 6101 SmallVector<Constant *, 4> ConstantArgs; 6102 unsigned NumArgs = Call->arg_size(); 6103 ConstantArgs.reserve(NumArgs); 6104 for (auto &Arg : Call->args()) { 6105 Constant *C = dyn_cast<Constant>(&Arg); 6106 if (!C) { 6107 if (isa<MetadataAsValue>(Arg.get())) 6108 continue; 6109 return nullptr; 6110 } 6111 ConstantArgs.push_back(C); 6112 } 6113 6114 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI); 6115 } 6116 6117 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) { 6118 // musttail calls can only be simplified if they are also DCEd. 6119 // As we can't guarantee this here, don't simplify them. 6120 if (Call->isMustTailCall()) 6121 return nullptr; 6122 6123 // call undef -> poison 6124 // call null -> poison 6125 Value *Callee = Call->getCalledOperand(); 6126 if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee)) 6127 return PoisonValue::get(Call->getType()); 6128 6129 if (Value *V = tryConstantFoldCall(Call, Q)) 6130 return V; 6131 6132 auto *F = dyn_cast<Function>(Callee); 6133 if (F && F->isIntrinsic()) 6134 if (Value *Ret = simplifyIntrinsic(Call, Q)) 6135 return Ret; 6136 6137 return nullptr; 6138 } 6139 6140 /// Given operands for a Freeze, see if we can fold the result. 6141 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) { 6142 // Use a utility function defined in ValueTracking. 6143 if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT)) 6144 return Op0; 6145 // We have room for improvement. 6146 return nullptr; 6147 } 6148 6149 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) { 6150 return ::SimplifyFreezeInst(Op0, Q); 6151 } 6152 6153 static Value *SimplifyLoadInst(LoadInst *LI, Value *PtrOp, 6154 const SimplifyQuery &Q) { 6155 if (LI->isVolatile()) 6156 return nullptr; 6157 6158 APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0); 6159 auto *PtrOpC = dyn_cast<Constant>(PtrOp); 6160 // Try to convert operand into a constant by stripping offsets while looking 6161 // through invariant.group intrinsics. Don't bother if the underlying object 6162 // is not constant, as calculating GEP offsets is expensive. 6163 if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) { 6164 PtrOp = PtrOp->stripAndAccumulateConstantOffsets( 6165 Q.DL, Offset, /* AllowNonInbounts */ true, 6166 /* AllowInvariantGroup */ true); 6167 // Index size may have changed due to address space casts. 6168 Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType())); 6169 PtrOpC = dyn_cast<Constant>(PtrOp); 6170 } 6171 6172 if (PtrOpC) 6173 return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL); 6174 return nullptr; 6175 } 6176 6177 /// See if we can compute a simplified version of this instruction. 6178 /// If not, this returns null. 6179 6180 static Value *simplifyInstructionWithOperands(Instruction *I, 6181 ArrayRef<Value *> NewOps, 6182 const SimplifyQuery &SQ, 6183 OptimizationRemarkEmitter *ORE) { 6184 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I); 6185 Value *Result = nullptr; 6186 6187 switch (I->getOpcode()) { 6188 default: 6189 if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) { 6190 SmallVector<Constant *, 8> NewConstOps(NewOps.size()); 6191 transform(NewOps, NewConstOps.begin(), 6192 [](Value *V) { return cast<Constant>(V); }); 6193 Result = ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI); 6194 } 6195 break; 6196 case Instruction::FNeg: 6197 Result = SimplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q); 6198 break; 6199 case Instruction::FAdd: 6200 Result = SimplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6201 break; 6202 case Instruction::Add: 6203 Result = SimplifyAddInst( 6204 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6205 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6206 break; 6207 case Instruction::FSub: 6208 Result = SimplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6209 break; 6210 case Instruction::Sub: 6211 Result = SimplifySubInst( 6212 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6213 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6214 break; 6215 case Instruction::FMul: 6216 Result = SimplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6217 break; 6218 case Instruction::Mul: 6219 Result = SimplifyMulInst(NewOps[0], NewOps[1], Q); 6220 break; 6221 case Instruction::SDiv: 6222 Result = SimplifySDivInst(NewOps[0], NewOps[1], Q); 6223 break; 6224 case Instruction::UDiv: 6225 Result = SimplifyUDivInst(NewOps[0], NewOps[1], Q); 6226 break; 6227 case Instruction::FDiv: 6228 Result = SimplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6229 break; 6230 case Instruction::SRem: 6231 Result = SimplifySRemInst(NewOps[0], NewOps[1], Q); 6232 break; 6233 case Instruction::URem: 6234 Result = SimplifyURemInst(NewOps[0], NewOps[1], Q); 6235 break; 6236 case Instruction::FRem: 6237 Result = SimplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6238 break; 6239 case Instruction::Shl: 6240 Result = SimplifyShlInst( 6241 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6242 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6243 break; 6244 case Instruction::LShr: 6245 Result = SimplifyLShrInst(NewOps[0], NewOps[1], 6246 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); 6247 break; 6248 case Instruction::AShr: 6249 Result = SimplifyAShrInst(NewOps[0], NewOps[1], 6250 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); 6251 break; 6252 case Instruction::And: 6253 Result = SimplifyAndInst(NewOps[0], NewOps[1], Q); 6254 break; 6255 case Instruction::Or: 6256 Result = SimplifyOrInst(NewOps[0], NewOps[1], Q); 6257 break; 6258 case Instruction::Xor: 6259 Result = SimplifyXorInst(NewOps[0], NewOps[1], Q); 6260 break; 6261 case Instruction::ICmp: 6262 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0], 6263 NewOps[1], Q); 6264 break; 6265 case Instruction::FCmp: 6266 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0], 6267 NewOps[1], I->getFastMathFlags(), Q); 6268 break; 6269 case Instruction::Select: 6270 Result = SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q); 6271 break; 6272 case Instruction::GetElementPtr: { 6273 auto *GEPI = cast<GetElementPtrInst>(I); 6274 Result = SimplifyGEPInst(GEPI->getSourceElementType(), NewOps, 6275 GEPI->isInBounds(), Q); 6276 break; 6277 } 6278 case Instruction::InsertValue: { 6279 InsertValueInst *IV = cast<InsertValueInst>(I); 6280 Result = SimplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q); 6281 break; 6282 } 6283 case Instruction::InsertElement: { 6284 Result = SimplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q); 6285 break; 6286 } 6287 case Instruction::ExtractValue: { 6288 auto *EVI = cast<ExtractValueInst>(I); 6289 Result = SimplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q); 6290 break; 6291 } 6292 case Instruction::ExtractElement: { 6293 Result = SimplifyExtractElementInst(NewOps[0], NewOps[1], Q); 6294 break; 6295 } 6296 case Instruction::ShuffleVector: { 6297 auto *SVI = cast<ShuffleVectorInst>(I); 6298 Result = SimplifyShuffleVectorInst( 6299 NewOps[0], NewOps[1], SVI->getShuffleMask(), SVI->getType(), Q); 6300 break; 6301 } 6302 case Instruction::PHI: 6303 Result = SimplifyPHINode(cast<PHINode>(I), NewOps, Q); 6304 break; 6305 case Instruction::Call: { 6306 // TODO: Use NewOps 6307 Result = SimplifyCall(cast<CallInst>(I), Q); 6308 break; 6309 } 6310 case Instruction::Freeze: 6311 Result = llvm::SimplifyFreezeInst(NewOps[0], Q); 6312 break; 6313 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc: 6314 #include "llvm/IR/Instruction.def" 6315 #undef HANDLE_CAST_INST 6316 Result = SimplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q); 6317 break; 6318 case Instruction::Alloca: 6319 // No simplifications for Alloca and it can't be constant folded. 6320 Result = nullptr; 6321 break; 6322 case Instruction::Load: 6323 Result = SimplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q); 6324 break; 6325 } 6326 6327 /// If called on unreachable code, the above logic may report that the 6328 /// instruction simplified to itself. Make life easier for users by 6329 /// detecting that case here, returning a safe value instead. 6330 return Result == I ? UndefValue::get(I->getType()) : Result; 6331 } 6332 6333 Value *llvm::SimplifyInstructionWithOperands(Instruction *I, 6334 ArrayRef<Value *> NewOps, 6335 const SimplifyQuery &SQ, 6336 OptimizationRemarkEmitter *ORE) { 6337 assert(NewOps.size() == I->getNumOperands() && 6338 "Number of operands should match the instruction!"); 6339 return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE); 6340 } 6341 6342 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ, 6343 OptimizationRemarkEmitter *ORE) { 6344 SmallVector<Value *, 8> Ops(I->operands()); 6345 return ::simplifyInstructionWithOperands(I, Ops, SQ, ORE); 6346 } 6347 6348 /// Implementation of recursive simplification through an instruction's 6349 /// uses. 6350 /// 6351 /// This is the common implementation of the recursive simplification routines. 6352 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to 6353 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of 6354 /// instructions to process and attempt to simplify it using 6355 /// InstructionSimplify. Recursively visited users which could not be 6356 /// simplified themselves are to the optional UnsimplifiedUsers set for 6357 /// further processing by the caller. 6358 /// 6359 /// This routine returns 'true' only when *it* simplifies something. The passed 6360 /// in simplified value does not count toward this. 6361 static bool replaceAndRecursivelySimplifyImpl( 6362 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI, 6363 const DominatorTree *DT, AssumptionCache *AC, 6364 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) { 6365 bool Simplified = false; 6366 SmallSetVector<Instruction *, 8> Worklist; 6367 const DataLayout &DL = I->getModule()->getDataLayout(); 6368 6369 // If we have an explicit value to collapse to, do that round of the 6370 // simplification loop by hand initially. 6371 if (SimpleV) { 6372 for (User *U : I->users()) 6373 if (U != I) 6374 Worklist.insert(cast<Instruction>(U)); 6375 6376 // Replace the instruction with its simplified value. 6377 I->replaceAllUsesWith(SimpleV); 6378 6379 // Gracefully handle edge cases where the instruction is not wired into any 6380 // parent block. 6381 if (I->getParent() && !I->isEHPad() && !I->isTerminator() && 6382 !I->mayHaveSideEffects()) 6383 I->eraseFromParent(); 6384 } else { 6385 Worklist.insert(I); 6386 } 6387 6388 // Note that we must test the size on each iteration, the worklist can grow. 6389 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 6390 I = Worklist[Idx]; 6391 6392 // See if this instruction simplifies. 6393 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC}); 6394 if (!SimpleV) { 6395 if (UnsimplifiedUsers) 6396 UnsimplifiedUsers->insert(I); 6397 continue; 6398 } 6399 6400 Simplified = true; 6401 6402 // Stash away all the uses of the old instruction so we can check them for 6403 // recursive simplifications after a RAUW. This is cheaper than checking all 6404 // uses of To on the recursive step in most cases. 6405 for (User *U : I->users()) 6406 Worklist.insert(cast<Instruction>(U)); 6407 6408 // Replace the instruction with its simplified value. 6409 I->replaceAllUsesWith(SimpleV); 6410 6411 // Gracefully handle edge cases where the instruction is not wired into any 6412 // parent block. 6413 if (I->getParent() && !I->isEHPad() && !I->isTerminator() && 6414 !I->mayHaveSideEffects()) 6415 I->eraseFromParent(); 6416 } 6417 return Simplified; 6418 } 6419 6420 bool llvm::replaceAndRecursivelySimplify( 6421 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI, 6422 const DominatorTree *DT, AssumptionCache *AC, 6423 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) { 6424 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!"); 6425 assert(SimpleV && "Must provide a simplified value."); 6426 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC, 6427 UnsimplifiedUsers); 6428 } 6429 6430 namespace llvm { 6431 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) { 6432 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 6433 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 6434 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 6435 auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr; 6436 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>(); 6437 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr; 6438 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 6439 } 6440 6441 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR, 6442 const DataLayout &DL) { 6443 return {DL, &AR.TLI, &AR.DT, &AR.AC}; 6444 } 6445 6446 template <class T, class... TArgs> 6447 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM, 6448 Function &F) { 6449 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F); 6450 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F); 6451 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F); 6452 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 6453 } 6454 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &, 6455 Function &); 6456 } 6457