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