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