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