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) || isa<PoisonValue>(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 // X ^ poison -> poison 2422 if (isa<PoisonValue>(Op1)) 2423 return Op1; 2424 2425 // A ^ undef -> undef 2426 if (Q.isUndefValue(Op1)) 2427 return Op1; 2428 2429 // A ^ 0 = A 2430 if (match(Op1, m_Zero())) 2431 return Op0; 2432 2433 // A ^ A = 0 2434 if (Op0 == Op1) 2435 return Constant::getNullValue(Op0->getType()); 2436 2437 // A ^ ~A = ~A ^ A = -1 2438 if (match(Op0, m_Not(m_Specific(Op1))) || 2439 match(Op1, m_Not(m_Specific(Op0)))) 2440 return Constant::getAllOnesValue(Op0->getType()); 2441 2442 auto foldAndOrNot = [](Value *X, Value *Y) -> Value * { 2443 Value *A, *B; 2444 // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants. 2445 if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) && 2446 match(Y, m_c_Or(m_Specific(A), m_Specific(B)))) 2447 return A; 2448 2449 // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants. 2450 // The 'not' op must contain a complete -1 operand (no undef elements for 2451 // vector) for the transform to be safe. 2452 Value *NotA; 2453 if (match(X, 2454 m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)), 2455 m_Value(B))) && 2456 match(Y, m_c_And(m_Specific(A), m_Specific(B)))) 2457 return NotA; 2458 2459 return nullptr; 2460 }; 2461 if (Value *R = foldAndOrNot(Op0, Op1)) 2462 return R; 2463 if (Value *R = foldAndOrNot(Op1, Op0)) 2464 return R; 2465 2466 if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor)) 2467 return V; 2468 2469 // Try some generic simplifications for associative operations. 2470 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, 2471 MaxRecurse)) 2472 return V; 2473 2474 // Threading Xor over selects and phi nodes is pointless, so don't bother. 2475 // Threading over the select in "A ^ select(cond, B, C)" means evaluating 2476 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and 2477 // only if B and C are equal. If B and C are equal then (since we assume 2478 // that operands have already been simplified) "select(cond, B, C)" should 2479 // have been simplified to the common value of B and C already. Analysing 2480 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly 2481 // for threading over phi nodes. 2482 2483 return nullptr; 2484 } 2485 2486 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) { 2487 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit); 2488 } 2489 2490 2491 static Type *GetCompareTy(Value *Op) { 2492 return CmpInst::makeCmpResultType(Op->getType()); 2493 } 2494 2495 /// Rummage around inside V looking for something equivalent to the comparison 2496 /// "LHS Pred RHS". Return such a value if found, otherwise return null. 2497 /// Helper function for analyzing max/min idioms. 2498 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, 2499 Value *LHS, Value *RHS) { 2500 SelectInst *SI = dyn_cast<SelectInst>(V); 2501 if (!SI) 2502 return nullptr; 2503 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 2504 if (!Cmp) 2505 return nullptr; 2506 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); 2507 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) 2508 return Cmp; 2509 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && 2510 LHS == CmpRHS && RHS == CmpLHS) 2511 return Cmp; 2512 return nullptr; 2513 } 2514 2515 // A significant optimization not implemented here is assuming that alloca 2516 // addresses are not equal to incoming argument values. They don't *alias*, 2517 // as we say, but that doesn't mean they aren't equal, so we take a 2518 // conservative approach. 2519 // 2520 // This is inspired in part by C++11 5.10p1: 2521 // "Two pointers of the same type compare equal if and only if they are both 2522 // null, both point to the same function, or both represent the same 2523 // address." 2524 // 2525 // This is pretty permissive. 2526 // 2527 // It's also partly due to C11 6.5.9p6: 2528 // "Two pointers compare equal if and only if both are null pointers, both are 2529 // pointers to the same object (including a pointer to an object and a 2530 // subobject at its beginning) or function, both are pointers to one past the 2531 // last element of the same array object, or one is a pointer to one past the 2532 // end of one array object and the other is a pointer to the start of a 2533 // different array object that happens to immediately follow the first array 2534 // object in the address space.) 2535 // 2536 // C11's version is more restrictive, however there's no reason why an argument 2537 // couldn't be a one-past-the-end value for a stack object in the caller and be 2538 // equal to the beginning of a stack object in the callee. 2539 // 2540 // If the C and C++ standards are ever made sufficiently restrictive in this 2541 // area, it may be possible to update LLVM's semantics accordingly and reinstate 2542 // this optimization. 2543 static Constant * 2544 computePointerICmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 2545 const SimplifyQuery &Q) { 2546 const DataLayout &DL = Q.DL; 2547 const TargetLibraryInfo *TLI = Q.TLI; 2548 const DominatorTree *DT = Q.DT; 2549 const Instruction *CxtI = Q.CxtI; 2550 const InstrInfoQuery &IIQ = Q.IIQ; 2551 2552 // First, skip past any trivial no-ops. 2553 LHS = LHS->stripPointerCasts(); 2554 RHS = RHS->stripPointerCasts(); 2555 2556 // A non-null pointer is not equal to a null pointer. 2557 if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) && 2558 llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr, 2559 IIQ.UseInstrInfo)) 2560 return ConstantInt::get(GetCompareTy(LHS), 2561 !CmpInst::isTrueWhenEqual(Pred)); 2562 2563 // We can only fold certain predicates on pointer comparisons. 2564 switch (Pred) { 2565 default: 2566 return nullptr; 2567 2568 // Equality comaprisons are easy to fold. 2569 case CmpInst::ICMP_EQ: 2570 case CmpInst::ICMP_NE: 2571 break; 2572 2573 // We can only handle unsigned relational comparisons because 'inbounds' on 2574 // a GEP only protects against unsigned wrapping. 2575 case CmpInst::ICMP_UGT: 2576 case CmpInst::ICMP_UGE: 2577 case CmpInst::ICMP_ULT: 2578 case CmpInst::ICMP_ULE: 2579 // However, we have to switch them to their signed variants to handle 2580 // negative indices from the base pointer. 2581 Pred = ICmpInst::getSignedPredicate(Pred); 2582 break; 2583 } 2584 2585 // Strip off any constant offsets so that we can reason about them. 2586 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets 2587 // here and compare base addresses like AliasAnalysis does, however there are 2588 // numerous hazards. AliasAnalysis and its utilities rely on special rules 2589 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis 2590 // doesn't need to guarantee pointer inequality when it says NoAlias. 2591 2592 // Even if an non-inbounds GEP occurs along the path we can still optimize 2593 // equality comparisons concerning the result. 2594 bool AllowNonInbounds = ICmpInst::isEquality(Pred); 2595 Constant *LHSOffset = 2596 stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds); 2597 Constant *RHSOffset = 2598 stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds); 2599 2600 // If LHS and RHS are related via constant offsets to the same base 2601 // value, we can replace it with an icmp which just compares the offsets. 2602 if (LHS == RHS) 2603 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); 2604 2605 // Various optimizations for (in)equality comparisons. 2606 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { 2607 // Different non-empty allocations that exist at the same time have 2608 // different addresses (if the program can tell). Global variables always 2609 // exist, so they always exist during the lifetime of each other and all 2610 // allocas. Two different allocas usually have different addresses... 2611 // 2612 // However, if there's an @llvm.stackrestore dynamically in between two 2613 // allocas, they may have the same address. It's tempting to reduce the 2614 // scope of the problem by only looking at *static* allocas here. That would 2615 // cover the majority of allocas while significantly reducing the likelihood 2616 // of having an @llvm.stackrestore pop up in the middle. However, it's not 2617 // actually impossible for an @llvm.stackrestore to pop up in the middle of 2618 // an entry block. Also, if we have a block that's not attached to a 2619 // function, we can't tell if it's "static" under the current definition. 2620 // Theoretically, this problem could be fixed by creating a new kind of 2621 // instruction kind specifically for static allocas. Such a new instruction 2622 // could be required to be at the top of the entry block, thus preventing it 2623 // from being subject to a @llvm.stackrestore. Instcombine could even 2624 // convert regular allocas into these special allocas. It'd be nifty. 2625 // However, until then, this problem remains open. 2626 // 2627 // So, we'll assume that two non-empty allocas have different addresses 2628 // for now. 2629 // 2630 // With all that, if the offsets are within the bounds of their allocations 2631 // (and not one-past-the-end! so we can't use inbounds!), and their 2632 // allocations aren't the same, the pointers are not equal. 2633 // 2634 // Note that it's not necessary to check for LHS being a global variable 2635 // address, due to canonicalization and constant folding. 2636 if (isa<AllocaInst>(LHS) && 2637 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { 2638 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); 2639 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); 2640 uint64_t LHSSize, RHSSize; 2641 ObjectSizeOpts Opts; 2642 Opts.NullIsUnknownSize = 2643 NullPointerIsDefined(cast<AllocaInst>(LHS)->getFunction()); 2644 if (LHSOffsetCI && RHSOffsetCI && 2645 getObjectSize(LHS, LHSSize, DL, TLI, Opts) && 2646 getObjectSize(RHS, RHSSize, DL, TLI, Opts)) { 2647 const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); 2648 const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); 2649 if (!LHSOffsetValue.isNegative() && 2650 !RHSOffsetValue.isNegative() && 2651 LHSOffsetValue.ult(LHSSize) && 2652 RHSOffsetValue.ult(RHSSize)) { 2653 return ConstantInt::get(GetCompareTy(LHS), 2654 !CmpInst::isTrueWhenEqual(Pred)); 2655 } 2656 } 2657 2658 // Repeat the above check but this time without depending on DataLayout 2659 // or being able to compute a precise size. 2660 if (!cast<PointerType>(LHS->getType())->isEmptyTy() && 2661 !cast<PointerType>(RHS->getType())->isEmptyTy() && 2662 LHSOffset->isNullValue() && 2663 RHSOffset->isNullValue()) 2664 return ConstantInt::get(GetCompareTy(LHS), 2665 !CmpInst::isTrueWhenEqual(Pred)); 2666 } 2667 2668 // If one side of the equality comparison must come from a noalias call 2669 // (meaning a system memory allocation function), and the other side must 2670 // come from a pointer that cannot overlap with dynamically-allocated 2671 // memory within the lifetime of the current function (allocas, byval 2672 // arguments, globals), then determine the comparison result here. 2673 SmallVector<const Value *, 8> LHSUObjs, RHSUObjs; 2674 getUnderlyingObjects(LHS, LHSUObjs); 2675 getUnderlyingObjects(RHS, RHSUObjs); 2676 2677 // Is the set of underlying objects all noalias calls? 2678 auto IsNAC = [](ArrayRef<const Value *> Objects) { 2679 return all_of(Objects, isNoAliasCall); 2680 }; 2681 2682 // Is the set of underlying objects all things which must be disjoint from 2683 // noalias calls. For allocas, we consider only static ones (dynamic 2684 // allocas might be transformed into calls to malloc not simultaneously 2685 // live with the compared-to allocation). For globals, we exclude symbols 2686 // that might be resolve lazily to symbols in another dynamically-loaded 2687 // library (and, thus, could be malloc'ed by the implementation). 2688 auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) { 2689 return all_of(Objects, [](const Value *V) { 2690 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V)) 2691 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca(); 2692 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V)) 2693 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() || 2694 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) && 2695 !GV->isThreadLocal(); 2696 if (const Argument *A = dyn_cast<Argument>(V)) 2697 return A->hasByValAttr(); 2698 return false; 2699 }); 2700 }; 2701 2702 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) || 2703 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs))) 2704 return ConstantInt::get(GetCompareTy(LHS), 2705 !CmpInst::isTrueWhenEqual(Pred)); 2706 2707 // Fold comparisons for non-escaping pointer even if the allocation call 2708 // cannot be elided. We cannot fold malloc comparison to null. Also, the 2709 // dynamic allocation call could be either of the operands. Note that 2710 // the other operand can not be based on the alloc - if it were, then 2711 // the cmp itself would be a capture. 2712 Value *MI = nullptr; 2713 if (isAllocLikeFn(LHS, TLI) && 2714 llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT)) 2715 MI = LHS; 2716 else if (isAllocLikeFn(RHS, TLI) && 2717 llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT)) 2718 MI = RHS; 2719 // FIXME: We should also fold the compare when the pointer escapes, but the 2720 // compare dominates the pointer escape 2721 if (MI && !PointerMayBeCaptured(MI, true, true)) 2722 return ConstantInt::get(GetCompareTy(LHS), 2723 CmpInst::isFalseWhenEqual(Pred)); 2724 } 2725 2726 // Otherwise, fail. 2727 return nullptr; 2728 } 2729 2730 /// Fold an icmp when its operands have i1 scalar type. 2731 static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS, 2732 Value *RHS, const SimplifyQuery &Q) { 2733 Type *ITy = GetCompareTy(LHS); // The return type. 2734 Type *OpTy = LHS->getType(); // The operand type. 2735 if (!OpTy->isIntOrIntVectorTy(1)) 2736 return nullptr; 2737 2738 // A boolean compared to true/false can be reduced in 14 out of the 20 2739 // (10 predicates * 2 constants) possible combinations. The other 2740 // 6 cases require a 'not' of the LHS. 2741 2742 auto ExtractNotLHS = [](Value *V) -> Value * { 2743 Value *X; 2744 if (match(V, m_Not(m_Value(X)))) 2745 return X; 2746 return nullptr; 2747 }; 2748 2749 if (match(RHS, m_Zero())) { 2750 switch (Pred) { 2751 case CmpInst::ICMP_NE: // X != 0 -> X 2752 case CmpInst::ICMP_UGT: // X >u 0 -> X 2753 case CmpInst::ICMP_SLT: // X <s 0 -> X 2754 return LHS; 2755 2756 case CmpInst::ICMP_EQ: // not(X) == 0 -> X != 0 -> X 2757 case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X 2758 case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X 2759 if (Value *X = ExtractNotLHS(LHS)) 2760 return X; 2761 break; 2762 2763 case CmpInst::ICMP_ULT: // X <u 0 -> false 2764 case CmpInst::ICMP_SGT: // X >s 0 -> false 2765 return getFalse(ITy); 2766 2767 case CmpInst::ICMP_UGE: // X >=u 0 -> true 2768 case CmpInst::ICMP_SLE: // X <=s 0 -> true 2769 return getTrue(ITy); 2770 2771 default: break; 2772 } 2773 } else if (match(RHS, m_One())) { 2774 switch (Pred) { 2775 case CmpInst::ICMP_EQ: // X == 1 -> X 2776 case CmpInst::ICMP_UGE: // X >=u 1 -> X 2777 case CmpInst::ICMP_SLE: // X <=s -1 -> X 2778 return LHS; 2779 2780 case CmpInst::ICMP_NE: // not(X) != 1 -> X == 1 -> X 2781 case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u 1 -> X 2782 case CmpInst::ICMP_SGT: // not(X) >s 1 -> X <=s -1 -> X 2783 if (Value *X = ExtractNotLHS(LHS)) 2784 return X; 2785 break; 2786 2787 case CmpInst::ICMP_UGT: // X >u 1 -> false 2788 case CmpInst::ICMP_SLT: // X <s -1 -> false 2789 return getFalse(ITy); 2790 2791 case CmpInst::ICMP_ULE: // X <=u 1 -> true 2792 case CmpInst::ICMP_SGE: // X >=s -1 -> true 2793 return getTrue(ITy); 2794 2795 default: break; 2796 } 2797 } 2798 2799 switch (Pred) { 2800 default: 2801 break; 2802 case ICmpInst::ICMP_UGE: 2803 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false)) 2804 return getTrue(ITy); 2805 break; 2806 case ICmpInst::ICMP_SGE: 2807 /// For signed comparison, the values for an i1 are 0 and -1 2808 /// respectively. This maps into a truth table of: 2809 /// LHS | RHS | LHS >=s RHS | LHS implies RHS 2810 /// 0 | 0 | 1 (0 >= 0) | 1 2811 /// 0 | 1 | 1 (0 >= -1) | 1 2812 /// 1 | 0 | 0 (-1 >= 0) | 0 2813 /// 1 | 1 | 1 (-1 >= -1) | 1 2814 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2815 return getTrue(ITy); 2816 break; 2817 case ICmpInst::ICMP_ULE: 2818 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false)) 2819 return getTrue(ITy); 2820 break; 2821 } 2822 2823 return nullptr; 2824 } 2825 2826 /// Try hard to fold icmp with zero RHS because this is a common case. 2827 static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS, 2828 Value *RHS, const SimplifyQuery &Q) { 2829 if (!match(RHS, m_Zero())) 2830 return nullptr; 2831 2832 Type *ITy = GetCompareTy(LHS); // The return type. 2833 switch (Pred) { 2834 default: 2835 llvm_unreachable("Unknown ICmp predicate!"); 2836 case ICmpInst::ICMP_ULT: 2837 return getFalse(ITy); 2838 case ICmpInst::ICMP_UGE: 2839 return getTrue(ITy); 2840 case ICmpInst::ICMP_EQ: 2841 case ICmpInst::ICMP_ULE: 2842 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) 2843 return getFalse(ITy); 2844 break; 2845 case ICmpInst::ICMP_NE: 2846 case ICmpInst::ICMP_UGT: 2847 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) 2848 return getTrue(ITy); 2849 break; 2850 case ICmpInst::ICMP_SLT: { 2851 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2852 if (LHSKnown.isNegative()) 2853 return getTrue(ITy); 2854 if (LHSKnown.isNonNegative()) 2855 return getFalse(ITy); 2856 break; 2857 } 2858 case ICmpInst::ICMP_SLE: { 2859 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2860 if (LHSKnown.isNegative()) 2861 return getTrue(ITy); 2862 if (LHSKnown.isNonNegative() && 2863 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2864 return getFalse(ITy); 2865 break; 2866 } 2867 case ICmpInst::ICMP_SGE: { 2868 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2869 if (LHSKnown.isNegative()) 2870 return getFalse(ITy); 2871 if (LHSKnown.isNonNegative()) 2872 return getTrue(ITy); 2873 break; 2874 } 2875 case ICmpInst::ICMP_SGT: { 2876 KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2877 if (LHSKnown.isNegative()) 2878 return getFalse(ITy); 2879 if (LHSKnown.isNonNegative() && 2880 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 2881 return getTrue(ITy); 2882 break; 2883 } 2884 } 2885 2886 return nullptr; 2887 } 2888 2889 static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS, 2890 Value *RHS, const InstrInfoQuery &IIQ) { 2891 Type *ITy = GetCompareTy(RHS); // The return type. 2892 2893 Value *X; 2894 // Sign-bit checks can be optimized to true/false after unsigned 2895 // floating-point casts: 2896 // icmp slt (bitcast (uitofp X)), 0 --> false 2897 // icmp sgt (bitcast (uitofp X)), -1 --> true 2898 if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) { 2899 if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero())) 2900 return ConstantInt::getFalse(ITy); 2901 if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes())) 2902 return ConstantInt::getTrue(ITy); 2903 } 2904 2905 const APInt *C; 2906 if (!match(RHS, m_APIntAllowUndef(C))) 2907 return nullptr; 2908 2909 // Rule out tautological comparisons (eg., ult 0 or uge 0). 2910 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C); 2911 if (RHS_CR.isEmptySet()) 2912 return ConstantInt::getFalse(ITy); 2913 if (RHS_CR.isFullSet()) 2914 return ConstantInt::getTrue(ITy); 2915 2916 ConstantRange LHS_CR = 2917 computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo); 2918 if (!LHS_CR.isFullSet()) { 2919 if (RHS_CR.contains(LHS_CR)) 2920 return ConstantInt::getTrue(ITy); 2921 if (RHS_CR.inverse().contains(LHS_CR)) 2922 return ConstantInt::getFalse(ITy); 2923 } 2924 2925 // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC) 2926 // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC) 2927 const APInt *MulC; 2928 if (ICmpInst::isEquality(Pred) && 2929 ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) && 2930 *MulC != 0 && C->urem(*MulC) != 0) || 2931 (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) && 2932 *MulC != 0 && C->srem(*MulC) != 0))) 2933 return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE); 2934 2935 return nullptr; 2936 } 2937 2938 static Value *simplifyICmpWithBinOpOnLHS( 2939 CmpInst::Predicate Pred, BinaryOperator *LBO, Value *RHS, 2940 const SimplifyQuery &Q, unsigned MaxRecurse) { 2941 Type *ITy = GetCompareTy(RHS); // The return type. 2942 2943 Value *Y = nullptr; 2944 // icmp pred (or X, Y), X 2945 if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) { 2946 if (Pred == ICmpInst::ICMP_ULT) 2947 return getFalse(ITy); 2948 if (Pred == ICmpInst::ICMP_UGE) 2949 return getTrue(ITy); 2950 2951 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) { 2952 KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2953 KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2954 if (RHSKnown.isNonNegative() && YKnown.isNegative()) 2955 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy); 2956 if (RHSKnown.isNegative() || YKnown.isNonNegative()) 2957 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy); 2958 } 2959 } 2960 2961 // icmp pred (and X, Y), X 2962 if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) { 2963 if (Pred == ICmpInst::ICMP_UGT) 2964 return getFalse(ITy); 2965 if (Pred == ICmpInst::ICMP_ULE) 2966 return getTrue(ITy); 2967 } 2968 2969 // icmp pred (urem X, Y), Y 2970 if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { 2971 switch (Pred) { 2972 default: 2973 break; 2974 case ICmpInst::ICMP_SGT: 2975 case ICmpInst::ICMP_SGE: { 2976 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2977 if (!Known.isNonNegative()) 2978 break; 2979 LLVM_FALLTHROUGH; 2980 } 2981 case ICmpInst::ICMP_EQ: 2982 case ICmpInst::ICMP_UGT: 2983 case ICmpInst::ICMP_UGE: 2984 return getFalse(ITy); 2985 case ICmpInst::ICMP_SLT: 2986 case ICmpInst::ICMP_SLE: { 2987 KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT); 2988 if (!Known.isNonNegative()) 2989 break; 2990 LLVM_FALLTHROUGH; 2991 } 2992 case ICmpInst::ICMP_NE: 2993 case ICmpInst::ICMP_ULT: 2994 case ICmpInst::ICMP_ULE: 2995 return getTrue(ITy); 2996 } 2997 } 2998 2999 // icmp pred (urem X, Y), X 3000 if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) { 3001 if (Pred == ICmpInst::ICMP_ULE) 3002 return getTrue(ITy); 3003 if (Pred == ICmpInst::ICMP_UGT) 3004 return getFalse(ITy); 3005 } 3006 3007 // x >>u y <=u x --> true. 3008 // x >>u y >u x --> false. 3009 // x udiv y <=u x --> true. 3010 // x udiv y >u x --> false. 3011 if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) || 3012 match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) { 3013 // icmp pred (X op Y), X 3014 if (Pred == ICmpInst::ICMP_UGT) 3015 return getFalse(ITy); 3016 if (Pred == ICmpInst::ICMP_ULE) 3017 return getTrue(ITy); 3018 } 3019 3020 // If x is nonzero: 3021 // x >>u C <u x --> true for C != 0. 3022 // x >>u C != x --> true for C != 0. 3023 // x >>u C >=u x --> false for C != 0. 3024 // x >>u C == x --> false for C != 0. 3025 // x udiv C <u x --> true for C != 1. 3026 // x udiv C != x --> true for C != 1. 3027 // x udiv C >=u x --> false for C != 1. 3028 // x udiv C == x --> false for C != 1. 3029 // TODO: allow non-constant shift amount/divisor 3030 const APInt *C; 3031 if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) || 3032 (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) { 3033 if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) { 3034 switch (Pred) { 3035 default: 3036 break; 3037 case ICmpInst::ICMP_EQ: 3038 case ICmpInst::ICMP_UGE: 3039 return getFalse(ITy); 3040 case ICmpInst::ICMP_NE: 3041 case ICmpInst::ICMP_ULT: 3042 return getTrue(ITy); 3043 case ICmpInst::ICMP_UGT: 3044 case ICmpInst::ICMP_ULE: 3045 // UGT/ULE are handled by the more general case just above 3046 llvm_unreachable("Unexpected UGT/ULE, should have been handled"); 3047 } 3048 } 3049 } 3050 3051 // (x*C1)/C2 <= x for C1 <= C2. 3052 // This holds even if the multiplication overflows: Assume that x != 0 and 3053 // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and 3054 // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x. 3055 // 3056 // Additionally, either the multiplication and division might be represented 3057 // as shifts: 3058 // (x*C1)>>C2 <= x for C1 < 2**C2. 3059 // (x<<C1)/C2 <= x for 2**C1 < C2. 3060 const APInt *C1, *C2; 3061 if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 3062 C1->ule(*C2)) || 3063 (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 3064 C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) || 3065 (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) && 3066 (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) { 3067 if (Pred == ICmpInst::ICMP_UGT) 3068 return getFalse(ITy); 3069 if (Pred == ICmpInst::ICMP_ULE) 3070 return getTrue(ITy); 3071 } 3072 3073 return nullptr; 3074 } 3075 3076 3077 // If only one of the icmp's operands has NSW flags, try to prove that: 3078 // 3079 // icmp slt (x + C1), (x +nsw C2) 3080 // 3081 // is equivalent to: 3082 // 3083 // icmp slt C1, C2 3084 // 3085 // which is true if x + C2 has the NSW flags set and: 3086 // *) C1 < C2 && C1 >= 0, or 3087 // *) C2 < C1 && C1 <= 0. 3088 // 3089 static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS, 3090 Value *RHS) { 3091 // TODO: only support icmp slt for now. 3092 if (Pred != CmpInst::ICMP_SLT) 3093 return false; 3094 3095 // Canonicalize nsw add as RHS. 3096 if (!match(RHS, m_NSWAdd(m_Value(), m_Value()))) 3097 std::swap(LHS, RHS); 3098 if (!match(RHS, m_NSWAdd(m_Value(), m_Value()))) 3099 return false; 3100 3101 Value *X; 3102 const APInt *C1, *C2; 3103 if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) || 3104 !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2)))) 3105 return false; 3106 3107 return (C1->slt(*C2) && C1->isNonNegative()) || 3108 (C2->slt(*C1) && C1->isNonPositive()); 3109 } 3110 3111 3112 /// TODO: A large part of this logic is duplicated in InstCombine's 3113 /// foldICmpBinOp(). We should be able to share that and avoid the code 3114 /// duplication. 3115 static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS, 3116 Value *RHS, const SimplifyQuery &Q, 3117 unsigned MaxRecurse) { 3118 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); 3119 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); 3120 if (MaxRecurse && (LBO || RBO)) { 3121 // Analyze the case when either LHS or RHS is an add instruction. 3122 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 3123 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). 3124 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; 3125 if (LBO && LBO->getOpcode() == Instruction::Add) { 3126 A = LBO->getOperand(0); 3127 B = LBO->getOperand(1); 3128 NoLHSWrapProblem = 3129 ICmpInst::isEquality(Pred) || 3130 (CmpInst::isUnsigned(Pred) && 3131 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) || 3132 (CmpInst::isSigned(Pred) && 3133 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO))); 3134 } 3135 if (RBO && RBO->getOpcode() == Instruction::Add) { 3136 C = RBO->getOperand(0); 3137 D = RBO->getOperand(1); 3138 NoRHSWrapProblem = 3139 ICmpInst::isEquality(Pred) || 3140 (CmpInst::isUnsigned(Pred) && 3141 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) || 3142 (CmpInst::isSigned(Pred) && 3143 Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO))); 3144 } 3145 3146 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 3147 if ((A == RHS || B == RHS) && NoLHSWrapProblem) 3148 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, 3149 Constant::getNullValue(RHS->getType()), Q, 3150 MaxRecurse - 1)) 3151 return V; 3152 3153 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 3154 if ((C == LHS || D == LHS) && NoRHSWrapProblem) 3155 if (Value *V = 3156 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()), 3157 C == LHS ? D : C, Q, MaxRecurse - 1)) 3158 return V; 3159 3160 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. 3161 bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) || 3162 trySimplifyICmpWithAdds(Pred, LHS, RHS); 3163 if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) { 3164 // Determine Y and Z in the form icmp (X+Y), (X+Z). 3165 Value *Y, *Z; 3166 if (A == C) { 3167 // C + B == C + D -> B == D 3168 Y = B; 3169 Z = D; 3170 } else if (A == D) { 3171 // D + B == C + D -> B == C 3172 Y = B; 3173 Z = C; 3174 } else if (B == C) { 3175 // A + C == C + D -> A == D 3176 Y = A; 3177 Z = D; 3178 } else { 3179 assert(B == D); 3180 // A + D == C + D -> A == C 3181 Y = A; 3182 Z = C; 3183 } 3184 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1)) 3185 return V; 3186 } 3187 } 3188 3189 if (LBO) 3190 if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse)) 3191 return V; 3192 3193 if (RBO) 3194 if (Value *V = simplifyICmpWithBinOpOnLHS( 3195 ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse)) 3196 return V; 3197 3198 // 0 - (zext X) pred C 3199 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) { 3200 const APInt *C; 3201 if (match(RHS, m_APInt(C))) { 3202 if (C->isStrictlyPositive()) { 3203 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE) 3204 return ConstantInt::getTrue(GetCompareTy(RHS)); 3205 if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ) 3206 return ConstantInt::getFalse(GetCompareTy(RHS)); 3207 } 3208 if (C->isNonNegative()) { 3209 if (Pred == ICmpInst::ICMP_SLE) 3210 return ConstantInt::getTrue(GetCompareTy(RHS)); 3211 if (Pred == ICmpInst::ICMP_SGT) 3212 return ConstantInt::getFalse(GetCompareTy(RHS)); 3213 } 3214 } 3215 } 3216 3217 // If C2 is a power-of-2 and C is not: 3218 // (C2 << X) == C --> false 3219 // (C2 << X) != C --> true 3220 const APInt *C; 3221 if (match(LHS, m_Shl(m_Power2(), m_Value())) && 3222 match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) { 3223 // C2 << X can equal zero in some circumstances. 3224 // This simplification might be unsafe if C is zero. 3225 // 3226 // We know it is safe if: 3227 // - The shift is nsw. We can't shift out the one bit. 3228 // - The shift is nuw. We can't shift out the one bit. 3229 // - C2 is one. 3230 // - C isn't zero. 3231 if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) || 3232 Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) || 3233 match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) { 3234 if (Pred == ICmpInst::ICMP_EQ) 3235 return ConstantInt::getFalse(GetCompareTy(RHS)); 3236 if (Pred == ICmpInst::ICMP_NE) 3237 return ConstantInt::getTrue(GetCompareTy(RHS)); 3238 } 3239 } 3240 3241 // TODO: This is overly constrained. LHS can be any power-of-2. 3242 // (1 << X) >u 0x8000 --> false 3243 // (1 << X) <=u 0x8000 --> true 3244 if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) { 3245 if (Pred == ICmpInst::ICMP_UGT) 3246 return ConstantInt::getFalse(GetCompareTy(RHS)); 3247 if (Pred == ICmpInst::ICMP_ULE) 3248 return ConstantInt::getTrue(GetCompareTy(RHS)); 3249 } 3250 3251 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && 3252 LBO->getOperand(1) == RBO->getOperand(1)) { 3253 switch (LBO->getOpcode()) { 3254 default: 3255 break; 3256 case Instruction::UDiv: 3257 case Instruction::LShr: 3258 if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) || 3259 !Q.IIQ.isExact(RBO)) 3260 break; 3261 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3262 RBO->getOperand(0), Q, MaxRecurse - 1)) 3263 return V; 3264 break; 3265 case Instruction::SDiv: 3266 if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) || 3267 !Q.IIQ.isExact(RBO)) 3268 break; 3269 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3270 RBO->getOperand(0), Q, MaxRecurse - 1)) 3271 return V; 3272 break; 3273 case Instruction::AShr: 3274 if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO)) 3275 break; 3276 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3277 RBO->getOperand(0), Q, MaxRecurse - 1)) 3278 return V; 3279 break; 3280 case Instruction::Shl: { 3281 bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO); 3282 bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO); 3283 if (!NUW && !NSW) 3284 break; 3285 if (!NSW && ICmpInst::isSigned(Pred)) 3286 break; 3287 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 3288 RBO->getOperand(0), Q, MaxRecurse - 1)) 3289 return V; 3290 break; 3291 } 3292 } 3293 } 3294 return nullptr; 3295 } 3296 3297 /// Simplify integer comparisons where at least one operand of the compare 3298 /// matches an integer min/max idiom. 3299 static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS, 3300 Value *RHS, const SimplifyQuery &Q, 3301 unsigned MaxRecurse) { 3302 Type *ITy = GetCompareTy(LHS); // The return type. 3303 Value *A, *B; 3304 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; 3305 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". 3306 3307 // Signed variants on "max(a,b)>=a -> true". 3308 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 3309 if (A != RHS) 3310 std::swap(A, B); // smax(A, B) pred A. 3311 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 3312 // We analyze this as smax(A, B) pred A. 3313 P = Pred; 3314 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && 3315 (A == LHS || B == LHS)) { 3316 if (A != LHS) 3317 std::swap(A, B); // A pred smax(A, B). 3318 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 3319 // We analyze this as smax(A, B) swapped-pred A. 3320 P = CmpInst::getSwappedPredicate(Pred); 3321 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 3322 (A == RHS || B == RHS)) { 3323 if (A != RHS) 3324 std::swap(A, B); // smin(A, B) pred A. 3325 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 3326 // We analyze this as smax(-A, -B) swapped-pred -A. 3327 // Note that we do not need to actually form -A or -B thanks to EqP. 3328 P = CmpInst::getSwappedPredicate(Pred); 3329 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && 3330 (A == LHS || B == LHS)) { 3331 if (A != LHS) 3332 std::swap(A, B); // A pred smin(A, B). 3333 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 3334 // We analyze this as smax(-A, -B) pred -A. 3335 // Note that we do not need to actually form -A or -B thanks to EqP. 3336 P = Pred; 3337 } 3338 if (P != CmpInst::BAD_ICMP_PREDICATE) { 3339 // Cases correspond to "max(A, B) p A". 3340 switch (P) { 3341 default: 3342 break; 3343 case CmpInst::ICMP_EQ: 3344 case CmpInst::ICMP_SLE: 3345 // Equivalent to "A EqP B". This may be the same as the condition tested 3346 // in the max/min; if so, we can just return that. 3347 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 3348 return V; 3349 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 3350 return V; 3351 // Otherwise, see if "A EqP B" simplifies. 3352 if (MaxRecurse) 3353 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 3354 return V; 3355 break; 3356 case CmpInst::ICMP_NE: 3357 case CmpInst::ICMP_SGT: { 3358 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 3359 // Equivalent to "A InvEqP B". This may be the same as the condition 3360 // tested in the max/min; if so, we can just return that. 3361 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 3362 return V; 3363 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 3364 return V; 3365 // Otherwise, see if "A InvEqP B" simplifies. 3366 if (MaxRecurse) 3367 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 3368 return V; 3369 break; 3370 } 3371 case CmpInst::ICMP_SGE: 3372 // Always true. 3373 return getTrue(ITy); 3374 case CmpInst::ICMP_SLT: 3375 // Always false. 3376 return getFalse(ITy); 3377 } 3378 } 3379 3380 // Unsigned variants on "max(a,b)>=a -> true". 3381 P = CmpInst::BAD_ICMP_PREDICATE; 3382 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 3383 if (A != RHS) 3384 std::swap(A, B); // umax(A, B) pred A. 3385 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 3386 // We analyze this as umax(A, B) pred A. 3387 P = Pred; 3388 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && 3389 (A == LHS || B == LHS)) { 3390 if (A != LHS) 3391 std::swap(A, B); // A pred umax(A, B). 3392 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 3393 // We analyze this as umax(A, B) swapped-pred A. 3394 P = CmpInst::getSwappedPredicate(Pred); 3395 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 3396 (A == RHS || B == RHS)) { 3397 if (A != RHS) 3398 std::swap(A, B); // umin(A, B) pred A. 3399 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 3400 // We analyze this as umax(-A, -B) swapped-pred -A. 3401 // Note that we do not need to actually form -A or -B thanks to EqP. 3402 P = CmpInst::getSwappedPredicate(Pred); 3403 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && 3404 (A == LHS || B == LHS)) { 3405 if (A != LHS) 3406 std::swap(A, B); // A pred umin(A, B). 3407 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 3408 // We analyze this as umax(-A, -B) pred -A. 3409 // Note that we do not need to actually form -A or -B thanks to EqP. 3410 P = Pred; 3411 } 3412 if (P != CmpInst::BAD_ICMP_PREDICATE) { 3413 // Cases correspond to "max(A, B) p A". 3414 switch (P) { 3415 default: 3416 break; 3417 case CmpInst::ICMP_EQ: 3418 case CmpInst::ICMP_ULE: 3419 // Equivalent to "A EqP B". This may be the same as the condition tested 3420 // in the max/min; if so, we can just return that. 3421 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 3422 return V; 3423 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 3424 return V; 3425 // Otherwise, see if "A EqP B" simplifies. 3426 if (MaxRecurse) 3427 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1)) 3428 return V; 3429 break; 3430 case CmpInst::ICMP_NE: 3431 case CmpInst::ICMP_UGT: { 3432 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 3433 // Equivalent to "A InvEqP B". This may be the same as the condition 3434 // tested in the max/min; if so, we can just return that. 3435 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 3436 return V; 3437 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 3438 return V; 3439 // Otherwise, see if "A InvEqP B" simplifies. 3440 if (MaxRecurse) 3441 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1)) 3442 return V; 3443 break; 3444 } 3445 case CmpInst::ICMP_UGE: 3446 return getTrue(ITy); 3447 case CmpInst::ICMP_ULT: 3448 return getFalse(ITy); 3449 } 3450 } 3451 3452 // Comparing 1 each of min/max with a common operand? 3453 // Canonicalize min operand to RHS. 3454 if (match(LHS, m_UMin(m_Value(), m_Value())) || 3455 match(LHS, m_SMin(m_Value(), m_Value()))) { 3456 std::swap(LHS, RHS); 3457 Pred = ICmpInst::getSwappedPredicate(Pred); 3458 } 3459 3460 Value *C, *D; 3461 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && 3462 match(RHS, m_SMin(m_Value(C), m_Value(D))) && 3463 (A == C || A == D || B == C || B == D)) { 3464 // smax(A, B) >=s smin(A, D) --> true 3465 if (Pred == CmpInst::ICMP_SGE) 3466 return getTrue(ITy); 3467 // smax(A, B) <s smin(A, D) --> false 3468 if (Pred == CmpInst::ICMP_SLT) 3469 return getFalse(ITy); 3470 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && 3471 match(RHS, m_UMin(m_Value(C), m_Value(D))) && 3472 (A == C || A == D || B == C || B == D)) { 3473 // umax(A, B) >=u umin(A, D) --> true 3474 if (Pred == CmpInst::ICMP_UGE) 3475 return getTrue(ITy); 3476 // umax(A, B) <u umin(A, D) --> false 3477 if (Pred == CmpInst::ICMP_ULT) 3478 return getFalse(ITy); 3479 } 3480 3481 return nullptr; 3482 } 3483 3484 static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate, 3485 Value *LHS, Value *RHS, 3486 const SimplifyQuery &Q) { 3487 // Gracefully handle instructions that have not been inserted yet. 3488 if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent()) 3489 return nullptr; 3490 3491 for (Value *AssumeBaseOp : {LHS, RHS}) { 3492 for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) { 3493 if (!AssumeVH) 3494 continue; 3495 3496 CallInst *Assume = cast<CallInst>(AssumeVH); 3497 if (Optional<bool> Imp = 3498 isImpliedCondition(Assume->getArgOperand(0), Predicate, LHS, RHS, 3499 Q.DL)) 3500 if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT)) 3501 return ConstantInt::get(GetCompareTy(LHS), *Imp); 3502 } 3503 } 3504 3505 return nullptr; 3506 } 3507 3508 /// Given operands for an ICmpInst, see if we can fold the result. 3509 /// If not, this returns null. 3510 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3511 const SimplifyQuery &Q, unsigned MaxRecurse) { 3512 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3513 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!"); 3514 3515 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3516 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3517 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3518 3519 // If we have a constant, make sure it is on the RHS. 3520 std::swap(LHS, RHS); 3521 Pred = CmpInst::getSwappedPredicate(Pred); 3522 } 3523 assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X"); 3524 3525 Type *ITy = GetCompareTy(LHS); // The return type. 3526 3527 // icmp poison, X -> poison 3528 if (isa<PoisonValue>(RHS)) 3529 return PoisonValue::get(ITy); 3530 3531 // For EQ and NE, we can always pick a value for the undef to make the 3532 // predicate pass or fail, so we can return undef. 3533 // Matches behavior in llvm::ConstantFoldCompareInstruction. 3534 if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred)) 3535 return UndefValue::get(ITy); 3536 3537 // icmp X, X -> true/false 3538 // icmp X, undef -> true/false because undef could be X. 3539 if (LHS == RHS || Q.isUndefValue(RHS)) 3540 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); 3541 3542 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q)) 3543 return V; 3544 3545 // TODO: Sink/common this with other potentially expensive calls that use 3546 // ValueTracking? See comment below for isKnownNonEqual(). 3547 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q)) 3548 return V; 3549 3550 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ)) 3551 return V; 3552 3553 // If both operands have range metadata, use the metadata 3554 // to simplify the comparison. 3555 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) { 3556 auto RHS_Instr = cast<Instruction>(RHS); 3557 auto LHS_Instr = cast<Instruction>(LHS); 3558 3559 if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) && 3560 Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) { 3561 auto RHS_CR = getConstantRangeFromMetadata( 3562 *RHS_Instr->getMetadata(LLVMContext::MD_range)); 3563 auto LHS_CR = getConstantRangeFromMetadata( 3564 *LHS_Instr->getMetadata(LLVMContext::MD_range)); 3565 3566 if (LHS_CR.icmp(Pred, RHS_CR)) 3567 return ConstantInt::getTrue(RHS->getContext()); 3568 3569 if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR)) 3570 return ConstantInt::getFalse(RHS->getContext()); 3571 } 3572 } 3573 3574 // Compare of cast, for example (zext X) != 0 -> X != 0 3575 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { 3576 Instruction *LI = cast<CastInst>(LHS); 3577 Value *SrcOp = LI->getOperand(0); 3578 Type *SrcTy = SrcOp->getType(); 3579 Type *DstTy = LI->getType(); 3580 3581 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input 3582 // if the integer type is the same size as the pointer type. 3583 if (MaxRecurse && isa<PtrToIntInst>(LI) && 3584 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) { 3585 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 3586 // Transfer the cast to the constant. 3587 if (Value *V = SimplifyICmpInst(Pred, SrcOp, 3588 ConstantExpr::getIntToPtr(RHSC, SrcTy), 3589 Q, MaxRecurse-1)) 3590 return V; 3591 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { 3592 if (RI->getOperand(0)->getType() == SrcTy) 3593 // Compare without the cast. 3594 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3595 Q, MaxRecurse-1)) 3596 return V; 3597 } 3598 } 3599 3600 if (isa<ZExtInst>(LHS)) { 3601 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the 3602 // same type. 3603 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 3604 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3605 // Compare X and Y. Note that signed predicates become unsigned. 3606 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3607 SrcOp, RI->getOperand(0), Q, 3608 MaxRecurse-1)) 3609 return V; 3610 } 3611 // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true. 3612 else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 3613 if (SrcOp == RI->getOperand(0)) { 3614 if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE) 3615 return ConstantInt::getTrue(ITy); 3616 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT) 3617 return ConstantInt::getFalse(ITy); 3618 } 3619 } 3620 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended 3621 // too. If not, then try to deduce the result of the comparison. 3622 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3623 // Compute the constant that would happen if we truncated to SrcTy then 3624 // reextended to DstTy. 3625 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3626 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); 3627 3628 // If the re-extended constant didn't change then this is effectively 3629 // also a case of comparing two zero-extended values. 3630 if (RExt == CI && MaxRecurse) 3631 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 3632 SrcOp, Trunc, Q, MaxRecurse-1)) 3633 return V; 3634 3635 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit 3636 // there. Use this to work out the result of the comparison. 3637 if (RExt != CI) { 3638 switch (Pred) { 3639 default: llvm_unreachable("Unknown ICmp predicate!"); 3640 // LHS <u RHS. 3641 case ICmpInst::ICMP_EQ: 3642 case ICmpInst::ICMP_UGT: 3643 case ICmpInst::ICMP_UGE: 3644 return ConstantInt::getFalse(CI->getContext()); 3645 3646 case ICmpInst::ICMP_NE: 3647 case ICmpInst::ICMP_ULT: 3648 case ICmpInst::ICMP_ULE: 3649 return ConstantInt::getTrue(CI->getContext()); 3650 3651 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS 3652 // is non-negative then LHS <s RHS. 3653 case ICmpInst::ICMP_SGT: 3654 case ICmpInst::ICMP_SGE: 3655 return CI->getValue().isNegative() ? 3656 ConstantInt::getTrue(CI->getContext()) : 3657 ConstantInt::getFalse(CI->getContext()); 3658 3659 case ICmpInst::ICMP_SLT: 3660 case ICmpInst::ICMP_SLE: 3661 return CI->getValue().isNegative() ? 3662 ConstantInt::getFalse(CI->getContext()) : 3663 ConstantInt::getTrue(CI->getContext()); 3664 } 3665 } 3666 } 3667 } 3668 3669 if (isa<SExtInst>(LHS)) { 3670 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the 3671 // same type. 3672 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 3673 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 3674 // Compare X and Y. Note that the predicate does not change. 3675 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 3676 Q, MaxRecurse-1)) 3677 return V; 3678 } 3679 // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true. 3680 else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 3681 if (SrcOp == RI->getOperand(0)) { 3682 if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE) 3683 return ConstantInt::getTrue(ITy); 3684 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT) 3685 return ConstantInt::getFalse(ITy); 3686 } 3687 } 3688 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended 3689 // too. If not, then try to deduce the result of the comparison. 3690 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 3691 // Compute the constant that would happen if we truncated to SrcTy then 3692 // reextended to DstTy. 3693 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 3694 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); 3695 3696 // If the re-extended constant didn't change then this is effectively 3697 // also a case of comparing two sign-extended values. 3698 if (RExt == CI && MaxRecurse) 3699 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) 3700 return V; 3701 3702 // Otherwise the upper bits of LHS are all equal, while RHS has varying 3703 // bits there. Use this to work out the result of the comparison. 3704 if (RExt != CI) { 3705 switch (Pred) { 3706 default: llvm_unreachable("Unknown ICmp predicate!"); 3707 case ICmpInst::ICMP_EQ: 3708 return ConstantInt::getFalse(CI->getContext()); 3709 case ICmpInst::ICMP_NE: 3710 return ConstantInt::getTrue(CI->getContext()); 3711 3712 // If RHS is non-negative then LHS <s RHS. If RHS is negative then 3713 // LHS >s RHS. 3714 case ICmpInst::ICMP_SGT: 3715 case ICmpInst::ICMP_SGE: 3716 return CI->getValue().isNegative() ? 3717 ConstantInt::getTrue(CI->getContext()) : 3718 ConstantInt::getFalse(CI->getContext()); 3719 case ICmpInst::ICMP_SLT: 3720 case ICmpInst::ICMP_SLE: 3721 return CI->getValue().isNegative() ? 3722 ConstantInt::getFalse(CI->getContext()) : 3723 ConstantInt::getTrue(CI->getContext()); 3724 3725 // If LHS is non-negative then LHS <u RHS. If LHS is negative then 3726 // LHS >u RHS. 3727 case ICmpInst::ICMP_UGT: 3728 case ICmpInst::ICMP_UGE: 3729 // Comparison is true iff the LHS <s 0. 3730 if (MaxRecurse) 3731 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, 3732 Constant::getNullValue(SrcTy), 3733 Q, MaxRecurse-1)) 3734 return V; 3735 break; 3736 case ICmpInst::ICMP_ULT: 3737 case ICmpInst::ICMP_ULE: 3738 // Comparison is true iff the LHS >=s 0. 3739 if (MaxRecurse) 3740 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, 3741 Constant::getNullValue(SrcTy), 3742 Q, MaxRecurse-1)) 3743 return V; 3744 break; 3745 } 3746 } 3747 } 3748 } 3749 } 3750 3751 // icmp eq|ne X, Y -> false|true if X != Y 3752 // This is potentially expensive, and we have already computedKnownBits for 3753 // compares with 0 above here, so only try this for a non-zero compare. 3754 if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) && 3755 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) { 3756 return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy); 3757 } 3758 3759 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse)) 3760 return V; 3761 3762 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse)) 3763 return V; 3764 3765 if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q)) 3766 return V; 3767 3768 // Simplify comparisons of related pointers using a powerful, recursive 3769 // GEP-walk when we have target data available.. 3770 if (LHS->getType()->isPointerTy()) 3771 if (auto *C = computePointerICmp(Pred, LHS, RHS, Q)) 3772 return C; 3773 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS)) 3774 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS)) 3775 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) == 3776 Q.DL.getTypeSizeInBits(CLHS->getType()) && 3777 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) == 3778 Q.DL.getTypeSizeInBits(CRHS->getType())) 3779 if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(), 3780 CRHS->getPointerOperand(), Q)) 3781 return C; 3782 3783 // If the comparison is with the result of a select instruction, check whether 3784 // comparing with either branch of the select always yields the same value. 3785 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3786 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3787 return V; 3788 3789 // If the comparison is with the result of a phi instruction, check whether 3790 // doing the compare with each incoming phi value yields a common result. 3791 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3792 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 3793 return V; 3794 3795 return nullptr; 3796 } 3797 3798 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3799 const SimplifyQuery &Q) { 3800 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 3801 } 3802 3803 /// Given operands for an FCmpInst, see if we can fold the result. 3804 /// If not, this returns null. 3805 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3806 FastMathFlags FMF, const SimplifyQuery &Q, 3807 unsigned MaxRecurse) { 3808 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 3809 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!"); 3810 3811 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 3812 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 3813 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 3814 3815 // If we have a constant, make sure it is on the RHS. 3816 std::swap(LHS, RHS); 3817 Pred = CmpInst::getSwappedPredicate(Pred); 3818 } 3819 3820 // Fold trivial predicates. 3821 Type *RetTy = GetCompareTy(LHS); 3822 if (Pred == FCmpInst::FCMP_FALSE) 3823 return getFalse(RetTy); 3824 if (Pred == FCmpInst::FCMP_TRUE) 3825 return getTrue(RetTy); 3826 3827 // Fold (un)ordered comparison if we can determine there are no NaNs. 3828 if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD) 3829 if (FMF.noNaNs() || 3830 (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI))) 3831 return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD); 3832 3833 // NaN is unordered; NaN is not ordered. 3834 assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) && 3835 "Comparison must be either ordered or unordered"); 3836 if (match(RHS, m_NaN())) 3837 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3838 3839 // fcmp pred x, poison and fcmp pred poison, x 3840 // fold to poison 3841 if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS)) 3842 return PoisonValue::get(RetTy); 3843 3844 // fcmp pred x, undef and fcmp pred undef, x 3845 // fold to true if unordered, false if ordered 3846 if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) { 3847 // Choosing NaN for the undef will always make unordered comparison succeed 3848 // and ordered comparison fail. 3849 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred)); 3850 } 3851 3852 // fcmp x,x -> true/false. Not all compares are foldable. 3853 if (LHS == RHS) { 3854 if (CmpInst::isTrueWhenEqual(Pred)) 3855 return getTrue(RetTy); 3856 if (CmpInst::isFalseWhenEqual(Pred)) 3857 return getFalse(RetTy); 3858 } 3859 3860 // Handle fcmp with constant RHS. 3861 // TODO: Use match with a specific FP value, so these work with vectors with 3862 // undef lanes. 3863 const APFloat *C; 3864 if (match(RHS, m_APFloat(C))) { 3865 // Check whether the constant is an infinity. 3866 if (C->isInfinity()) { 3867 if (C->isNegative()) { 3868 switch (Pred) { 3869 case FCmpInst::FCMP_OLT: 3870 // No value is ordered and less than negative infinity. 3871 return getFalse(RetTy); 3872 case FCmpInst::FCMP_UGE: 3873 // All values are unordered with or at least negative infinity. 3874 return getTrue(RetTy); 3875 default: 3876 break; 3877 } 3878 } else { 3879 switch (Pred) { 3880 case FCmpInst::FCMP_OGT: 3881 // No value is ordered and greater than infinity. 3882 return getFalse(RetTy); 3883 case FCmpInst::FCMP_ULE: 3884 // All values are unordered with and at most infinity. 3885 return getTrue(RetTy); 3886 default: 3887 break; 3888 } 3889 } 3890 3891 // LHS == Inf 3892 if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI)) 3893 return getFalse(RetTy); 3894 // LHS != Inf 3895 if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI)) 3896 return getTrue(RetTy); 3897 // LHS == Inf || LHS == NaN 3898 if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) && 3899 isKnownNeverNaN(LHS, Q.TLI)) 3900 return getFalse(RetTy); 3901 // LHS != Inf && LHS != NaN 3902 if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) && 3903 isKnownNeverNaN(LHS, Q.TLI)) 3904 return getTrue(RetTy); 3905 } 3906 if (C->isNegative() && !C->isNegZero()) { 3907 assert(!C->isNaN() && "Unexpected NaN constant!"); 3908 // TODO: We can catch more cases by using a range check rather than 3909 // relying on CannotBeOrderedLessThanZero. 3910 switch (Pred) { 3911 case FCmpInst::FCMP_UGE: 3912 case FCmpInst::FCMP_UGT: 3913 case FCmpInst::FCMP_UNE: 3914 // (X >= 0) implies (X > C) when (C < 0) 3915 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3916 return getTrue(RetTy); 3917 break; 3918 case FCmpInst::FCMP_OEQ: 3919 case FCmpInst::FCMP_OLE: 3920 case FCmpInst::FCMP_OLT: 3921 // (X >= 0) implies !(X < C) when (C < 0) 3922 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3923 return getFalse(RetTy); 3924 break; 3925 default: 3926 break; 3927 } 3928 } 3929 3930 // Check comparison of [minnum/maxnum with constant] with other constant. 3931 const APFloat *C2; 3932 if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) && 3933 *C2 < *C) || 3934 (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) && 3935 *C2 > *C)) { 3936 bool IsMaxNum = 3937 cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum; 3938 // The ordered relationship and minnum/maxnum guarantee that we do not 3939 // have NaN constants, so ordered/unordered preds are handled the same. 3940 switch (Pred) { 3941 case FCmpInst::FCMP_OEQ: case FCmpInst::FCMP_UEQ: 3942 // minnum(X, LesserC) == C --> false 3943 // maxnum(X, GreaterC) == C --> false 3944 return getFalse(RetTy); 3945 case FCmpInst::FCMP_ONE: case FCmpInst::FCMP_UNE: 3946 // minnum(X, LesserC) != C --> true 3947 // maxnum(X, GreaterC) != C --> true 3948 return getTrue(RetTy); 3949 case FCmpInst::FCMP_OGE: case FCmpInst::FCMP_UGE: 3950 case FCmpInst::FCMP_OGT: case FCmpInst::FCMP_UGT: 3951 // minnum(X, LesserC) >= C --> false 3952 // minnum(X, LesserC) > C --> false 3953 // maxnum(X, GreaterC) >= C --> true 3954 // maxnum(X, GreaterC) > C --> true 3955 return ConstantInt::get(RetTy, IsMaxNum); 3956 case FCmpInst::FCMP_OLE: case FCmpInst::FCMP_ULE: 3957 case FCmpInst::FCMP_OLT: case FCmpInst::FCMP_ULT: 3958 // minnum(X, LesserC) <= C --> true 3959 // minnum(X, LesserC) < C --> true 3960 // maxnum(X, GreaterC) <= C --> false 3961 // maxnum(X, GreaterC) < C --> false 3962 return ConstantInt::get(RetTy, !IsMaxNum); 3963 default: 3964 // TRUE/FALSE/ORD/UNO should be handled before this. 3965 llvm_unreachable("Unexpected fcmp predicate"); 3966 } 3967 } 3968 } 3969 3970 if (match(RHS, m_AnyZeroFP())) { 3971 switch (Pred) { 3972 case FCmpInst::FCMP_OGE: 3973 case FCmpInst::FCMP_ULT: 3974 // Positive or zero X >= 0.0 --> true 3975 // Positive or zero X < 0.0 --> false 3976 if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) && 3977 CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3978 return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy); 3979 break; 3980 case FCmpInst::FCMP_UGE: 3981 case FCmpInst::FCMP_OLT: 3982 // Positive or zero or nan X >= 0.0 --> true 3983 // Positive or zero or nan X < 0.0 --> false 3984 if (CannotBeOrderedLessThanZero(LHS, Q.TLI)) 3985 return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy); 3986 break; 3987 default: 3988 break; 3989 } 3990 } 3991 3992 // If the comparison is with the result of a select instruction, check whether 3993 // comparing with either branch of the select always yields the same value. 3994 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3995 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 3996 return V; 3997 3998 // If the comparison is with the result of a phi instruction, check whether 3999 // doing the compare with each incoming phi value yields a common result. 4000 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 4001 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 4002 return V; 4003 4004 return nullptr; 4005 } 4006 4007 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 4008 FastMathFlags FMF, const SimplifyQuery &Q) { 4009 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit); 4010 } 4011 4012 static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 4013 const SimplifyQuery &Q, 4014 bool AllowRefinement, 4015 unsigned MaxRecurse) { 4016 assert(!Op->getType()->isVectorTy() && "This is not safe for vectors"); 4017 4018 // Trivial replacement. 4019 if (V == Op) 4020 return RepOp; 4021 4022 // We cannot replace a constant, and shouldn't even try. 4023 if (isa<Constant>(Op)) 4024 return nullptr; 4025 4026 auto *I = dyn_cast<Instruction>(V); 4027 if (!I || !is_contained(I->operands(), Op)) 4028 return nullptr; 4029 4030 // Replace Op with RepOp in instruction operands. 4031 SmallVector<Value *, 8> NewOps(I->getNumOperands()); 4032 transform(I->operands(), NewOps.begin(), 4033 [&](Value *V) { return V == Op ? RepOp : V; }); 4034 4035 if (!AllowRefinement) { 4036 // General InstSimplify functions may refine the result, e.g. by returning 4037 // a constant for a potentially poison value. To avoid this, implement only 4038 // a few non-refining but profitable transforms here. 4039 4040 if (auto *BO = dyn_cast<BinaryOperator>(I)) { 4041 unsigned Opcode = BO->getOpcode(); 4042 // id op x -> x, x op id -> x 4043 if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType())) 4044 return NewOps[1]; 4045 if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(), 4046 /* RHS */ true)) 4047 return NewOps[0]; 4048 4049 // x & x -> x, x | x -> x 4050 if ((Opcode == Instruction::And || Opcode == Instruction::Or) && 4051 NewOps[0] == NewOps[1]) 4052 return NewOps[0]; 4053 } 4054 4055 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) { 4056 // getelementptr x, 0 -> x 4057 if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) && 4058 !GEP->isInBounds()) 4059 return NewOps[0]; 4060 } 4061 } else if (MaxRecurse) { 4062 // The simplification queries below may return the original value. Consider: 4063 // %div = udiv i32 %arg, %arg2 4064 // %mul = mul nsw i32 %div, %arg2 4065 // %cmp = icmp eq i32 %mul, %arg 4066 // %sel = select i1 %cmp, i32 %div, i32 undef 4067 // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which 4068 // simplifies back to %arg. This can only happen because %mul does not 4069 // dominate %div. To ensure a consistent return value contract, we make sure 4070 // that this case returns nullptr as well. 4071 auto PreventSelfSimplify = [V](Value *Simplified) { 4072 return Simplified != V ? Simplified : nullptr; 4073 }; 4074 4075 if (auto *B = dyn_cast<BinaryOperator>(I)) 4076 return PreventSelfSimplify(SimplifyBinOp(B->getOpcode(), NewOps[0], 4077 NewOps[1], Q, MaxRecurse - 1)); 4078 4079 if (CmpInst *C = dyn_cast<CmpInst>(I)) 4080 return PreventSelfSimplify(SimplifyCmpInst(C->getPredicate(), NewOps[0], 4081 NewOps[1], Q, MaxRecurse - 1)); 4082 4083 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) 4084 return PreventSelfSimplify(SimplifyGEPInst( 4085 GEP->getSourceElementType(), NewOps[0], makeArrayRef(NewOps).slice(1), 4086 GEP->isInBounds(), Q, MaxRecurse - 1)); 4087 4088 if (isa<SelectInst>(I)) 4089 return PreventSelfSimplify( 4090 SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q, 4091 MaxRecurse - 1)); 4092 // TODO: We could hand off more cases to instsimplify here. 4093 } 4094 4095 // If all operands are constant after substituting Op for RepOp then we can 4096 // constant fold the instruction. 4097 SmallVector<Constant *, 8> ConstOps; 4098 for (Value *NewOp : NewOps) { 4099 if (Constant *ConstOp = dyn_cast<Constant>(NewOp)) 4100 ConstOps.push_back(ConstOp); 4101 else 4102 return nullptr; 4103 } 4104 4105 // Consider: 4106 // %cmp = icmp eq i32 %x, 2147483647 4107 // %add = add nsw i32 %x, 1 4108 // %sel = select i1 %cmp, i32 -2147483648, i32 %add 4109 // 4110 // We can't replace %sel with %add unless we strip away the flags (which 4111 // will be done in InstCombine). 4112 // TODO: This may be unsound, because it only catches some forms of 4113 // refinement. 4114 if (!AllowRefinement && canCreatePoison(cast<Operator>(I))) 4115 return nullptr; 4116 4117 if (CmpInst *C = dyn_cast<CmpInst>(I)) 4118 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0], 4119 ConstOps[1], Q.DL, Q.TLI); 4120 4121 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 4122 if (!LI->isVolatile()) 4123 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL); 4124 4125 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI); 4126 } 4127 4128 Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp, 4129 const SimplifyQuery &Q, 4130 bool AllowRefinement) { 4131 return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement, 4132 RecursionLimit); 4133 } 4134 4135 /// Try to simplify a select instruction when its condition operand is an 4136 /// integer comparison where one operand of the compare is a constant. 4137 static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X, 4138 const APInt *Y, bool TrueWhenUnset) { 4139 const APInt *C; 4140 4141 // (X & Y) == 0 ? X & ~Y : X --> X 4142 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y 4143 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) && 4144 *Y == ~*C) 4145 return TrueWhenUnset ? FalseVal : TrueVal; 4146 4147 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y 4148 // (X & Y) != 0 ? X : X & ~Y --> X 4149 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) && 4150 *Y == ~*C) 4151 return TrueWhenUnset ? FalseVal : TrueVal; 4152 4153 if (Y->isPowerOf2()) { 4154 // (X & Y) == 0 ? X | Y : X --> X | Y 4155 // (X & Y) != 0 ? X | Y : X --> X 4156 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) && 4157 *Y == *C) 4158 return TrueWhenUnset ? TrueVal : FalseVal; 4159 4160 // (X & Y) == 0 ? X : X | Y --> X 4161 // (X & Y) != 0 ? X : X | Y --> X | Y 4162 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) && 4163 *Y == *C) 4164 return TrueWhenUnset ? TrueVal : FalseVal; 4165 } 4166 4167 return nullptr; 4168 } 4169 4170 /// An alternative way to test if a bit is set or not uses sgt/slt instead of 4171 /// eq/ne. 4172 static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS, 4173 ICmpInst::Predicate Pred, 4174 Value *TrueVal, Value *FalseVal) { 4175 Value *X; 4176 APInt Mask; 4177 if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask)) 4178 return nullptr; 4179 4180 return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask, 4181 Pred == ICmpInst::ICMP_EQ); 4182 } 4183 4184 /// Try to simplify a select instruction when its condition operand is an 4185 /// integer comparison. 4186 static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal, 4187 Value *FalseVal, const SimplifyQuery &Q, 4188 unsigned MaxRecurse) { 4189 ICmpInst::Predicate Pred; 4190 Value *CmpLHS, *CmpRHS; 4191 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS)))) 4192 return nullptr; 4193 4194 // Canonicalize ne to eq predicate. 4195 if (Pred == ICmpInst::ICMP_NE) { 4196 Pred = ICmpInst::ICMP_EQ; 4197 std::swap(TrueVal, FalseVal); 4198 } 4199 4200 // Check for integer min/max with a limit constant: 4201 // X > MIN_INT ? X : MIN_INT --> X 4202 // X < MAX_INT ? X : MAX_INT --> X 4203 if (TrueVal->getType()->isIntOrIntVectorTy()) { 4204 Value *X, *Y; 4205 SelectPatternFlavor SPF = 4206 matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal, 4207 X, Y).Flavor; 4208 if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) { 4209 APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF), 4210 X->getType()->getScalarSizeInBits()); 4211 if (match(Y, m_SpecificInt(LimitC))) 4212 return X; 4213 } 4214 } 4215 4216 if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) { 4217 Value *X; 4218 const APInt *Y; 4219 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y)))) 4220 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y, 4221 /*TrueWhenUnset=*/true)) 4222 return V; 4223 4224 // Test for a bogus zero-shift-guard-op around funnel-shift or rotate. 4225 Value *ShAmt; 4226 auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)), 4227 m_FShr(m_Value(), m_Value(X), m_Value(ShAmt))); 4228 // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X 4229 // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X 4230 if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt) 4231 return X; 4232 4233 // Test for a zero-shift-guard-op around rotates. These are used to 4234 // avoid UB from oversized shifts in raw IR rotate patterns, but the 4235 // intrinsics do not have that problem. 4236 // We do not allow this transform for the general funnel shift case because 4237 // that would not preserve the poison safety of the original code. 4238 auto isRotate = 4239 m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)), 4240 m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt))); 4241 // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt) 4242 // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt) 4243 if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt && 4244 Pred == ICmpInst::ICMP_EQ) 4245 return FalseVal; 4246 4247 // X == 0 ? abs(X) : -abs(X) --> -abs(X) 4248 // X == 0 ? -abs(X) : abs(X) --> abs(X) 4249 if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) && 4250 match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))) 4251 return FalseVal; 4252 if (match(TrueVal, 4253 m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) && 4254 match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) 4255 return FalseVal; 4256 } 4257 4258 // Check for other compares that behave like bit test. 4259 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, 4260 TrueVal, FalseVal)) 4261 return V; 4262 4263 // If we have a scalar equality comparison, then we know the value in one of 4264 // the arms of the select. See if substituting this value into the arm and 4265 // simplifying the result yields the same value as the other arm. 4266 // Note that the equivalence/replacement opportunity does not hold for vectors 4267 // because each element of a vector select is chosen independently. 4268 if (Pred == ICmpInst::ICMP_EQ && !CondVal->getType()->isVectorTy()) { 4269 if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, 4270 /* AllowRefinement */ false, MaxRecurse) == 4271 TrueVal || 4272 simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, 4273 /* AllowRefinement */ false, MaxRecurse) == 4274 TrueVal) 4275 return FalseVal; 4276 if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, 4277 /* AllowRefinement */ true, MaxRecurse) == 4278 FalseVal || 4279 simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, 4280 /* AllowRefinement */ true, MaxRecurse) == 4281 FalseVal) 4282 return FalseVal; 4283 } 4284 4285 return nullptr; 4286 } 4287 4288 /// Try to simplify a select instruction when its condition operand is a 4289 /// floating-point comparison. 4290 static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F, 4291 const SimplifyQuery &Q) { 4292 FCmpInst::Predicate Pred; 4293 if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) && 4294 !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T)))) 4295 return nullptr; 4296 4297 // This transform is safe if we do not have (do not care about) -0.0 or if 4298 // at least one operand is known to not be -0.0. Otherwise, the select can 4299 // change the sign of a zero operand. 4300 bool HasNoSignedZeros = Q.CxtI && isa<FPMathOperator>(Q.CxtI) && 4301 Q.CxtI->hasNoSignedZeros(); 4302 const APFloat *C; 4303 if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) || 4304 (match(F, m_APFloat(C)) && C->isNonZero())) { 4305 // (T == F) ? T : F --> F 4306 // (F == T) ? T : F --> F 4307 if (Pred == FCmpInst::FCMP_OEQ) 4308 return F; 4309 4310 // (T != F) ? T : F --> T 4311 // (F != T) ? T : F --> T 4312 if (Pred == FCmpInst::FCMP_UNE) 4313 return T; 4314 } 4315 4316 return nullptr; 4317 } 4318 4319 /// Given operands for a SelectInst, see if we can fold the result. 4320 /// If not, this returns null. 4321 static Value *SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 4322 const SimplifyQuery &Q, unsigned MaxRecurse) { 4323 if (auto *CondC = dyn_cast<Constant>(Cond)) { 4324 if (auto *TrueC = dyn_cast<Constant>(TrueVal)) 4325 if (auto *FalseC = dyn_cast<Constant>(FalseVal)) 4326 return ConstantFoldSelectInstruction(CondC, TrueC, FalseC); 4327 4328 // select poison, X, Y -> poison 4329 if (isa<PoisonValue>(CondC)) 4330 return PoisonValue::get(TrueVal->getType()); 4331 4332 // select undef, X, Y -> X or Y 4333 if (Q.isUndefValue(CondC)) 4334 return isa<Constant>(FalseVal) ? FalseVal : TrueVal; 4335 4336 // select true, X, Y --> X 4337 // select false, X, Y --> Y 4338 // For vectors, allow undef/poison elements in the condition to match the 4339 // defined elements, so we can eliminate the select. 4340 if (match(CondC, m_One())) 4341 return TrueVal; 4342 if (match(CondC, m_Zero())) 4343 return FalseVal; 4344 } 4345 4346 assert(Cond->getType()->isIntOrIntVectorTy(1) && 4347 "Select must have bool or bool vector condition"); 4348 assert(TrueVal->getType() == FalseVal->getType() && 4349 "Select must have same types for true/false ops"); 4350 4351 if (Cond->getType() == TrueVal->getType()) { 4352 // select i1 Cond, i1 true, i1 false --> i1 Cond 4353 if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt())) 4354 return Cond; 4355 4356 // (X || Y) && (X || !Y) --> X (commuted 8 ways) 4357 Value *X, *Y; 4358 if (match(FalseVal, m_ZeroInt())) { 4359 if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) && 4360 match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y)))) 4361 return X; 4362 if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) && 4363 match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y)))) 4364 return X; 4365 } 4366 } 4367 4368 // select ?, X, X -> X 4369 if (TrueVal == FalseVal) 4370 return TrueVal; 4371 4372 // If the true or false value is poison, we can fold to the other value. 4373 // If the true or false value is undef, we can fold to the other value as 4374 // long as the other value isn't poison. 4375 // select ?, poison, X -> X 4376 // select ?, undef, X -> X 4377 if (isa<PoisonValue>(TrueVal) || 4378 (Q.isUndefValue(TrueVal) && 4379 isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT))) 4380 return FalseVal; 4381 // select ?, X, poison -> X 4382 // select ?, X, undef -> X 4383 if (isa<PoisonValue>(FalseVal) || 4384 (Q.isUndefValue(FalseVal) && 4385 isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT))) 4386 return TrueVal; 4387 4388 // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC'' 4389 Constant *TrueC, *FalseC; 4390 if (isa<FixedVectorType>(TrueVal->getType()) && 4391 match(TrueVal, m_Constant(TrueC)) && 4392 match(FalseVal, m_Constant(FalseC))) { 4393 unsigned NumElts = 4394 cast<FixedVectorType>(TrueC->getType())->getNumElements(); 4395 SmallVector<Constant *, 16> NewC; 4396 for (unsigned i = 0; i != NumElts; ++i) { 4397 // Bail out on incomplete vector constants. 4398 Constant *TEltC = TrueC->getAggregateElement(i); 4399 Constant *FEltC = FalseC->getAggregateElement(i); 4400 if (!TEltC || !FEltC) 4401 break; 4402 4403 // If the elements match (undef or not), that value is the result. If only 4404 // one element is undef, choose the defined element as the safe result. 4405 if (TEltC == FEltC) 4406 NewC.push_back(TEltC); 4407 else if (isa<PoisonValue>(TEltC) || 4408 (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC))) 4409 NewC.push_back(FEltC); 4410 else if (isa<PoisonValue>(FEltC) || 4411 (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC))) 4412 NewC.push_back(TEltC); 4413 else 4414 break; 4415 } 4416 if (NewC.size() == NumElts) 4417 return ConstantVector::get(NewC); 4418 } 4419 4420 if (Value *V = 4421 simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse)) 4422 return V; 4423 4424 if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q)) 4425 return V; 4426 4427 if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal)) 4428 return V; 4429 4430 Optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL); 4431 if (Imp) 4432 return *Imp ? TrueVal : FalseVal; 4433 4434 return nullptr; 4435 } 4436 4437 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 4438 const SimplifyQuery &Q) { 4439 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit); 4440 } 4441 4442 /// Given operands for an GetElementPtrInst, see if we can fold the result. 4443 /// If not, this returns null. 4444 static Value *SimplifyGEPInst(Type *SrcTy, Value *Ptr, 4445 ArrayRef<Value *> Indices, bool InBounds, 4446 const SimplifyQuery &Q, unsigned) { 4447 // The type of the GEP pointer operand. 4448 unsigned AS = 4449 cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace(); 4450 4451 // getelementptr P -> P. 4452 if (Indices.empty()) 4453 return Ptr; 4454 4455 // Compute the (pointer) type returned by the GEP instruction. 4456 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices); 4457 Type *GEPTy = PointerType::get(LastType, AS); 4458 if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType())) 4459 GEPTy = VectorType::get(GEPTy, VT->getElementCount()); 4460 else { 4461 for (Value *Op : Indices) { 4462 // If one of the operands is a vector, the result type is a vector of 4463 // pointers. All vector operands must have the same number of elements. 4464 if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) { 4465 GEPTy = VectorType::get(GEPTy, VT->getElementCount()); 4466 break; 4467 } 4468 } 4469 } 4470 4471 // For opaque pointers an all-zero GEP is a no-op. For typed pointers, 4472 // it may be equivalent to a bitcast. 4473 if (Ptr->getType()->isOpaquePointerTy() && 4474 all_of(Indices, [](const auto *V) { return match(V, m_Zero()); })) 4475 return Ptr; 4476 4477 // getelementptr poison, idx -> poison 4478 // getelementptr baseptr, poison -> poison 4479 if (isa<PoisonValue>(Ptr) || 4480 any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); })) 4481 return PoisonValue::get(GEPTy); 4482 4483 if (Q.isUndefValue(Ptr)) 4484 // If inbounds, we can choose an out-of-bounds pointer as a base pointer. 4485 return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy); 4486 4487 bool IsScalableVec = 4488 isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) { 4489 return isa<ScalableVectorType>(V->getType()); 4490 }); 4491 4492 if (Indices.size() == 1) { 4493 // getelementptr P, 0 -> P. 4494 if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy) 4495 return Ptr; 4496 4497 Type *Ty = SrcTy; 4498 if (!IsScalableVec && Ty->isSized()) { 4499 Value *P; 4500 uint64_t C; 4501 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty); 4502 // getelementptr P, N -> P if P points to a type of zero size. 4503 if (TyAllocSize == 0 && Ptr->getType() == GEPTy) 4504 return Ptr; 4505 4506 // The following transforms are only safe if the ptrtoint cast 4507 // doesn't truncate the pointers. 4508 if (Indices[0]->getType()->getScalarSizeInBits() == 4509 Q.DL.getPointerSizeInBits(AS)) { 4510 auto CanSimplify = [GEPTy, &P, Ptr]() -> bool { 4511 return P->getType() == GEPTy && 4512 getUnderlyingObject(P) == getUnderlyingObject(Ptr); 4513 }; 4514 // getelementptr V, (sub P, V) -> P if P points to a type of size 1. 4515 if (TyAllocSize == 1 && 4516 match(Indices[0], 4517 m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) && 4518 CanSimplify()) 4519 return P; 4520 4521 // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of 4522 // size 1 << C. 4523 if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)), 4524 m_PtrToInt(m_Specific(Ptr))), 4525 m_ConstantInt(C))) && 4526 TyAllocSize == 1ULL << C && CanSimplify()) 4527 return P; 4528 4529 // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of 4530 // size C. 4531 if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)), 4532 m_PtrToInt(m_Specific(Ptr))), 4533 m_SpecificInt(TyAllocSize))) && 4534 CanSimplify()) 4535 return P; 4536 } 4537 } 4538 } 4539 4540 if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 && 4541 all_of(Indices.drop_back(1), 4542 [](Value *Idx) { return match(Idx, m_Zero()); })) { 4543 unsigned IdxWidth = 4544 Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace()); 4545 if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) { 4546 APInt BasePtrOffset(IdxWidth, 0); 4547 Value *StrippedBasePtr = 4548 Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset); 4549 4550 // Avoid creating inttoptr of zero here: While LLVMs treatment of 4551 // inttoptr is generally conservative, this particular case is folded to 4552 // a null pointer, which will have incorrect provenance. 4553 4554 // gep (gep V, C), (sub 0, V) -> C 4555 if (match(Indices.back(), 4556 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) && 4557 !BasePtrOffset.isZero()) { 4558 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset); 4559 return ConstantExpr::getIntToPtr(CI, GEPTy); 4560 } 4561 // gep (gep V, C), (xor V, -1) -> C-1 4562 if (match(Indices.back(), 4563 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) && 4564 !BasePtrOffset.isOne()) { 4565 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1); 4566 return ConstantExpr::getIntToPtr(CI, GEPTy); 4567 } 4568 } 4569 } 4570 4571 // Check to see if this is constant foldable. 4572 if (!isa<Constant>(Ptr) || 4573 !all_of(Indices, [](Value *V) { return isa<Constant>(V); })) 4574 return nullptr; 4575 4576 auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices, 4577 InBounds); 4578 return ConstantFoldConstant(CE, Q.DL); 4579 } 4580 4581 Value *llvm::SimplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices, 4582 bool InBounds, const SimplifyQuery &Q) { 4583 return ::SimplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit); 4584 } 4585 4586 /// Given operands for an InsertValueInst, see if we can fold the result. 4587 /// If not, this returns null. 4588 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, 4589 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q, 4590 unsigned) { 4591 if (Constant *CAgg = dyn_cast<Constant>(Agg)) 4592 if (Constant *CVal = dyn_cast<Constant>(Val)) 4593 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); 4594 4595 // insertvalue x, undef, n -> x 4596 if (Q.isUndefValue(Val)) 4597 return Agg; 4598 4599 // insertvalue x, (extractvalue y, n), n 4600 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) 4601 if (EV->getAggregateOperand()->getType() == Agg->getType() && 4602 EV->getIndices() == Idxs) { 4603 // insertvalue undef, (extractvalue y, n), n -> y 4604 if (Q.isUndefValue(Agg)) 4605 return EV->getAggregateOperand(); 4606 4607 // insertvalue y, (extractvalue y, n), n -> y 4608 if (Agg == EV->getAggregateOperand()) 4609 return Agg; 4610 } 4611 4612 return nullptr; 4613 } 4614 4615 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, 4616 ArrayRef<unsigned> Idxs, 4617 const SimplifyQuery &Q) { 4618 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit); 4619 } 4620 4621 Value *llvm::SimplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx, 4622 const SimplifyQuery &Q) { 4623 // Try to constant fold. 4624 auto *VecC = dyn_cast<Constant>(Vec); 4625 auto *ValC = dyn_cast<Constant>(Val); 4626 auto *IdxC = dyn_cast<Constant>(Idx); 4627 if (VecC && ValC && IdxC) 4628 return ConstantExpr::getInsertElement(VecC, ValC, IdxC); 4629 4630 // For fixed-length vector, fold into poison if index is out of bounds. 4631 if (auto *CI = dyn_cast<ConstantInt>(Idx)) { 4632 if (isa<FixedVectorType>(Vec->getType()) && 4633 CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements())) 4634 return PoisonValue::get(Vec->getType()); 4635 } 4636 4637 // If index is undef, it might be out of bounds (see above case) 4638 if (Q.isUndefValue(Idx)) 4639 return PoisonValue::get(Vec->getType()); 4640 4641 // If the scalar is poison, or it is undef and there is no risk of 4642 // propagating poison from the vector value, simplify to the vector value. 4643 if (isa<PoisonValue>(Val) || 4644 (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec))) 4645 return Vec; 4646 4647 // If we are extracting a value from a vector, then inserting it into the same 4648 // place, that's the input vector: 4649 // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec 4650 if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx)))) 4651 return Vec; 4652 4653 return nullptr; 4654 } 4655 4656 /// Given operands for an ExtractValueInst, see if we can fold the result. 4657 /// If not, this returns null. 4658 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 4659 const SimplifyQuery &, unsigned) { 4660 if (auto *CAgg = dyn_cast<Constant>(Agg)) 4661 return ConstantFoldExtractValueInstruction(CAgg, Idxs); 4662 4663 // extractvalue x, (insertvalue y, elt, n), n -> elt 4664 unsigned NumIdxs = Idxs.size(); 4665 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr; 4666 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) { 4667 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices(); 4668 unsigned NumInsertValueIdxs = InsertValueIdxs.size(); 4669 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs); 4670 if (InsertValueIdxs.slice(0, NumCommonIdxs) == 4671 Idxs.slice(0, NumCommonIdxs)) { 4672 if (NumIdxs == NumInsertValueIdxs) 4673 return IVI->getInsertedValueOperand(); 4674 break; 4675 } 4676 } 4677 4678 return nullptr; 4679 } 4680 4681 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs, 4682 const SimplifyQuery &Q) { 4683 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit); 4684 } 4685 4686 /// Given operands for an ExtractElementInst, see if we can fold the result. 4687 /// If not, this returns null. 4688 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, 4689 const SimplifyQuery &Q, unsigned) { 4690 auto *VecVTy = cast<VectorType>(Vec->getType()); 4691 if (auto *CVec = dyn_cast<Constant>(Vec)) { 4692 if (auto *CIdx = dyn_cast<Constant>(Idx)) 4693 return ConstantExpr::getExtractElement(CVec, CIdx); 4694 4695 if (Q.isUndefValue(Vec)) 4696 return UndefValue::get(VecVTy->getElementType()); 4697 } 4698 4699 // An undef extract index can be arbitrarily chosen to be an out-of-range 4700 // index value, which would result in the instruction being poison. 4701 if (Q.isUndefValue(Idx)) 4702 return PoisonValue::get(VecVTy->getElementType()); 4703 4704 // If extracting a specified index from the vector, see if we can recursively 4705 // find a previously computed scalar that was inserted into the vector. 4706 if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) { 4707 // For fixed-length vector, fold into undef if index is out of bounds. 4708 unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue(); 4709 if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts)) 4710 return PoisonValue::get(VecVTy->getElementType()); 4711 // Handle case where an element is extracted from a splat. 4712 if (IdxC->getValue().ult(MinNumElts)) 4713 if (auto *Splat = getSplatValue(Vec)) 4714 return Splat; 4715 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue())) 4716 return Elt; 4717 } else { 4718 // The index is not relevant if our vector is a splat. 4719 if (Value *Splat = getSplatValue(Vec)) 4720 return Splat; 4721 } 4722 return nullptr; 4723 } 4724 4725 Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx, 4726 const SimplifyQuery &Q) { 4727 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit); 4728 } 4729 4730 /// See if we can fold the given phi. If not, returns null. 4731 static Value *SimplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues, 4732 const SimplifyQuery &Q) { 4733 // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE 4734 // here, because the PHI we may succeed simplifying to was not 4735 // def-reachable from the original PHI! 4736 4737 // If all of the PHI's incoming values are the same then replace the PHI node 4738 // with the common value. 4739 Value *CommonValue = nullptr; 4740 bool HasUndefInput = false; 4741 for (Value *Incoming : IncomingValues) { 4742 // If the incoming value is the phi node itself, it can safely be skipped. 4743 if (Incoming == PN) continue; 4744 if (Q.isUndefValue(Incoming)) { 4745 // Remember that we saw an undef value, but otherwise ignore them. 4746 HasUndefInput = true; 4747 continue; 4748 } 4749 if (CommonValue && Incoming != CommonValue) 4750 return nullptr; // Not the same, bail out. 4751 CommonValue = Incoming; 4752 } 4753 4754 // If CommonValue is null then all of the incoming values were either undef or 4755 // equal to the phi node itself. 4756 if (!CommonValue) 4757 return UndefValue::get(PN->getType()); 4758 4759 // If we have a PHI node like phi(X, undef, X), where X is defined by some 4760 // instruction, we cannot return X as the result of the PHI node unless it 4761 // dominates the PHI block. 4762 if (HasUndefInput) 4763 return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr; 4764 4765 return CommonValue; 4766 } 4767 4768 static Value *SimplifyCastInst(unsigned CastOpc, Value *Op, 4769 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) { 4770 if (auto *C = dyn_cast<Constant>(Op)) 4771 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL); 4772 4773 if (auto *CI = dyn_cast<CastInst>(Op)) { 4774 auto *Src = CI->getOperand(0); 4775 Type *SrcTy = Src->getType(); 4776 Type *MidTy = CI->getType(); 4777 Type *DstTy = Ty; 4778 if (Src->getType() == Ty) { 4779 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode()); 4780 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc); 4781 Type *SrcIntPtrTy = 4782 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr; 4783 Type *MidIntPtrTy = 4784 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr; 4785 Type *DstIntPtrTy = 4786 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr; 4787 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy, 4788 SrcIntPtrTy, MidIntPtrTy, 4789 DstIntPtrTy) == Instruction::BitCast) 4790 return Src; 4791 } 4792 } 4793 4794 // bitcast x -> x 4795 if (CastOpc == Instruction::BitCast) 4796 if (Op->getType() == Ty) 4797 return Op; 4798 4799 return nullptr; 4800 } 4801 4802 Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, 4803 const SimplifyQuery &Q) { 4804 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit); 4805 } 4806 4807 /// For the given destination element of a shuffle, peek through shuffles to 4808 /// match a root vector source operand that contains that element in the same 4809 /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s). 4810 static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1, 4811 int MaskVal, Value *RootVec, 4812 unsigned MaxRecurse) { 4813 if (!MaxRecurse--) 4814 return nullptr; 4815 4816 // Bail out if any mask value is undefined. That kind of shuffle may be 4817 // simplified further based on demanded bits or other folds. 4818 if (MaskVal == -1) 4819 return nullptr; 4820 4821 // The mask value chooses which source operand we need to look at next. 4822 int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements(); 4823 int RootElt = MaskVal; 4824 Value *SourceOp = Op0; 4825 if (MaskVal >= InVecNumElts) { 4826 RootElt = MaskVal - InVecNumElts; 4827 SourceOp = Op1; 4828 } 4829 4830 // If the source operand is a shuffle itself, look through it to find the 4831 // matching root vector. 4832 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) { 4833 return foldIdentityShuffles( 4834 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1), 4835 SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse); 4836 } 4837 4838 // TODO: Look through bitcasts? What if the bitcast changes the vector element 4839 // size? 4840 4841 // The source operand is not a shuffle. Initialize the root vector value for 4842 // this shuffle if that has not been done yet. 4843 if (!RootVec) 4844 RootVec = SourceOp; 4845 4846 // Give up as soon as a source operand does not match the existing root value. 4847 if (RootVec != SourceOp) 4848 return nullptr; 4849 4850 // The element must be coming from the same lane in the source vector 4851 // (although it may have crossed lanes in intermediate shuffles). 4852 if (RootElt != DestElt) 4853 return nullptr; 4854 4855 return RootVec; 4856 } 4857 4858 static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, 4859 ArrayRef<int> Mask, Type *RetTy, 4860 const SimplifyQuery &Q, 4861 unsigned MaxRecurse) { 4862 if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; })) 4863 return UndefValue::get(RetTy); 4864 4865 auto *InVecTy = cast<VectorType>(Op0->getType()); 4866 unsigned MaskNumElts = Mask.size(); 4867 ElementCount InVecEltCount = InVecTy->getElementCount(); 4868 4869 bool Scalable = InVecEltCount.isScalable(); 4870 4871 SmallVector<int, 32> Indices; 4872 Indices.assign(Mask.begin(), Mask.end()); 4873 4874 // Canonicalization: If mask does not select elements from an input vector, 4875 // replace that input vector with poison. 4876 if (!Scalable) { 4877 bool MaskSelects0 = false, MaskSelects1 = false; 4878 unsigned InVecNumElts = InVecEltCount.getKnownMinValue(); 4879 for (unsigned i = 0; i != MaskNumElts; ++i) { 4880 if (Indices[i] == -1) 4881 continue; 4882 if ((unsigned)Indices[i] < InVecNumElts) 4883 MaskSelects0 = true; 4884 else 4885 MaskSelects1 = true; 4886 } 4887 if (!MaskSelects0) 4888 Op0 = PoisonValue::get(InVecTy); 4889 if (!MaskSelects1) 4890 Op1 = PoisonValue::get(InVecTy); 4891 } 4892 4893 auto *Op0Const = dyn_cast<Constant>(Op0); 4894 auto *Op1Const = dyn_cast<Constant>(Op1); 4895 4896 // If all operands are constant, constant fold the shuffle. This 4897 // transformation depends on the value of the mask which is not known at 4898 // compile time for scalable vectors 4899 if (Op0Const && Op1Const) 4900 return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask); 4901 4902 // Canonicalization: if only one input vector is constant, it shall be the 4903 // second one. This transformation depends on the value of the mask which 4904 // is not known at compile time for scalable vectors 4905 if (!Scalable && Op0Const && !Op1Const) { 4906 std::swap(Op0, Op1); 4907 ShuffleVectorInst::commuteShuffleMask(Indices, 4908 InVecEltCount.getKnownMinValue()); 4909 } 4910 4911 // A splat of an inserted scalar constant becomes a vector constant: 4912 // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...> 4913 // NOTE: We may have commuted above, so analyze the updated Indices, not the 4914 // original mask constant. 4915 // NOTE: This transformation depends on the value of the mask which is not 4916 // known at compile time for scalable vectors 4917 Constant *C; 4918 ConstantInt *IndexC; 4919 if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C), 4920 m_ConstantInt(IndexC)))) { 4921 // Match a splat shuffle mask of the insert index allowing undef elements. 4922 int InsertIndex = IndexC->getZExtValue(); 4923 if (all_of(Indices, [InsertIndex](int MaskElt) { 4924 return MaskElt == InsertIndex || MaskElt == -1; 4925 })) { 4926 assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat"); 4927 4928 // Shuffle mask undefs become undefined constant result elements. 4929 SmallVector<Constant *, 16> VecC(MaskNumElts, C); 4930 for (unsigned i = 0; i != MaskNumElts; ++i) 4931 if (Indices[i] == -1) 4932 VecC[i] = UndefValue::get(C->getType()); 4933 return ConstantVector::get(VecC); 4934 } 4935 } 4936 4937 // A shuffle of a splat is always the splat itself. Legal if the shuffle's 4938 // value type is same as the input vectors' type. 4939 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0)) 4940 if (Q.isUndefValue(Op1) && RetTy == InVecTy && 4941 is_splat(OpShuf->getShuffleMask())) 4942 return Op0; 4943 4944 // All remaining transformation depend on the value of the mask, which is 4945 // not known at compile time for scalable vectors. 4946 if (Scalable) 4947 return nullptr; 4948 4949 // Don't fold a shuffle with undef mask elements. This may get folded in a 4950 // better way using demanded bits or other analysis. 4951 // TODO: Should we allow this? 4952 if (is_contained(Indices, -1)) 4953 return nullptr; 4954 4955 // Check if every element of this shuffle can be mapped back to the 4956 // corresponding element of a single root vector. If so, we don't need this 4957 // shuffle. This handles simple identity shuffles as well as chains of 4958 // shuffles that may widen/narrow and/or move elements across lanes and back. 4959 Value *RootVec = nullptr; 4960 for (unsigned i = 0; i != MaskNumElts; ++i) { 4961 // Note that recursion is limited for each vector element, so if any element 4962 // exceeds the limit, this will fail to simplify. 4963 RootVec = 4964 foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse); 4965 4966 // We can't replace a widening/narrowing shuffle with one of its operands. 4967 if (!RootVec || RootVec->getType() != RetTy) 4968 return nullptr; 4969 } 4970 return RootVec; 4971 } 4972 4973 /// Given operands for a ShuffleVectorInst, fold the result or return null. 4974 Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, 4975 ArrayRef<int> Mask, Type *RetTy, 4976 const SimplifyQuery &Q) { 4977 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit); 4978 } 4979 4980 static Constant *foldConstant(Instruction::UnaryOps Opcode, 4981 Value *&Op, const SimplifyQuery &Q) { 4982 if (auto *C = dyn_cast<Constant>(Op)) 4983 return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL); 4984 return nullptr; 4985 } 4986 4987 /// Given the operand for an FNeg, see if we can fold the result. If not, this 4988 /// returns null. 4989 static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF, 4990 const SimplifyQuery &Q, unsigned MaxRecurse) { 4991 if (Constant *C = foldConstant(Instruction::FNeg, Op, Q)) 4992 return C; 4993 4994 Value *X; 4995 // fneg (fneg X) ==> X 4996 if (match(Op, m_FNeg(m_Value(X)))) 4997 return X; 4998 4999 return nullptr; 5000 } 5001 5002 Value *llvm::SimplifyFNegInst(Value *Op, FastMathFlags FMF, 5003 const SimplifyQuery &Q) { 5004 return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit); 5005 } 5006 5007 static Constant *propagateNaN(Constant *In) { 5008 // If the input is a vector with undef elements, just return a default NaN. 5009 if (!In->isNaN()) 5010 return ConstantFP::getNaN(In->getType()); 5011 5012 // Propagate the existing NaN constant when possible. 5013 // TODO: Should we quiet a signaling NaN? 5014 return In; 5015 } 5016 5017 /// Perform folds that are common to any floating-point operation. This implies 5018 /// transforms based on poison/undef/NaN because the operation itself makes no 5019 /// difference to the result. 5020 static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF, 5021 const SimplifyQuery &Q, 5022 fp::ExceptionBehavior ExBehavior, 5023 RoundingMode Rounding) { 5024 // Poison is independent of anything else. It always propagates from an 5025 // operand to a math result. 5026 if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); })) 5027 return PoisonValue::get(Ops[0]->getType()); 5028 5029 for (Value *V : Ops) { 5030 bool IsNan = match(V, m_NaN()); 5031 bool IsInf = match(V, m_Inf()); 5032 bool IsUndef = Q.isUndefValue(V); 5033 5034 // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand 5035 // (an undef operand can be chosen to be Nan/Inf), then the result of 5036 // this operation is poison. 5037 if (FMF.noNaNs() && (IsNan || IsUndef)) 5038 return PoisonValue::get(V->getType()); 5039 if (FMF.noInfs() && (IsInf || IsUndef)) 5040 return PoisonValue::get(V->getType()); 5041 5042 if (isDefaultFPEnvironment(ExBehavior, Rounding)) { 5043 if (IsUndef || IsNan) 5044 return propagateNaN(cast<Constant>(V)); 5045 } else if (ExBehavior != fp::ebStrict) { 5046 if (IsNan) 5047 return propagateNaN(cast<Constant>(V)); 5048 } 5049 } 5050 return nullptr; 5051 } 5052 5053 // TODO: Move this out to a header file: 5054 static inline bool canIgnoreSNaN(fp::ExceptionBehavior EB, FastMathFlags FMF) { 5055 return (EB == fp::ebIgnore || FMF.noNaNs()); 5056 } 5057 5058 /// Given operands for an FAdd, see if we can fold the result. If not, this 5059 /// returns null. 5060 static Value * 5061 SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5062 const SimplifyQuery &Q, unsigned MaxRecurse, 5063 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5064 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5065 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5066 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q)) 5067 return C; 5068 5069 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5070 return C; 5071 5072 // fadd X, -0 ==> X 5073 // With strict/constrained FP, we have these possible edge cases that do 5074 // not simplify to Op0: 5075 // fadd SNaN, -0.0 --> QNaN 5076 // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative) 5077 if (canIgnoreSNaN(ExBehavior, FMF) && 5078 (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) || 5079 FMF.noSignedZeros())) 5080 if (match(Op1, m_NegZeroFP())) 5081 return Op0; 5082 5083 // fadd X, 0 ==> X, when we know X is not -0 5084 if (canIgnoreSNaN(ExBehavior, FMF)) 5085 if (match(Op1, m_PosZeroFP()) && 5086 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 5087 return Op0; 5088 5089 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5090 return nullptr; 5091 5092 // With nnan: -X + X --> 0.0 (and commuted variant) 5093 // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN. 5094 // Negative zeros are allowed because we always end up with positive zero: 5095 // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 5096 // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0 5097 // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0 5098 // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0 5099 if (FMF.noNaNs()) { 5100 if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) || 5101 match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0)))) 5102 return ConstantFP::getNullValue(Op0->getType()); 5103 5104 if (match(Op0, m_FNeg(m_Specific(Op1))) || 5105 match(Op1, m_FNeg(m_Specific(Op0)))) 5106 return ConstantFP::getNullValue(Op0->getType()); 5107 } 5108 5109 // (X - Y) + Y --> X 5110 // Y + (X - Y) --> X 5111 Value *X; 5112 if (FMF.noSignedZeros() && FMF.allowReassoc() && 5113 (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) || 5114 match(Op1, m_FSub(m_Value(X), m_Specific(Op0))))) 5115 return X; 5116 5117 return nullptr; 5118 } 5119 5120 /// Given operands for an FSub, see if we can fold the result. If not, this 5121 /// returns null. 5122 static Value * 5123 SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5124 const SimplifyQuery &Q, unsigned MaxRecurse, 5125 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5126 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5127 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5128 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q)) 5129 return C; 5130 5131 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5132 return C; 5133 5134 // fsub X, +0 ==> X 5135 if (canIgnoreSNaN(ExBehavior, FMF) && 5136 (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) || 5137 FMF.noSignedZeros())) 5138 if (match(Op1, m_PosZeroFP())) 5139 return Op0; 5140 5141 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5142 return nullptr; 5143 5144 // fsub X, -0 ==> X, when we know X is not -0 5145 if (match(Op1, m_NegZeroFP()) && 5146 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI))) 5147 return Op0; 5148 5149 // fsub -0.0, (fsub -0.0, X) ==> X 5150 // fsub -0.0, (fneg X) ==> X 5151 Value *X; 5152 if (match(Op0, m_NegZeroFP()) && 5153 match(Op1, m_FNeg(m_Value(X)))) 5154 return X; 5155 5156 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored. 5157 // fsub 0.0, (fneg X) ==> X if signed zeros are ignored. 5158 if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) && 5159 (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) || 5160 match(Op1, m_FNeg(m_Value(X))))) 5161 return X; 5162 5163 // fsub nnan x, x ==> 0.0 5164 if (FMF.noNaNs() && Op0 == Op1) 5165 return Constant::getNullValue(Op0->getType()); 5166 5167 // Y - (Y - X) --> X 5168 // (X + Y) - Y --> X 5169 if (FMF.noSignedZeros() && FMF.allowReassoc() && 5170 (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) || 5171 match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X))))) 5172 return X; 5173 5174 return nullptr; 5175 } 5176 5177 static Value *SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF, 5178 const SimplifyQuery &Q, unsigned MaxRecurse, 5179 fp::ExceptionBehavior ExBehavior, 5180 RoundingMode Rounding) { 5181 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5182 return C; 5183 5184 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5185 return nullptr; 5186 5187 // fmul X, 1.0 ==> X 5188 if (match(Op1, m_FPOne())) 5189 return Op0; 5190 5191 // fmul 1.0, X ==> X 5192 if (match(Op0, m_FPOne())) 5193 return Op1; 5194 5195 // fmul nnan nsz X, 0 ==> 0 5196 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZeroFP())) 5197 return ConstantFP::getNullValue(Op0->getType()); 5198 5199 // fmul nnan nsz 0, X ==> 0 5200 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) 5201 return ConstantFP::getNullValue(Op1->getType()); 5202 5203 // sqrt(X) * sqrt(X) --> X, if we can: 5204 // 1. Remove the intermediate rounding (reassociate). 5205 // 2. Ignore non-zero negative numbers because sqrt would produce NAN. 5206 // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0. 5207 Value *X; 5208 if (Op0 == Op1 && match(Op0, m_Intrinsic<Intrinsic::sqrt>(m_Value(X))) && 5209 FMF.allowReassoc() && FMF.noNaNs() && FMF.noSignedZeros()) 5210 return X; 5211 5212 return nullptr; 5213 } 5214 5215 /// Given the operands for an FMul, see if we can fold the result 5216 static Value * 5217 SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5218 const SimplifyQuery &Q, unsigned MaxRecurse, 5219 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5220 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5221 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5222 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q)) 5223 return C; 5224 5225 // Now apply simplifications that do not require rounding. 5226 return SimplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding); 5227 } 5228 5229 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5230 const SimplifyQuery &Q, 5231 fp::ExceptionBehavior ExBehavior, 5232 RoundingMode Rounding) { 5233 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5234 Rounding); 5235 } 5236 5237 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5238 const SimplifyQuery &Q, 5239 fp::ExceptionBehavior ExBehavior, 5240 RoundingMode Rounding) { 5241 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5242 Rounding); 5243 } 5244 5245 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5246 const SimplifyQuery &Q, 5247 fp::ExceptionBehavior ExBehavior, 5248 RoundingMode Rounding) { 5249 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5250 Rounding); 5251 } 5252 5253 Value *llvm::SimplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF, 5254 const SimplifyQuery &Q, 5255 fp::ExceptionBehavior ExBehavior, 5256 RoundingMode Rounding) { 5257 return ::SimplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5258 Rounding); 5259 } 5260 5261 static Value * 5262 SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5263 const SimplifyQuery &Q, unsigned, 5264 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5265 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5266 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5267 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q)) 5268 return C; 5269 5270 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5271 return C; 5272 5273 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5274 return nullptr; 5275 5276 // X / 1.0 -> X 5277 if (match(Op1, m_FPOne())) 5278 return Op0; 5279 5280 // 0 / X -> 0 5281 // Requires that NaNs are off (X could be zero) and signed zeroes are 5282 // ignored (X could be positive or negative, so the output sign is unknown). 5283 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP())) 5284 return ConstantFP::getNullValue(Op0->getType()); 5285 5286 if (FMF.noNaNs()) { 5287 // X / X -> 1.0 is legal when NaNs are ignored. 5288 // We can ignore infinities because INF/INF is NaN. 5289 if (Op0 == Op1) 5290 return ConstantFP::get(Op0->getType(), 1.0); 5291 5292 // (X * Y) / Y --> X if we can reassociate to the above form. 5293 Value *X; 5294 if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1)))) 5295 return X; 5296 5297 // -X / X -> -1.0 and 5298 // X / -X -> -1.0 are legal when NaNs are ignored. 5299 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored. 5300 if (match(Op0, m_FNegNSZ(m_Specific(Op1))) || 5301 match(Op1, m_FNegNSZ(m_Specific(Op0)))) 5302 return ConstantFP::get(Op0->getType(), -1.0); 5303 } 5304 5305 return nullptr; 5306 } 5307 5308 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5309 const SimplifyQuery &Q, 5310 fp::ExceptionBehavior ExBehavior, 5311 RoundingMode Rounding) { 5312 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5313 Rounding); 5314 } 5315 5316 static Value * 5317 SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5318 const SimplifyQuery &Q, unsigned, 5319 fp::ExceptionBehavior ExBehavior = fp::ebIgnore, 5320 RoundingMode Rounding = RoundingMode::NearestTiesToEven) { 5321 if (isDefaultFPEnvironment(ExBehavior, Rounding)) 5322 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q)) 5323 return C; 5324 5325 if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding)) 5326 return C; 5327 5328 if (!isDefaultFPEnvironment(ExBehavior, Rounding)) 5329 return nullptr; 5330 5331 // Unlike fdiv, the result of frem always matches the sign of the dividend. 5332 // The constant match may include undef elements in a vector, so return a full 5333 // zero constant as the result. 5334 if (FMF.noNaNs()) { 5335 // +0 % X -> 0 5336 if (match(Op0, m_PosZeroFP())) 5337 return ConstantFP::getNullValue(Op0->getType()); 5338 // -0 % X -> -0 5339 if (match(Op0, m_NegZeroFP())) 5340 return ConstantFP::getNegativeZero(Op0->getType()); 5341 } 5342 5343 return nullptr; 5344 } 5345 5346 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF, 5347 const SimplifyQuery &Q, 5348 fp::ExceptionBehavior ExBehavior, 5349 RoundingMode Rounding) { 5350 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior, 5351 Rounding); 5352 } 5353 5354 //=== Helper functions for higher up the class hierarchy. 5355 5356 /// Given the operand for a UnaryOperator, see if we can fold the result. 5357 /// If not, this returns null. 5358 static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q, 5359 unsigned MaxRecurse) { 5360 switch (Opcode) { 5361 case Instruction::FNeg: 5362 return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse); 5363 default: 5364 llvm_unreachable("Unexpected opcode"); 5365 } 5366 } 5367 5368 /// Given the operand for a UnaryOperator, see if we can fold the result. 5369 /// If not, this returns null. 5370 /// Try to use FastMathFlags when folding the result. 5371 static Value *simplifyFPUnOp(unsigned Opcode, Value *Op, 5372 const FastMathFlags &FMF, 5373 const SimplifyQuery &Q, unsigned MaxRecurse) { 5374 switch (Opcode) { 5375 case Instruction::FNeg: 5376 return simplifyFNegInst(Op, FMF, Q, MaxRecurse); 5377 default: 5378 return simplifyUnOp(Opcode, Op, Q, MaxRecurse); 5379 } 5380 } 5381 5382 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) { 5383 return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit); 5384 } 5385 5386 Value *llvm::SimplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF, 5387 const SimplifyQuery &Q) { 5388 return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit); 5389 } 5390 5391 /// Given operands for a BinaryOperator, see if we can fold the result. 5392 /// If not, this returns null. 5393 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5394 const SimplifyQuery &Q, unsigned MaxRecurse) { 5395 switch (Opcode) { 5396 case Instruction::Add: 5397 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse); 5398 case Instruction::Sub: 5399 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse); 5400 case Instruction::Mul: 5401 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse); 5402 case Instruction::SDiv: 5403 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); 5404 case Instruction::UDiv: 5405 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); 5406 case Instruction::SRem: 5407 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); 5408 case Instruction::URem: 5409 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); 5410 case Instruction::Shl: 5411 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse); 5412 case Instruction::LShr: 5413 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse); 5414 case Instruction::AShr: 5415 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse); 5416 case Instruction::And: 5417 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); 5418 case Instruction::Or: 5419 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse); 5420 case Instruction::Xor: 5421 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); 5422 case Instruction::FAdd: 5423 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5424 case Instruction::FSub: 5425 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5426 case Instruction::FMul: 5427 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5428 case Instruction::FDiv: 5429 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5430 case Instruction::FRem: 5431 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5432 default: 5433 llvm_unreachable("Unexpected opcode"); 5434 } 5435 } 5436 5437 /// Given operands for a BinaryOperator, see if we can fold the result. 5438 /// If not, this returns null. 5439 /// Try to use FastMathFlags when folding the result. 5440 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5441 const FastMathFlags &FMF, const SimplifyQuery &Q, 5442 unsigned MaxRecurse) { 5443 switch (Opcode) { 5444 case Instruction::FAdd: 5445 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse); 5446 case Instruction::FSub: 5447 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse); 5448 case Instruction::FMul: 5449 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse); 5450 case Instruction::FDiv: 5451 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse); 5452 default: 5453 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse); 5454 } 5455 } 5456 5457 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5458 const SimplifyQuery &Q) { 5459 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit); 5460 } 5461 5462 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 5463 FastMathFlags FMF, const SimplifyQuery &Q) { 5464 return ::SimplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit); 5465 } 5466 5467 /// Given operands for a CmpInst, see if we can fold the result. 5468 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 5469 const SimplifyQuery &Q, unsigned MaxRecurse) { 5470 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) 5471 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 5472 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse); 5473 } 5474 5475 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 5476 const SimplifyQuery &Q) { 5477 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit); 5478 } 5479 5480 static bool IsIdempotent(Intrinsic::ID ID) { 5481 switch (ID) { 5482 default: return false; 5483 5484 // Unary idempotent: f(f(x)) = f(x) 5485 case Intrinsic::fabs: 5486 case Intrinsic::floor: 5487 case Intrinsic::ceil: 5488 case Intrinsic::trunc: 5489 case Intrinsic::rint: 5490 case Intrinsic::nearbyint: 5491 case Intrinsic::round: 5492 case Intrinsic::roundeven: 5493 case Intrinsic::canonicalize: 5494 return true; 5495 } 5496 } 5497 5498 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset, 5499 const DataLayout &DL) { 5500 GlobalValue *PtrSym; 5501 APInt PtrOffset; 5502 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL)) 5503 return nullptr; 5504 5505 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext()); 5506 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext()); 5507 Type *Int32PtrTy = Int32Ty->getPointerTo(); 5508 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext()); 5509 5510 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset); 5511 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64) 5512 return nullptr; 5513 5514 uint64_t OffsetInt = OffsetConstInt->getSExtValue(); 5515 if (OffsetInt % 4 != 0) 5516 return nullptr; 5517 5518 Constant *C = ConstantExpr::getGetElementPtr( 5519 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy), 5520 ConstantInt::get(Int64Ty, OffsetInt / 4)); 5521 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL); 5522 if (!Loaded) 5523 return nullptr; 5524 5525 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded); 5526 if (!LoadedCE) 5527 return nullptr; 5528 5529 if (LoadedCE->getOpcode() == Instruction::Trunc) { 5530 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 5531 if (!LoadedCE) 5532 return nullptr; 5533 } 5534 5535 if (LoadedCE->getOpcode() != Instruction::Sub) 5536 return nullptr; 5537 5538 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0)); 5539 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt) 5540 return nullptr; 5541 auto *LoadedLHSPtr = LoadedLHS->getOperand(0); 5542 5543 Constant *LoadedRHS = LoadedCE->getOperand(1); 5544 GlobalValue *LoadedRHSSym; 5545 APInt LoadedRHSOffset; 5546 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset, 5547 DL) || 5548 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset) 5549 return nullptr; 5550 5551 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy); 5552 } 5553 5554 static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0, 5555 const SimplifyQuery &Q) { 5556 // Idempotent functions return the same result when called repeatedly. 5557 Intrinsic::ID IID = F->getIntrinsicID(); 5558 if (IsIdempotent(IID)) 5559 if (auto *II = dyn_cast<IntrinsicInst>(Op0)) 5560 if (II->getIntrinsicID() == IID) 5561 return II; 5562 5563 Value *X; 5564 switch (IID) { 5565 case Intrinsic::fabs: 5566 if (SignBitMustBeZero(Op0, Q.TLI)) return Op0; 5567 break; 5568 case Intrinsic::bswap: 5569 // bswap(bswap(x)) -> x 5570 if (match(Op0, m_BSwap(m_Value(X)))) return X; 5571 break; 5572 case Intrinsic::bitreverse: 5573 // bitreverse(bitreverse(x)) -> x 5574 if (match(Op0, m_BitReverse(m_Value(X)))) return X; 5575 break; 5576 case Intrinsic::ctpop: { 5577 // If everything but the lowest bit is zero, that bit is the pop-count. Ex: 5578 // ctpop(and X, 1) --> and X, 1 5579 unsigned BitWidth = Op0->getType()->getScalarSizeInBits(); 5580 if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1), 5581 Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) 5582 return Op0; 5583 break; 5584 } 5585 case Intrinsic::exp: 5586 // exp(log(x)) -> x 5587 if (Q.CxtI->hasAllowReassoc() && 5588 match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X)))) return X; 5589 break; 5590 case Intrinsic::exp2: 5591 // exp2(log2(x)) -> x 5592 if (Q.CxtI->hasAllowReassoc() && 5593 match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X)))) return X; 5594 break; 5595 case Intrinsic::log: 5596 // log(exp(x)) -> x 5597 if (Q.CxtI->hasAllowReassoc() && 5598 match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X)))) return X; 5599 break; 5600 case Intrinsic::log2: 5601 // log2(exp2(x)) -> x 5602 if (Q.CxtI->hasAllowReassoc() && 5603 (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) || 5604 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), 5605 m_Value(X))))) return X; 5606 break; 5607 case Intrinsic::log10: 5608 // log10(pow(10.0, x)) -> x 5609 if (Q.CxtI->hasAllowReassoc() && 5610 match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), 5611 m_Value(X)))) return X; 5612 break; 5613 case Intrinsic::floor: 5614 case Intrinsic::trunc: 5615 case Intrinsic::ceil: 5616 case Intrinsic::round: 5617 case Intrinsic::roundeven: 5618 case Intrinsic::nearbyint: 5619 case Intrinsic::rint: { 5620 // floor (sitofp x) -> sitofp x 5621 // floor (uitofp x) -> uitofp x 5622 // 5623 // Converting from int always results in a finite integral number or 5624 // infinity. For either of those inputs, these rounding functions always 5625 // return the same value, so the rounding can be eliminated. 5626 if (match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value()))) 5627 return Op0; 5628 break; 5629 } 5630 case Intrinsic::experimental_vector_reverse: 5631 // experimental.vector.reverse(experimental.vector.reverse(x)) -> x 5632 if (match(Op0, 5633 m_Intrinsic<Intrinsic::experimental_vector_reverse>(m_Value(X)))) 5634 return X; 5635 // experimental.vector.reverse(splat(X)) -> splat(X) 5636 if (isSplatValue(Op0)) 5637 return Op0; 5638 break; 5639 default: 5640 break; 5641 } 5642 5643 return nullptr; 5644 } 5645 5646 /// Given a min/max intrinsic, see if it can be removed based on having an 5647 /// operand that is another min/max intrinsic with shared operand(s). The caller 5648 /// is expected to swap the operand arguments to handle commutation. 5649 static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) { 5650 Value *X, *Y; 5651 if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y)))) 5652 return nullptr; 5653 5654 auto *MM0 = dyn_cast<IntrinsicInst>(Op0); 5655 if (!MM0) 5656 return nullptr; 5657 Intrinsic::ID IID0 = MM0->getIntrinsicID(); 5658 5659 if (Op1 == X || Op1 == Y || 5660 match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) { 5661 // max (max X, Y), X --> max X, Y 5662 if (IID0 == IID) 5663 return MM0; 5664 // max (min X, Y), X --> X 5665 if (IID0 == getInverseMinMaxIntrinsic(IID)) 5666 return Op1; 5667 } 5668 return nullptr; 5669 } 5670 5671 static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1, 5672 const SimplifyQuery &Q) { 5673 Intrinsic::ID IID = F->getIntrinsicID(); 5674 Type *ReturnType = F->getReturnType(); 5675 unsigned BitWidth = ReturnType->getScalarSizeInBits(); 5676 switch (IID) { 5677 case Intrinsic::abs: 5678 // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here. 5679 // It is always ok to pick the earlier abs. We'll just lose nsw if its only 5680 // on the outer abs. 5681 if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value()))) 5682 return Op0; 5683 break; 5684 5685 case Intrinsic::cttz: { 5686 Value *X; 5687 if (match(Op0, m_Shl(m_One(), m_Value(X)))) 5688 return X; 5689 break; 5690 } 5691 case Intrinsic::ctlz: { 5692 Value *X; 5693 if (match(Op0, m_LShr(m_Negative(), m_Value(X)))) 5694 return X; 5695 if (match(Op0, m_AShr(m_Negative(), m_Value()))) 5696 return Constant::getNullValue(ReturnType); 5697 break; 5698 } 5699 case Intrinsic::smax: 5700 case Intrinsic::smin: 5701 case Intrinsic::umax: 5702 case Intrinsic::umin: { 5703 // If the arguments are the same, this is a no-op. 5704 if (Op0 == Op1) 5705 return Op0; 5706 5707 // Canonicalize constant operand as Op1. 5708 if (isa<Constant>(Op0)) 5709 std::swap(Op0, Op1); 5710 5711 // Assume undef is the limit value. 5712 if (Q.isUndefValue(Op1)) 5713 return ConstantInt::get( 5714 ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth)); 5715 5716 const APInt *C; 5717 if (match(Op1, m_APIntAllowUndef(C))) { 5718 // Clamp to limit value. For example: 5719 // umax(i8 %x, i8 255) --> 255 5720 if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth)) 5721 return ConstantInt::get(ReturnType, *C); 5722 5723 // If the constant op is the opposite of the limit value, the other must 5724 // be larger/smaller or equal. For example: 5725 // umin(i8 %x, i8 255) --> %x 5726 if (*C == MinMaxIntrinsic::getSaturationPoint( 5727 getInverseMinMaxIntrinsic(IID), BitWidth)) 5728 return Op0; 5729 5730 // Remove nested call if constant operands allow it. Example: 5731 // max (max X, 7), 5 -> max X, 7 5732 auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0); 5733 if (MinMax0 && MinMax0->getIntrinsicID() == IID) { 5734 // TODO: loosen undef/splat restrictions for vector constants. 5735 Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1); 5736 const APInt *InnerC; 5737 if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) && 5738 ICmpInst::compare(*InnerC, *C, 5739 ICmpInst::getNonStrictPredicate( 5740 MinMaxIntrinsic::getPredicate(IID)))) 5741 return Op0; 5742 } 5743 } 5744 5745 if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1)) 5746 return V; 5747 if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0)) 5748 return V; 5749 5750 ICmpInst::Predicate Pred = 5751 ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID)); 5752 if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit)) 5753 return Op0; 5754 if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit)) 5755 return Op1; 5756 5757 if (Optional<bool> Imp = 5758 isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL)) 5759 return *Imp ? Op0 : Op1; 5760 if (Optional<bool> Imp = 5761 isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL)) 5762 return *Imp ? Op1 : Op0; 5763 5764 break; 5765 } 5766 case Intrinsic::usub_with_overflow: 5767 case Intrinsic::ssub_with_overflow: 5768 // X - X -> { 0, false } 5769 // X - undef -> { 0, false } 5770 // undef - X -> { 0, false } 5771 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5772 return Constant::getNullValue(ReturnType); 5773 break; 5774 case Intrinsic::uadd_with_overflow: 5775 case Intrinsic::sadd_with_overflow: 5776 // X + undef -> { -1, false } 5777 // undef + x -> { -1, false } 5778 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) { 5779 return ConstantStruct::get( 5780 cast<StructType>(ReturnType), 5781 {Constant::getAllOnesValue(ReturnType->getStructElementType(0)), 5782 Constant::getNullValue(ReturnType->getStructElementType(1))}); 5783 } 5784 break; 5785 case Intrinsic::umul_with_overflow: 5786 case Intrinsic::smul_with_overflow: 5787 // 0 * X -> { 0, false } 5788 // X * 0 -> { 0, false } 5789 if (match(Op0, m_Zero()) || match(Op1, m_Zero())) 5790 return Constant::getNullValue(ReturnType); 5791 // undef * X -> { 0, false } 5792 // X * undef -> { 0, false } 5793 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5794 return Constant::getNullValue(ReturnType); 5795 break; 5796 case Intrinsic::uadd_sat: 5797 // sat(MAX + X) -> MAX 5798 // sat(X + MAX) -> MAX 5799 if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes())) 5800 return Constant::getAllOnesValue(ReturnType); 5801 LLVM_FALLTHROUGH; 5802 case Intrinsic::sadd_sat: 5803 // sat(X + undef) -> -1 5804 // sat(undef + X) -> -1 5805 // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1). 5806 // For signed: Assume undef is ~X, in which case X + ~X = -1. 5807 if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5808 return Constant::getAllOnesValue(ReturnType); 5809 5810 // X + 0 -> X 5811 if (match(Op1, m_Zero())) 5812 return Op0; 5813 // 0 + X -> X 5814 if (match(Op0, m_Zero())) 5815 return Op1; 5816 break; 5817 case Intrinsic::usub_sat: 5818 // sat(0 - X) -> 0, sat(X - MAX) -> 0 5819 if (match(Op0, m_Zero()) || match(Op1, m_AllOnes())) 5820 return Constant::getNullValue(ReturnType); 5821 LLVM_FALLTHROUGH; 5822 case Intrinsic::ssub_sat: 5823 // X - X -> 0, X - undef -> 0, undef - X -> 0 5824 if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) 5825 return Constant::getNullValue(ReturnType); 5826 // X - 0 -> X 5827 if (match(Op1, m_Zero())) 5828 return Op0; 5829 break; 5830 case Intrinsic::load_relative: 5831 if (auto *C0 = dyn_cast<Constant>(Op0)) 5832 if (auto *C1 = dyn_cast<Constant>(Op1)) 5833 return SimplifyRelativeLoad(C0, C1, Q.DL); 5834 break; 5835 case Intrinsic::powi: 5836 if (auto *Power = dyn_cast<ConstantInt>(Op1)) { 5837 // powi(x, 0) -> 1.0 5838 if (Power->isZero()) 5839 return ConstantFP::get(Op0->getType(), 1.0); 5840 // powi(x, 1) -> x 5841 if (Power->isOne()) 5842 return Op0; 5843 } 5844 break; 5845 case Intrinsic::copysign: 5846 // copysign X, X --> X 5847 if (Op0 == Op1) 5848 return Op0; 5849 // copysign -X, X --> X 5850 // copysign X, -X --> -X 5851 if (match(Op0, m_FNeg(m_Specific(Op1))) || 5852 match(Op1, m_FNeg(m_Specific(Op0)))) 5853 return Op1; 5854 break; 5855 case Intrinsic::maxnum: 5856 case Intrinsic::minnum: 5857 case Intrinsic::maximum: 5858 case Intrinsic::minimum: { 5859 // If the arguments are the same, this is a no-op. 5860 if (Op0 == Op1) return Op0; 5861 5862 // Canonicalize constant operand as Op1. 5863 if (isa<Constant>(Op0)) 5864 std::swap(Op0, Op1); 5865 5866 // If an argument is undef, return the other argument. 5867 if (Q.isUndefValue(Op1)) 5868 return Op0; 5869 5870 bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum; 5871 bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum; 5872 5873 // minnum(X, nan) -> X 5874 // maxnum(X, nan) -> X 5875 // minimum(X, nan) -> nan 5876 // maximum(X, nan) -> nan 5877 if (match(Op1, m_NaN())) 5878 return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0; 5879 5880 // In the following folds, inf can be replaced with the largest finite 5881 // float, if the ninf flag is set. 5882 const APFloat *C; 5883 if (match(Op1, m_APFloat(C)) && 5884 (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) { 5885 // minnum(X, -inf) -> -inf 5886 // maxnum(X, +inf) -> +inf 5887 // minimum(X, -inf) -> -inf if nnan 5888 // maximum(X, +inf) -> +inf if nnan 5889 if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs())) 5890 return ConstantFP::get(ReturnType, *C); 5891 5892 // minnum(X, +inf) -> X if nnan 5893 // maxnum(X, -inf) -> X if nnan 5894 // minimum(X, +inf) -> X 5895 // maximum(X, -inf) -> X 5896 if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs())) 5897 return Op0; 5898 } 5899 5900 // Min/max of the same operation with common operand: 5901 // m(m(X, Y)), X --> m(X, Y) (4 commuted variants) 5902 if (auto *M0 = dyn_cast<IntrinsicInst>(Op0)) 5903 if (M0->getIntrinsicID() == IID && 5904 (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1)) 5905 return Op0; 5906 if (auto *M1 = dyn_cast<IntrinsicInst>(Op1)) 5907 if (M1->getIntrinsicID() == IID && 5908 (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0)) 5909 return Op1; 5910 5911 break; 5912 } 5913 case Intrinsic::experimental_vector_extract: { 5914 Type *ReturnType = F->getReturnType(); 5915 5916 // (extract_vector (insert_vector _, X, 0), 0) -> X 5917 unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue(); 5918 Value *X = nullptr; 5919 if (match(Op0, m_Intrinsic<Intrinsic::experimental_vector_insert>( 5920 m_Value(), m_Value(X), m_Zero())) && 5921 IdxN == 0 && X->getType() == ReturnType) 5922 return X; 5923 5924 break; 5925 } 5926 default: 5927 break; 5928 } 5929 5930 return nullptr; 5931 } 5932 5933 static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) { 5934 5935 unsigned NumOperands = Call->arg_size(); 5936 Function *F = cast<Function>(Call->getCalledFunction()); 5937 Intrinsic::ID IID = F->getIntrinsicID(); 5938 5939 // Most of the intrinsics with no operands have some kind of side effect. 5940 // Don't simplify. 5941 if (!NumOperands) { 5942 switch (IID) { 5943 case Intrinsic::vscale: { 5944 // Call may not be inserted into the IR yet at point of calling simplify. 5945 if (!Call->getParent() || !Call->getParent()->getParent()) 5946 return nullptr; 5947 auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange); 5948 if (!Attr.isValid()) 5949 return nullptr; 5950 unsigned VScaleMin = Attr.getVScaleRangeMin(); 5951 Optional<unsigned> VScaleMax = Attr.getVScaleRangeMax(); 5952 if (VScaleMax && VScaleMin == VScaleMax) 5953 return ConstantInt::get(F->getReturnType(), VScaleMin); 5954 return nullptr; 5955 } 5956 default: 5957 return nullptr; 5958 } 5959 } 5960 5961 if (NumOperands == 1) 5962 return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q); 5963 5964 if (NumOperands == 2) 5965 return simplifyBinaryIntrinsic(F, Call->getArgOperand(0), 5966 Call->getArgOperand(1), Q); 5967 5968 // Handle intrinsics with 3 or more arguments. 5969 switch (IID) { 5970 case Intrinsic::masked_load: 5971 case Intrinsic::masked_gather: { 5972 Value *MaskArg = Call->getArgOperand(2); 5973 Value *PassthruArg = Call->getArgOperand(3); 5974 // If the mask is all zeros or undef, the "passthru" argument is the result. 5975 if (maskIsAllZeroOrUndef(MaskArg)) 5976 return PassthruArg; 5977 return nullptr; 5978 } 5979 case Intrinsic::fshl: 5980 case Intrinsic::fshr: { 5981 Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1), 5982 *ShAmtArg = Call->getArgOperand(2); 5983 5984 // If both operands are undef, the result is undef. 5985 if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1)) 5986 return UndefValue::get(F->getReturnType()); 5987 5988 // If shift amount is undef, assume it is zero. 5989 if (Q.isUndefValue(ShAmtArg)) 5990 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1); 5991 5992 const APInt *ShAmtC; 5993 if (match(ShAmtArg, m_APInt(ShAmtC))) { 5994 // If there's effectively no shift, return the 1st arg or 2nd arg. 5995 APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth()); 5996 if (ShAmtC->urem(BitWidth).isZero()) 5997 return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1); 5998 } 5999 6000 // Rotating zero by anything is zero. 6001 if (match(Op0, m_Zero()) && match(Op1, m_Zero())) 6002 return ConstantInt::getNullValue(F->getReturnType()); 6003 6004 // Rotating -1 by anything is -1. 6005 if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes())) 6006 return ConstantInt::getAllOnesValue(F->getReturnType()); 6007 6008 return nullptr; 6009 } 6010 case Intrinsic::experimental_constrained_fma: { 6011 Value *Op0 = Call->getArgOperand(0); 6012 Value *Op1 = Call->getArgOperand(1); 6013 Value *Op2 = Call->getArgOperand(2); 6014 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6015 if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, 6016 FPI->getExceptionBehavior().getValue(), 6017 FPI->getRoundingMode().getValue())) 6018 return V; 6019 return nullptr; 6020 } 6021 case Intrinsic::fma: 6022 case Intrinsic::fmuladd: { 6023 Value *Op0 = Call->getArgOperand(0); 6024 Value *Op1 = Call->getArgOperand(1); 6025 Value *Op2 = Call->getArgOperand(2); 6026 if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore, 6027 RoundingMode::NearestTiesToEven)) 6028 return V; 6029 return nullptr; 6030 } 6031 case Intrinsic::smul_fix: 6032 case Intrinsic::smul_fix_sat: { 6033 Value *Op0 = Call->getArgOperand(0); 6034 Value *Op1 = Call->getArgOperand(1); 6035 Value *Op2 = Call->getArgOperand(2); 6036 Type *ReturnType = F->getReturnType(); 6037 6038 // Canonicalize constant operand as Op1 (ConstantFolding handles the case 6039 // when both Op0 and Op1 are constant so we do not care about that special 6040 // case here). 6041 if (isa<Constant>(Op0)) 6042 std::swap(Op0, Op1); 6043 6044 // X * 0 -> 0 6045 if (match(Op1, m_Zero())) 6046 return Constant::getNullValue(ReturnType); 6047 6048 // X * undef -> 0 6049 if (Q.isUndefValue(Op1)) 6050 return Constant::getNullValue(ReturnType); 6051 6052 // X * (1 << Scale) -> X 6053 APInt ScaledOne = 6054 APInt::getOneBitSet(ReturnType->getScalarSizeInBits(), 6055 cast<ConstantInt>(Op2)->getZExtValue()); 6056 if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne))) 6057 return Op0; 6058 6059 return nullptr; 6060 } 6061 case Intrinsic::experimental_vector_insert: { 6062 Value *Vec = Call->getArgOperand(0); 6063 Value *SubVec = Call->getArgOperand(1); 6064 Value *Idx = Call->getArgOperand(2); 6065 Type *ReturnType = F->getReturnType(); 6066 6067 // (insert_vector Y, (extract_vector X, 0), 0) -> X 6068 // where: Y is X, or Y is undef 6069 unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue(); 6070 Value *X = nullptr; 6071 if (match(SubVec, m_Intrinsic<Intrinsic::experimental_vector_extract>( 6072 m_Value(X), m_Zero())) && 6073 (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 && 6074 X->getType() == ReturnType) 6075 return X; 6076 6077 return nullptr; 6078 } 6079 case Intrinsic::experimental_constrained_fadd: { 6080 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6081 return SimplifyFAddInst(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_fsub: { 6088 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6089 return SimplifyFSubInst(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_fmul: { 6096 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6097 return SimplifyFMulInst(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_fdiv: { 6104 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6105 return SimplifyFDivInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 6106 FPI->getFastMathFlags(), Q, 6107 FPI->getExceptionBehavior().getValue(), 6108 FPI->getRoundingMode().getValue()); 6109 break; 6110 } 6111 case Intrinsic::experimental_constrained_frem: { 6112 auto *FPI = cast<ConstrainedFPIntrinsic>(Call); 6113 return SimplifyFRemInst(FPI->getArgOperand(0), FPI->getArgOperand(1), 6114 FPI->getFastMathFlags(), Q, 6115 FPI->getExceptionBehavior().getValue(), 6116 FPI->getRoundingMode().getValue()); 6117 break; 6118 } 6119 default: 6120 return nullptr; 6121 } 6122 } 6123 6124 static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) { 6125 auto *F = dyn_cast<Function>(Call->getCalledOperand()); 6126 if (!F || !canConstantFoldCallTo(Call, F)) 6127 return nullptr; 6128 6129 SmallVector<Constant *, 4> ConstantArgs; 6130 unsigned NumArgs = Call->arg_size(); 6131 ConstantArgs.reserve(NumArgs); 6132 for (auto &Arg : Call->args()) { 6133 Constant *C = dyn_cast<Constant>(&Arg); 6134 if (!C) { 6135 if (isa<MetadataAsValue>(Arg.get())) 6136 continue; 6137 return nullptr; 6138 } 6139 ConstantArgs.push_back(C); 6140 } 6141 6142 return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI); 6143 } 6144 6145 Value *llvm::SimplifyCall(CallBase *Call, const SimplifyQuery &Q) { 6146 // musttail calls can only be simplified if they are also DCEd. 6147 // As we can't guarantee this here, don't simplify them. 6148 if (Call->isMustTailCall()) 6149 return nullptr; 6150 6151 // call undef -> poison 6152 // call null -> poison 6153 Value *Callee = Call->getCalledOperand(); 6154 if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee)) 6155 return PoisonValue::get(Call->getType()); 6156 6157 if (Value *V = tryConstantFoldCall(Call, Q)) 6158 return V; 6159 6160 auto *F = dyn_cast<Function>(Callee); 6161 if (F && F->isIntrinsic()) 6162 if (Value *Ret = simplifyIntrinsic(Call, Q)) 6163 return Ret; 6164 6165 return nullptr; 6166 } 6167 6168 /// Given operands for a Freeze, see if we can fold the result. 6169 static Value *SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) { 6170 // Use a utility function defined in ValueTracking. 6171 if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT)) 6172 return Op0; 6173 // We have room for improvement. 6174 return nullptr; 6175 } 6176 6177 Value *llvm::SimplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) { 6178 return ::SimplifyFreezeInst(Op0, Q); 6179 } 6180 6181 static Value *SimplifyLoadInst(LoadInst *LI, Value *PtrOp, 6182 const SimplifyQuery &Q) { 6183 if (LI->isVolatile()) 6184 return nullptr; 6185 6186 APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0); 6187 auto *PtrOpC = dyn_cast<Constant>(PtrOp); 6188 // Try to convert operand into a constant by stripping offsets while looking 6189 // through invariant.group intrinsics. Don't bother if the underlying object 6190 // is not constant, as calculating GEP offsets is expensive. 6191 if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) { 6192 PtrOp = PtrOp->stripAndAccumulateConstantOffsets( 6193 Q.DL, Offset, /* AllowNonInbounts */ true, 6194 /* AllowInvariantGroup */ true); 6195 // Index size may have changed due to address space casts. 6196 Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType())); 6197 PtrOpC = dyn_cast<Constant>(PtrOp); 6198 } 6199 6200 if (PtrOpC) 6201 return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL); 6202 return nullptr; 6203 } 6204 6205 /// See if we can compute a simplified version of this instruction. 6206 /// If not, this returns null. 6207 6208 static Value *simplifyInstructionWithOperands(Instruction *I, 6209 ArrayRef<Value *> NewOps, 6210 const SimplifyQuery &SQ, 6211 OptimizationRemarkEmitter *ORE) { 6212 const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I); 6213 Value *Result = nullptr; 6214 6215 switch (I->getOpcode()) { 6216 default: 6217 if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) { 6218 SmallVector<Constant *, 8> NewConstOps(NewOps.size()); 6219 transform(NewOps, NewConstOps.begin(), 6220 [](Value *V) { return cast<Constant>(V); }); 6221 Result = ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI); 6222 } 6223 break; 6224 case Instruction::FNeg: 6225 Result = SimplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q); 6226 break; 6227 case Instruction::FAdd: 6228 Result = SimplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6229 break; 6230 case Instruction::Add: 6231 Result = SimplifyAddInst( 6232 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6233 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6234 break; 6235 case Instruction::FSub: 6236 Result = SimplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6237 break; 6238 case Instruction::Sub: 6239 Result = SimplifySubInst( 6240 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6241 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6242 break; 6243 case Instruction::FMul: 6244 Result = SimplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6245 break; 6246 case Instruction::Mul: 6247 Result = SimplifyMulInst(NewOps[0], NewOps[1], Q); 6248 break; 6249 case Instruction::SDiv: 6250 Result = SimplifySDivInst(NewOps[0], NewOps[1], Q); 6251 break; 6252 case Instruction::UDiv: 6253 Result = SimplifyUDivInst(NewOps[0], NewOps[1], Q); 6254 break; 6255 case Instruction::FDiv: 6256 Result = SimplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6257 break; 6258 case Instruction::SRem: 6259 Result = SimplifySRemInst(NewOps[0], NewOps[1], Q); 6260 break; 6261 case Instruction::URem: 6262 Result = SimplifyURemInst(NewOps[0], NewOps[1], Q); 6263 break; 6264 case Instruction::FRem: 6265 Result = SimplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q); 6266 break; 6267 case Instruction::Shl: 6268 Result = SimplifyShlInst( 6269 NewOps[0], NewOps[1], Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)), 6270 Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q); 6271 break; 6272 case Instruction::LShr: 6273 Result = SimplifyLShrInst(NewOps[0], NewOps[1], 6274 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); 6275 break; 6276 case Instruction::AShr: 6277 Result = SimplifyAShrInst(NewOps[0], NewOps[1], 6278 Q.IIQ.isExact(cast<BinaryOperator>(I)), Q); 6279 break; 6280 case Instruction::And: 6281 Result = SimplifyAndInst(NewOps[0], NewOps[1], Q); 6282 break; 6283 case Instruction::Or: 6284 Result = SimplifyOrInst(NewOps[0], NewOps[1], Q); 6285 break; 6286 case Instruction::Xor: 6287 Result = SimplifyXorInst(NewOps[0], NewOps[1], Q); 6288 break; 6289 case Instruction::ICmp: 6290 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0], 6291 NewOps[1], Q); 6292 break; 6293 case Instruction::FCmp: 6294 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0], 6295 NewOps[1], I->getFastMathFlags(), Q); 6296 break; 6297 case Instruction::Select: 6298 Result = SimplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q); 6299 break; 6300 case Instruction::GetElementPtr: { 6301 auto *GEPI = cast<GetElementPtrInst>(I); 6302 Result = 6303 SimplifyGEPInst(GEPI->getSourceElementType(), NewOps[0], 6304 makeArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q); 6305 break; 6306 } 6307 case Instruction::InsertValue: { 6308 InsertValueInst *IV = cast<InsertValueInst>(I); 6309 Result = SimplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q); 6310 break; 6311 } 6312 case Instruction::InsertElement: { 6313 Result = SimplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q); 6314 break; 6315 } 6316 case Instruction::ExtractValue: { 6317 auto *EVI = cast<ExtractValueInst>(I); 6318 Result = SimplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q); 6319 break; 6320 } 6321 case Instruction::ExtractElement: { 6322 Result = SimplifyExtractElementInst(NewOps[0], NewOps[1], Q); 6323 break; 6324 } 6325 case Instruction::ShuffleVector: { 6326 auto *SVI = cast<ShuffleVectorInst>(I); 6327 Result = SimplifyShuffleVectorInst( 6328 NewOps[0], NewOps[1], SVI->getShuffleMask(), SVI->getType(), Q); 6329 break; 6330 } 6331 case Instruction::PHI: 6332 Result = SimplifyPHINode(cast<PHINode>(I), NewOps, Q); 6333 break; 6334 case Instruction::Call: { 6335 // TODO: Use NewOps 6336 Result = SimplifyCall(cast<CallInst>(I), Q); 6337 break; 6338 } 6339 case Instruction::Freeze: 6340 Result = llvm::SimplifyFreezeInst(NewOps[0], Q); 6341 break; 6342 #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc: 6343 #include "llvm/IR/Instruction.def" 6344 #undef HANDLE_CAST_INST 6345 Result = SimplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q); 6346 break; 6347 case Instruction::Alloca: 6348 // No simplifications for Alloca and it can't be constant folded. 6349 Result = nullptr; 6350 break; 6351 case Instruction::Load: 6352 Result = SimplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q); 6353 break; 6354 } 6355 6356 /// If called on unreachable code, the above logic may report that the 6357 /// instruction simplified to itself. Make life easier for users by 6358 /// detecting that case here, returning a safe value instead. 6359 return Result == I ? UndefValue::get(I->getType()) : Result; 6360 } 6361 6362 Value *llvm::SimplifyInstructionWithOperands(Instruction *I, 6363 ArrayRef<Value *> NewOps, 6364 const SimplifyQuery &SQ, 6365 OptimizationRemarkEmitter *ORE) { 6366 assert(NewOps.size() == I->getNumOperands() && 6367 "Number of operands should match the instruction!"); 6368 return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE); 6369 } 6370 6371 Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &SQ, 6372 OptimizationRemarkEmitter *ORE) { 6373 SmallVector<Value *, 8> Ops(I->operands()); 6374 return ::simplifyInstructionWithOperands(I, Ops, SQ, ORE); 6375 } 6376 6377 /// Implementation of recursive simplification through an instruction's 6378 /// uses. 6379 /// 6380 /// This is the common implementation of the recursive simplification routines. 6381 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to 6382 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of 6383 /// instructions to process and attempt to simplify it using 6384 /// InstructionSimplify. Recursively visited users which could not be 6385 /// simplified themselves are to the optional UnsimplifiedUsers set for 6386 /// further processing by the caller. 6387 /// 6388 /// This routine returns 'true' only when *it* simplifies something. The passed 6389 /// in simplified value does not count toward this. 6390 static bool replaceAndRecursivelySimplifyImpl( 6391 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI, 6392 const DominatorTree *DT, AssumptionCache *AC, 6393 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) { 6394 bool Simplified = false; 6395 SmallSetVector<Instruction *, 8> Worklist; 6396 const DataLayout &DL = I->getModule()->getDataLayout(); 6397 6398 // If we have an explicit value to collapse to, do that round of the 6399 // simplification loop by hand initially. 6400 if (SimpleV) { 6401 for (User *U : I->users()) 6402 if (U != I) 6403 Worklist.insert(cast<Instruction>(U)); 6404 6405 // Replace the instruction with its simplified value. 6406 I->replaceAllUsesWith(SimpleV); 6407 6408 // Gracefully handle edge cases where the instruction is not wired into any 6409 // parent block. 6410 if (I->getParent() && !I->isEHPad() && !I->isTerminator() && 6411 !I->mayHaveSideEffects()) 6412 I->eraseFromParent(); 6413 } else { 6414 Worklist.insert(I); 6415 } 6416 6417 // Note that we must test the size on each iteration, the worklist can grow. 6418 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 6419 I = Worklist[Idx]; 6420 6421 // See if this instruction simplifies. 6422 SimpleV = SimplifyInstruction(I, {DL, TLI, DT, AC}); 6423 if (!SimpleV) { 6424 if (UnsimplifiedUsers) 6425 UnsimplifiedUsers->insert(I); 6426 continue; 6427 } 6428 6429 Simplified = true; 6430 6431 // Stash away all the uses of the old instruction so we can check them for 6432 // recursive simplifications after a RAUW. This is cheaper than checking all 6433 // uses of To on the recursive step in most cases. 6434 for (User *U : I->users()) 6435 Worklist.insert(cast<Instruction>(U)); 6436 6437 // Replace the instruction with its simplified value. 6438 I->replaceAllUsesWith(SimpleV); 6439 6440 // Gracefully handle edge cases where the instruction is not wired into any 6441 // parent block. 6442 if (I->getParent() && !I->isEHPad() && !I->isTerminator() && 6443 !I->mayHaveSideEffects()) 6444 I->eraseFromParent(); 6445 } 6446 return Simplified; 6447 } 6448 6449 bool llvm::replaceAndRecursivelySimplify( 6450 Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI, 6451 const DominatorTree *DT, AssumptionCache *AC, 6452 SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) { 6453 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!"); 6454 assert(SimpleV && "Must provide a simplified value."); 6455 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC, 6456 UnsimplifiedUsers); 6457 } 6458 6459 namespace llvm { 6460 const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) { 6461 auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>(); 6462 auto *DT = DTWP ? &DTWP->getDomTree() : nullptr; 6463 auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 6464 auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr; 6465 auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>(); 6466 auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr; 6467 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 6468 } 6469 6470 const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR, 6471 const DataLayout &DL) { 6472 return {DL, &AR.TLI, &AR.DT, &AR.AC}; 6473 } 6474 6475 template <class T, class... TArgs> 6476 const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM, 6477 Function &F) { 6478 auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F); 6479 auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F); 6480 auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F); 6481 return {F.getParent()->getDataLayout(), TLI, DT, AC}; 6482 } 6483 template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &, 6484 Function &); 6485 } 6486 6487 void InstSimplifyFolder::anchor() {} 6488