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