1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements routines for folding instructions into simpler forms 11 // that do not require creating new instructions. This does constant folding 12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either 13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value 14 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been 15 // simplified: This is usually true and assuming it simplifies the logic (if 16 // they have not been simplified then results are correct but maybe suboptimal). 17 // 18 //===----------------------------------------------------------------------===// 19 20 #include "llvm/Analysis/InstructionSimplify.h" 21 #include "llvm/ADT/SetVector.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/Analysis/ConstantFolding.h" 24 #include "llvm/Analysis/MemoryBuiltins.h" 25 #include "llvm/Analysis/ValueTracking.h" 26 #include "llvm/IR/ConstantRange.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/Dominators.h" 29 #include "llvm/IR/GetElementPtrTypeIterator.h" 30 #include "llvm/IR/GlobalAlias.h" 31 #include "llvm/IR/Operator.h" 32 #include "llvm/IR/PatternMatch.h" 33 #include "llvm/IR/ValueHandle.h" 34 using namespace llvm; 35 using namespace llvm::PatternMatch; 36 37 #define DEBUG_TYPE "instsimplify" 38 39 enum { RecursionLimit = 3 }; 40 41 STATISTIC(NumExpand, "Number of expansions"); 42 STATISTIC(NumReassoc, "Number of reassociations"); 43 44 struct Query { 45 const DataLayout *DL; 46 const TargetLibraryInfo *TLI; 47 const DominatorTree *DT; 48 49 Query(const DataLayout *DL, const TargetLibraryInfo *tli, 50 const DominatorTree *dt) : DL(DL), TLI(tli), DT(dt) {} 51 }; 52 53 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned); 54 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &, 55 unsigned); 56 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &, 57 unsigned); 58 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned); 59 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned); 60 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned); 61 62 /// getFalse - For a boolean type, or a vector of boolean type, return false, or 63 /// a vector with every element false, as appropriate for the type. 64 static Constant *getFalse(Type *Ty) { 65 assert(Ty->getScalarType()->isIntegerTy(1) && 66 "Expected i1 type or a vector of i1!"); 67 return Constant::getNullValue(Ty); 68 } 69 70 /// getTrue - For a boolean type, or a vector of boolean type, return true, or 71 /// a vector with every element true, as appropriate for the type. 72 static Constant *getTrue(Type *Ty) { 73 assert(Ty->getScalarType()->isIntegerTy(1) && 74 "Expected i1 type or a vector of i1!"); 75 return Constant::getAllOnesValue(Ty); 76 } 77 78 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"? 79 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS, 80 Value *RHS) { 81 CmpInst *Cmp = dyn_cast<CmpInst>(V); 82 if (!Cmp) 83 return false; 84 CmpInst::Predicate CPred = Cmp->getPredicate(); 85 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1); 86 if (CPred == Pred && CLHS == LHS && CRHS == RHS) 87 return true; 88 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS && 89 CRHS == LHS; 90 } 91 92 /// ValueDominatesPHI - Does the given value dominate the specified phi node? 93 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) { 94 Instruction *I = dyn_cast<Instruction>(V); 95 if (!I) 96 // Arguments and constants dominate all instructions. 97 return true; 98 99 // If we are processing instructions (and/or basic blocks) that have not been 100 // fully added to a function, the parent nodes may still be null. Simply 101 // return the conservative answer in these cases. 102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent()) 103 return false; 104 105 // If we have a DominatorTree then do a precise test. 106 if (DT) { 107 if (!DT->isReachableFromEntry(P->getParent())) 108 return true; 109 if (!DT->isReachableFromEntry(I->getParent())) 110 return false; 111 return DT->dominates(I, P); 112 } 113 114 // Otherwise, if the instruction is in the entry block, and is not an invoke, 115 // then it obviously dominates all phi nodes. 116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() && 117 !isa<InvokeInst>(I)) 118 return true; 119 120 return false; 121 } 122 123 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning 124 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is 125 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS. 126 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)". 127 /// Returns the simplified value, or null if no simplification was performed. 128 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS, 129 unsigned OpcToExpand, const Query &Q, 130 unsigned MaxRecurse) { 131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand; 132 // Recursion is always used, so bail out at once if we already hit the limit. 133 if (!MaxRecurse--) 134 return nullptr; 135 136 // Check whether the expression has the form "(A op' B) op C". 137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS)) 138 if (Op0->getOpcode() == OpcodeToExpand) { 139 // It does! Try turning it into "(A op C) op' (B op C)". 140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS; 141 // Do "A op C" and "B op C" both simplify? 142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) 143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 144 // They do! Return "L op' R" if it simplifies or is already available. 145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS. 146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand) 147 && L == B && R == A)) { 148 ++NumExpand; 149 return LHS; 150 } 151 // Otherwise return "L op' R" if it simplifies. 152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 153 ++NumExpand; 154 return V; 155 } 156 } 157 } 158 159 // Check whether the expression has the form "A op (B op' C)". 160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS)) 161 if (Op1->getOpcode() == OpcodeToExpand) { 162 // It does! Try turning it into "(A op B) op' (A op C)". 163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1); 164 // Do "A op B" and "A op C" both simplify? 165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) 166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) { 167 // They do! Return "L op' R" if it simplifies or is already available. 168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS. 169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand) 170 && L == C && R == B)) { 171 ++NumExpand; 172 return RHS; 173 } 174 // Otherwise return "L op' R" if it simplifies. 175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) { 176 ++NumExpand; 177 return V; 178 } 179 } 180 } 181 182 return nullptr; 183 } 184 185 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary 186 /// operations. Returns the simpler value, or null if none was found. 187 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS, 188 const Query &Q, unsigned MaxRecurse) { 189 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc; 190 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!"); 191 192 // Recursion is always used, so bail out at once if we already hit the limit. 193 if (!MaxRecurse--) 194 return nullptr; 195 196 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS); 197 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS); 198 199 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely. 200 if (Op0 && Op0->getOpcode() == Opcode) { 201 Value *A = Op0->getOperand(0); 202 Value *B = Op0->getOperand(1); 203 Value *C = RHS; 204 205 // Does "B op C" simplify? 206 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) { 207 // It does! Return "A op V" if it simplifies or is already available. 208 // If V equals B then "A op V" is just the LHS. 209 if (V == B) return LHS; 210 // Otherwise return "A op V" if it simplifies. 211 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) { 212 ++NumReassoc; 213 return W; 214 } 215 } 216 } 217 218 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely. 219 if (Op1 && Op1->getOpcode() == Opcode) { 220 Value *A = LHS; 221 Value *B = Op1->getOperand(0); 222 Value *C = Op1->getOperand(1); 223 224 // Does "A op B" simplify? 225 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) { 226 // It does! Return "V op C" if it simplifies or is already available. 227 // If V equals B then "V op C" is just the RHS. 228 if (V == B) return RHS; 229 // Otherwise return "V op C" if it simplifies. 230 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) { 231 ++NumReassoc; 232 return W; 233 } 234 } 235 } 236 237 // The remaining transforms require commutativity as well as associativity. 238 if (!Instruction::isCommutative(Opcode)) 239 return nullptr; 240 241 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely. 242 if (Op0 && Op0->getOpcode() == Opcode) { 243 Value *A = Op0->getOperand(0); 244 Value *B = Op0->getOperand(1); 245 Value *C = RHS; 246 247 // Does "C op A" simplify? 248 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 249 // It does! Return "V op B" if it simplifies or is already available. 250 // If V equals A then "V op B" is just the LHS. 251 if (V == A) return LHS; 252 // Otherwise return "V op B" if it simplifies. 253 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) { 254 ++NumReassoc; 255 return W; 256 } 257 } 258 } 259 260 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely. 261 if (Op1 && Op1->getOpcode() == Opcode) { 262 Value *A = LHS; 263 Value *B = Op1->getOperand(0); 264 Value *C = Op1->getOperand(1); 265 266 // Does "C op A" simplify? 267 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) { 268 // It does! Return "B op V" if it simplifies or is already available. 269 // If V equals C then "B op V" is just the RHS. 270 if (V == C) return RHS; 271 // Otherwise return "B op V" if it simplifies. 272 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) { 273 ++NumReassoc; 274 return W; 275 } 276 } 277 } 278 279 return nullptr; 280 } 281 282 /// ThreadBinOpOverSelect - In the case of a binary operation with a select 283 /// instruction as an operand, try to simplify the binop by seeing whether 284 /// evaluating it on both branches of the select results in the same value. 285 /// Returns the common value if so, otherwise returns null. 286 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS, 287 const Query &Q, unsigned MaxRecurse) { 288 // Recursion is always used, so bail out at once if we already hit the limit. 289 if (!MaxRecurse--) 290 return nullptr; 291 292 SelectInst *SI; 293 if (isa<SelectInst>(LHS)) { 294 SI = cast<SelectInst>(LHS); 295 } else { 296 assert(isa<SelectInst>(RHS) && "No select instruction operand!"); 297 SI = cast<SelectInst>(RHS); 298 } 299 300 // Evaluate the BinOp on the true and false branches of the select. 301 Value *TV; 302 Value *FV; 303 if (SI == LHS) { 304 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse); 305 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse); 306 } else { 307 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse); 308 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse); 309 } 310 311 // If they simplified to the same value, then return the common value. 312 // If they both failed to simplify then return null. 313 if (TV == FV) 314 return TV; 315 316 // If one branch simplified to undef, return the other one. 317 if (TV && isa<UndefValue>(TV)) 318 return FV; 319 if (FV && isa<UndefValue>(FV)) 320 return TV; 321 322 // If applying the operation did not change the true and false select values, 323 // then the result of the binop is the select itself. 324 if (TV == SI->getTrueValue() && FV == SI->getFalseValue()) 325 return SI; 326 327 // If one branch simplified and the other did not, and the simplified 328 // value is equal to the unsimplified one, return the simplified value. 329 // For example, select (cond, X, X & Z) & Z -> X & Z. 330 if ((FV && !TV) || (TV && !FV)) { 331 // Check that the simplified value has the form "X op Y" where "op" is the 332 // same as the original operation. 333 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV); 334 if (Simplified && Simplified->getOpcode() == Opcode) { 335 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS". 336 // We already know that "op" is the same as for the simplified value. See 337 // if the operands match too. If so, return the simplified value. 338 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue(); 339 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS; 340 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch; 341 if (Simplified->getOperand(0) == UnsimplifiedLHS && 342 Simplified->getOperand(1) == UnsimplifiedRHS) 343 return Simplified; 344 if (Simplified->isCommutative() && 345 Simplified->getOperand(1) == UnsimplifiedLHS && 346 Simplified->getOperand(0) == UnsimplifiedRHS) 347 return Simplified; 348 } 349 } 350 351 return nullptr; 352 } 353 354 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction, 355 /// try to simplify the comparison by seeing whether both branches of the select 356 /// result in the same value. Returns the common value if so, otherwise returns 357 /// null. 358 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS, 359 Value *RHS, const Query &Q, 360 unsigned MaxRecurse) { 361 // Recursion is always used, so bail out at once if we already hit the limit. 362 if (!MaxRecurse--) 363 return nullptr; 364 365 // Make sure the select is on the LHS. 366 if (!isa<SelectInst>(LHS)) { 367 std::swap(LHS, RHS); 368 Pred = CmpInst::getSwappedPredicate(Pred); 369 } 370 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!"); 371 SelectInst *SI = cast<SelectInst>(LHS); 372 Value *Cond = SI->getCondition(); 373 Value *TV = SI->getTrueValue(); 374 Value *FV = SI->getFalseValue(); 375 376 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it. 377 // Does "cmp TV, RHS" simplify? 378 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse); 379 if (TCmp == Cond) { 380 // It not only simplified, it simplified to the select condition. Replace 381 // it with 'true'. 382 TCmp = getTrue(Cond->getType()); 383 } else if (!TCmp) { 384 // It didn't simplify. However if "cmp TV, RHS" is equal to the select 385 // condition then we can replace it with 'true'. Otherwise give up. 386 if (!isSameCompare(Cond, Pred, TV, RHS)) 387 return nullptr; 388 TCmp = getTrue(Cond->getType()); 389 } 390 391 // Does "cmp FV, RHS" simplify? 392 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse); 393 if (FCmp == Cond) { 394 // It not only simplified, it simplified to the select condition. Replace 395 // it with 'false'. 396 FCmp = getFalse(Cond->getType()); 397 } else if (!FCmp) { 398 // It didn't simplify. However if "cmp FV, RHS" is equal to the select 399 // condition then we can replace it with 'false'. Otherwise give up. 400 if (!isSameCompare(Cond, Pred, FV, RHS)) 401 return nullptr; 402 FCmp = getFalse(Cond->getType()); 403 } 404 405 // If both sides simplified to the same value, then use it as the result of 406 // the original comparison. 407 if (TCmp == FCmp) 408 return TCmp; 409 410 // The remaining cases only make sense if the select condition has the same 411 // type as the result of the comparison, so bail out if this is not so. 412 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy()) 413 return nullptr; 414 // If the false value simplified to false, then the result of the compare 415 // is equal to "Cond && TCmp". This also catches the case when the false 416 // value simplified to false and the true value to true, returning "Cond". 417 if (match(FCmp, m_Zero())) 418 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse)) 419 return V; 420 // If the true value simplified to true, then the result of the compare 421 // is equal to "Cond || FCmp". 422 if (match(TCmp, m_One())) 423 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse)) 424 return V; 425 // Finally, if the false value simplified to true and the true value to 426 // false, then the result of the compare is equal to "!Cond". 427 if (match(FCmp, m_One()) && match(TCmp, m_Zero())) 428 if (Value *V = 429 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()), 430 Q, MaxRecurse)) 431 return V; 432 433 return nullptr; 434 } 435 436 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that 437 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating 438 /// it on the incoming phi values yields the same result for every value. If so 439 /// returns the common value, otherwise returns null. 440 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS, 441 const Query &Q, unsigned MaxRecurse) { 442 // Recursion is always used, so bail out at once if we already hit the limit. 443 if (!MaxRecurse--) 444 return nullptr; 445 446 PHINode *PI; 447 if (isa<PHINode>(LHS)) { 448 PI = cast<PHINode>(LHS); 449 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 450 if (!ValueDominatesPHI(RHS, PI, Q.DT)) 451 return nullptr; 452 } else { 453 assert(isa<PHINode>(RHS) && "No PHI instruction operand!"); 454 PI = cast<PHINode>(RHS); 455 // Bail out if LHS and the phi may be mutually interdependent due to a loop. 456 if (!ValueDominatesPHI(LHS, PI, Q.DT)) 457 return nullptr; 458 } 459 460 // Evaluate the BinOp on the incoming phi values. 461 Value *CommonValue = nullptr; 462 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) { 463 Value *Incoming = PI->getIncomingValue(i); 464 // If the incoming value is the phi node itself, it can safely be skipped. 465 if (Incoming == PI) continue; 466 Value *V = PI == LHS ? 467 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) : 468 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse); 469 // If the operation failed to simplify, or simplified to a different value 470 // to previously, then give up. 471 if (!V || (CommonValue && V != CommonValue)) 472 return nullptr; 473 CommonValue = V; 474 } 475 476 return CommonValue; 477 } 478 479 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try 480 /// try to simplify the comparison by seeing whether comparing with all of the 481 /// incoming phi values yields the same result every time. If so returns the 482 /// common result, otherwise returns null. 483 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS, 484 const Query &Q, unsigned MaxRecurse) { 485 // Recursion is always used, so bail out at once if we already hit the limit. 486 if (!MaxRecurse--) 487 return nullptr; 488 489 // Make sure the phi is on the LHS. 490 if (!isa<PHINode>(LHS)) { 491 std::swap(LHS, RHS); 492 Pred = CmpInst::getSwappedPredicate(Pred); 493 } 494 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!"); 495 PHINode *PI = cast<PHINode>(LHS); 496 497 // Bail out if RHS and the phi may be mutually interdependent due to a loop. 498 if (!ValueDominatesPHI(RHS, PI, Q.DT)) 499 return nullptr; 500 501 // Evaluate the BinOp on the incoming phi values. 502 Value *CommonValue = nullptr; 503 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) { 504 Value *Incoming = PI->getIncomingValue(i); 505 // If the incoming value is the phi node itself, it can safely be skipped. 506 if (Incoming == PI) continue; 507 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse); 508 // If the operation failed to simplify, or simplified to a different value 509 // to previously, then give up. 510 if (!V || (CommonValue && V != CommonValue)) 511 return nullptr; 512 CommonValue = V; 513 } 514 515 return CommonValue; 516 } 517 518 /// SimplifyAddInst - Given operands for an Add, see if we can 519 /// fold the result. If not, this returns null. 520 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 521 const Query &Q, unsigned MaxRecurse) { 522 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 523 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 524 Constant *Ops[] = { CLHS, CRHS }; 525 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops, 526 Q.DL, Q.TLI); 527 } 528 529 // Canonicalize the constant to the RHS. 530 std::swap(Op0, Op1); 531 } 532 533 // X + undef -> undef 534 if (match(Op1, m_Undef())) 535 return Op1; 536 537 // X + 0 -> X 538 if (match(Op1, m_Zero())) 539 return Op0; 540 541 // X + (Y - X) -> Y 542 // (Y - X) + X -> Y 543 // Eg: X + -X -> 0 544 Value *Y = nullptr; 545 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) || 546 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1)))) 547 return Y; 548 549 // X + ~X -> -1 since ~X = -X-1 550 if (match(Op0, m_Not(m_Specific(Op1))) || 551 match(Op1, m_Not(m_Specific(Op0)))) 552 return Constant::getAllOnesValue(Op0->getType()); 553 554 /// i1 add -> xor. 555 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 556 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 557 return V; 558 559 // Try some generic simplifications for associative operations. 560 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, 561 MaxRecurse)) 562 return V; 563 564 // Threading Add over selects and phi nodes is pointless, so don't bother. 565 // Threading over the select in "A + select(cond, B, C)" means evaluating 566 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and 567 // only if B and C are equal. If B and C are equal then (since we assume 568 // that operands have already been simplified) "select(cond, B, C)" should 569 // have been simplified to the common value of B and C already. Analysing 570 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly 571 // for threading over phi nodes. 572 573 return nullptr; 574 } 575 576 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 577 const DataLayout *DL, const TargetLibraryInfo *TLI, 578 const DominatorTree *DT) { 579 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT), 580 RecursionLimit); 581 } 582 583 /// \brief Compute the base pointer and cumulative constant offsets for V. 584 /// 585 /// This strips all constant offsets off of V, leaving it the base pointer, and 586 /// accumulates the total constant offset applied in the returned constant. It 587 /// returns 0 if V is not a pointer, and returns the constant '0' if there are 588 /// no constant offsets applied. 589 /// 590 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't 591 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc. 592 /// folding. 593 static Constant *stripAndComputeConstantOffsets(const DataLayout *DL, 594 Value *&V, 595 bool AllowNonInbounds = false) { 596 assert(V->getType()->getScalarType()->isPointerTy()); 597 598 // Without DataLayout, just be conservative for now. Theoretically, more could 599 // be done in this case. 600 if (!DL) 601 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0); 602 603 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType(); 604 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth()); 605 606 // Even though we don't look through PHI nodes, we could be called on an 607 // instruction in an unreachable block, which may be on a cycle. 608 SmallPtrSet<Value *, 4> Visited; 609 Visited.insert(V); 610 do { 611 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) { 612 if ((!AllowNonInbounds && !GEP->isInBounds()) || 613 !GEP->accumulateConstantOffset(*DL, Offset)) 614 break; 615 V = GEP->getPointerOperand(); 616 } else if (Operator::getOpcode(V) == Instruction::BitCast) { 617 V = cast<Operator>(V)->getOperand(0); 618 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) { 619 if (GA->mayBeOverridden()) 620 break; 621 V = GA->getAliasee(); 622 } else { 623 break; 624 } 625 assert(V->getType()->getScalarType()->isPointerTy() && 626 "Unexpected operand type!"); 627 } while (Visited.insert(V)); 628 629 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset); 630 if (V->getType()->isVectorTy()) 631 return ConstantVector::getSplat(V->getType()->getVectorNumElements(), 632 OffsetIntPtr); 633 return OffsetIntPtr; 634 } 635 636 /// \brief Compute the constant difference between two pointer values. 637 /// If the difference is not a constant, returns zero. 638 static Constant *computePointerDifference(const DataLayout *DL, 639 Value *LHS, Value *RHS) { 640 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 641 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 642 643 // If LHS and RHS are not related via constant offsets to the same base 644 // value, there is nothing we can do here. 645 if (LHS != RHS) 646 return nullptr; 647 648 // Otherwise, the difference of LHS - RHS can be computed as: 649 // LHS - RHS 650 // = (LHSOffset + Base) - (RHSOffset + Base) 651 // = LHSOffset - RHSOffset 652 return ConstantExpr::getSub(LHSOffset, RHSOffset); 653 } 654 655 /// SimplifySubInst - Given operands for a Sub, see if we can 656 /// fold the result. If not, this returns null. 657 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 658 const Query &Q, unsigned MaxRecurse) { 659 if (Constant *CLHS = dyn_cast<Constant>(Op0)) 660 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 661 Constant *Ops[] = { CLHS, CRHS }; 662 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(), 663 Ops, Q.DL, Q.TLI); 664 } 665 666 // X - undef -> undef 667 // undef - X -> undef 668 if (match(Op0, m_Undef()) || match(Op1, m_Undef())) 669 return UndefValue::get(Op0->getType()); 670 671 // X - 0 -> X 672 if (match(Op1, m_Zero())) 673 return Op0; 674 675 // X - X -> 0 676 if (Op0 == Op1) 677 return Constant::getNullValue(Op0->getType()); 678 679 // X - (0 - Y) -> X if the second sub is NUW. 680 // If Y != 0, 0 - Y is a poison value. 681 // If Y == 0, 0 - Y simplifies to 0. 682 if (BinaryOperator::isNeg(Op1)) { 683 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) { 684 assert(BO->getOpcode() == Instruction::Sub && 685 "Expected a subtraction operator!"); 686 if (BO->hasNoUnsignedWrap()) 687 return Op0; 688 } 689 } 690 691 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies. 692 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X 693 Value *X = nullptr, *Y = nullptr, *Z = Op1; 694 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z 695 // See if "V === Y - Z" simplifies. 696 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1)) 697 // It does! Now see if "X + V" simplifies. 698 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) { 699 // It does, we successfully reassociated! 700 ++NumReassoc; 701 return W; 702 } 703 // See if "V === X - Z" simplifies. 704 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 705 // It does! Now see if "Y + V" simplifies. 706 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) { 707 // It does, we successfully reassociated! 708 ++NumReassoc; 709 return W; 710 } 711 } 712 713 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies. 714 // For example, X - (X + 1) -> -1 715 X = Op0; 716 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z) 717 // See if "V === X - Y" simplifies. 718 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 719 // It does! Now see if "V - Z" simplifies. 720 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) { 721 // It does, we successfully reassociated! 722 ++NumReassoc; 723 return W; 724 } 725 // See if "V === X - Z" simplifies. 726 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1)) 727 // It does! Now see if "V - Y" simplifies. 728 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) { 729 // It does, we successfully reassociated! 730 ++NumReassoc; 731 return W; 732 } 733 } 734 735 // Z - (X - Y) -> (Z - X) + Y if everything simplifies. 736 // For example, X - (X - Y) -> Y. 737 Z = Op0; 738 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y) 739 // See if "V === Z - X" simplifies. 740 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1)) 741 // It does! Now see if "V + Y" simplifies. 742 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) { 743 // It does, we successfully reassociated! 744 ++NumReassoc; 745 return W; 746 } 747 748 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies. 749 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) && 750 match(Op1, m_Trunc(m_Value(Y)))) 751 if (X->getType() == Y->getType()) 752 // See if "V === X - Y" simplifies. 753 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1)) 754 // It does! Now see if "trunc V" simplifies. 755 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1)) 756 // It does, return the simplified "trunc V". 757 return W; 758 759 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...). 760 if (match(Op0, m_PtrToInt(m_Value(X))) && 761 match(Op1, m_PtrToInt(m_Value(Y)))) 762 if (Constant *Result = computePointerDifference(Q.DL, X, Y)) 763 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true); 764 765 // i1 sub -> xor. 766 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 767 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1)) 768 return V; 769 770 // Threading Sub over selects and phi nodes is pointless, so don't bother. 771 // Threading over the select in "A - select(cond, B, C)" means evaluating 772 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and 773 // only if B and C are equal. If B and C are equal then (since we assume 774 // that operands have already been simplified) "select(cond, B, C)" should 775 // have been simplified to the common value of B and C already. Analysing 776 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly 777 // for threading over phi nodes. 778 779 return nullptr; 780 } 781 782 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 783 const DataLayout *DL, const TargetLibraryInfo *TLI, 784 const DominatorTree *DT) { 785 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT), 786 RecursionLimit); 787 } 788 789 /// Given operands for an FAdd, see if we can fold the result. If not, this 790 /// returns null. 791 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 792 const Query &Q, unsigned MaxRecurse) { 793 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 794 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 795 Constant *Ops[] = { CLHS, CRHS }; 796 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(), 797 Ops, Q.DL, Q.TLI); 798 } 799 800 // Canonicalize the constant to the RHS. 801 std::swap(Op0, Op1); 802 } 803 804 // fadd X, -0 ==> X 805 if (match(Op1, m_NegZero())) 806 return Op0; 807 808 // fadd X, 0 ==> X, when we know X is not -0 809 if (match(Op1, m_Zero()) && 810 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0))) 811 return Op0; 812 813 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0 814 // where nnan and ninf have to occur at least once somewhere in this 815 // expression 816 Value *SubOp = nullptr; 817 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0)))) 818 SubOp = Op1; 819 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1)))) 820 SubOp = Op0; 821 if (SubOp) { 822 Instruction *FSub = cast<Instruction>(SubOp); 823 if ((FMF.noNaNs() || FSub->hasNoNaNs()) && 824 (FMF.noInfs() || FSub->hasNoInfs())) 825 return Constant::getNullValue(Op0->getType()); 826 } 827 828 return nullptr; 829 } 830 831 /// Given operands for an FSub, see if we can fold the result. If not, this 832 /// returns null. 833 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 834 const Query &Q, unsigned MaxRecurse) { 835 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 836 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 837 Constant *Ops[] = { CLHS, CRHS }; 838 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(), 839 Ops, Q.DL, Q.TLI); 840 } 841 } 842 843 // fsub X, 0 ==> X 844 if (match(Op1, m_Zero())) 845 return Op0; 846 847 // fsub X, -0 ==> X, when we know X is not -0 848 if (match(Op1, m_NegZero()) && 849 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0))) 850 return Op0; 851 852 // fsub 0, (fsub -0.0, X) ==> X 853 Value *X; 854 if (match(Op0, m_AnyZero())) { 855 if (match(Op1, m_FSub(m_NegZero(), m_Value(X)))) 856 return X; 857 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X)))) 858 return X; 859 } 860 861 // fsub nnan ninf x, x ==> 0.0 862 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1) 863 return Constant::getNullValue(Op0->getType()); 864 865 return nullptr; 866 } 867 868 /// Given the operands for an FMul, see if we can fold the result 869 static Value *SimplifyFMulInst(Value *Op0, Value *Op1, 870 FastMathFlags FMF, 871 const Query &Q, 872 unsigned MaxRecurse) { 873 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 874 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 875 Constant *Ops[] = { CLHS, CRHS }; 876 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(), 877 Ops, Q.DL, Q.TLI); 878 } 879 880 // Canonicalize the constant to the RHS. 881 std::swap(Op0, Op1); 882 } 883 884 // fmul X, 1.0 ==> X 885 if (match(Op1, m_FPOne())) 886 return Op0; 887 888 // fmul nnan nsz X, 0 ==> 0 889 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero())) 890 return Op1; 891 892 return nullptr; 893 } 894 895 /// SimplifyMulInst - Given operands for a Mul, see if we can 896 /// fold the result. If not, this returns null. 897 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q, 898 unsigned MaxRecurse) { 899 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 900 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 901 Constant *Ops[] = { CLHS, CRHS }; 902 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(), 903 Ops, Q.DL, Q.TLI); 904 } 905 906 // Canonicalize the constant to the RHS. 907 std::swap(Op0, Op1); 908 } 909 910 // X * undef -> 0 911 if (match(Op1, m_Undef())) 912 return Constant::getNullValue(Op0->getType()); 913 914 // X * 0 -> 0 915 if (match(Op1, m_Zero())) 916 return Op1; 917 918 // X * 1 -> X 919 if (match(Op1, m_One())) 920 return Op0; 921 922 // (X / Y) * Y -> X if the division is exact. 923 Value *X = nullptr; 924 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y 925 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y) 926 return X; 927 928 // i1 mul -> and. 929 if (MaxRecurse && Op0->getType()->isIntegerTy(1)) 930 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1)) 931 return V; 932 933 // Try some generic simplifications for associative operations. 934 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, 935 MaxRecurse)) 936 return V; 937 938 // Mul distributes over Add. Try some generic simplifications based on this. 939 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add, 940 Q, MaxRecurse)) 941 return V; 942 943 // If the operation is with the result of a select instruction, check whether 944 // operating on either branch of the select always yields the same value. 945 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 946 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, 947 MaxRecurse)) 948 return V; 949 950 // If the operation is with the result of a phi instruction, check whether 951 // operating on all incoming values of the phi always yields the same value. 952 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 953 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, 954 MaxRecurse)) 955 return V; 956 957 return nullptr; 958 } 959 960 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF, 961 const DataLayout *DL, const TargetLibraryInfo *TLI, 962 const DominatorTree *DT) { 963 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit); 964 } 965 966 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF, 967 const DataLayout *DL, const TargetLibraryInfo *TLI, 968 const DominatorTree *DT) { 969 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit); 970 } 971 972 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, 973 FastMathFlags FMF, 974 const DataLayout *DL, 975 const TargetLibraryInfo *TLI, 976 const DominatorTree *DT) { 977 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit); 978 } 979 980 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL, 981 const TargetLibraryInfo *TLI, 982 const DominatorTree *DT) { 983 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 984 } 985 986 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can 987 /// fold the result. If not, this returns null. 988 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 989 const Query &Q, unsigned MaxRecurse) { 990 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 991 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 992 Constant *Ops[] = { C0, C1 }; 993 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI); 994 } 995 } 996 997 bool isSigned = Opcode == Instruction::SDiv; 998 999 // X / undef -> undef 1000 if (match(Op1, m_Undef())) 1001 return Op1; 1002 1003 // undef / X -> 0 1004 if (match(Op0, m_Undef())) 1005 return Constant::getNullValue(Op0->getType()); 1006 1007 // 0 / X -> 0, we don't need to preserve faults! 1008 if (match(Op0, m_Zero())) 1009 return Op0; 1010 1011 // X / 1 -> X 1012 if (match(Op1, m_One())) 1013 return Op0; 1014 1015 if (Op0->getType()->isIntegerTy(1)) 1016 // It can't be division by zero, hence it must be division by one. 1017 return Op0; 1018 1019 // X / X -> 1 1020 if (Op0 == Op1) 1021 return ConstantInt::get(Op0->getType(), 1); 1022 1023 // (X * Y) / Y -> X if the multiplication does not overflow. 1024 Value *X = nullptr, *Y = nullptr; 1025 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) { 1026 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1 1027 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0); 1028 // If the Mul knows it does not overflow, then we are good to go. 1029 if ((isSigned && Mul->hasNoSignedWrap()) || 1030 (!isSigned && Mul->hasNoUnsignedWrap())) 1031 return X; 1032 // If X has the form X = A / Y then X * Y cannot overflow. 1033 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X)) 1034 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y) 1035 return X; 1036 } 1037 1038 // (X rem Y) / Y -> 0 1039 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) || 1040 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1))))) 1041 return Constant::getNullValue(Op0->getType()); 1042 1043 // If the operation is with the result of a select instruction, check whether 1044 // operating on either branch of the select always yields the same value. 1045 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1046 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1047 return V; 1048 1049 // If the operation is with the result of a phi instruction, check whether 1050 // operating on all incoming values of the phi always yields the same value. 1051 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1052 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1053 return V; 1054 1055 return nullptr; 1056 } 1057 1058 /// SimplifySDivInst - Given operands for an SDiv, see if we can 1059 /// fold the result. If not, this returns null. 1060 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q, 1061 unsigned MaxRecurse) { 1062 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse)) 1063 return V; 1064 1065 return nullptr; 1066 } 1067 1068 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL, 1069 const TargetLibraryInfo *TLI, 1070 const DominatorTree *DT) { 1071 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1072 } 1073 1074 /// SimplifyUDivInst - Given operands for a UDiv, see if we can 1075 /// fold the result. If not, this returns null. 1076 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q, 1077 unsigned MaxRecurse) { 1078 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse)) 1079 return V; 1080 1081 return nullptr; 1082 } 1083 1084 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL, 1085 const TargetLibraryInfo *TLI, 1086 const DominatorTree *DT) { 1087 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1088 } 1089 1090 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q, 1091 unsigned) { 1092 // undef / X -> undef (the undef could be a snan). 1093 if (match(Op0, m_Undef())) 1094 return Op0; 1095 1096 // X / undef -> undef 1097 if (match(Op1, m_Undef())) 1098 return Op1; 1099 1100 return nullptr; 1101 } 1102 1103 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL, 1104 const TargetLibraryInfo *TLI, 1105 const DominatorTree *DT) { 1106 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1107 } 1108 1109 /// SimplifyRem - Given operands for an SRem or URem, see if we can 1110 /// fold the result. If not, this returns null. 1111 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1, 1112 const Query &Q, unsigned MaxRecurse) { 1113 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 1114 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 1115 Constant *Ops[] = { C0, C1 }; 1116 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI); 1117 } 1118 } 1119 1120 // X % undef -> undef 1121 if (match(Op1, m_Undef())) 1122 return Op1; 1123 1124 // undef % X -> 0 1125 if (match(Op0, m_Undef())) 1126 return Constant::getNullValue(Op0->getType()); 1127 1128 // 0 % X -> 0, we don't need to preserve faults! 1129 if (match(Op0, m_Zero())) 1130 return Op0; 1131 1132 // X % 0 -> undef, we don't need to preserve faults! 1133 if (match(Op1, m_Zero())) 1134 return UndefValue::get(Op0->getType()); 1135 1136 // X % 1 -> 0 1137 if (match(Op1, m_One())) 1138 return Constant::getNullValue(Op0->getType()); 1139 1140 if (Op0->getType()->isIntegerTy(1)) 1141 // It can't be remainder by zero, hence it must be remainder by one. 1142 return Constant::getNullValue(Op0->getType()); 1143 1144 // X % X -> 0 1145 if (Op0 == Op1) 1146 return Constant::getNullValue(Op0->getType()); 1147 1148 // If the operation is with the result of a select instruction, check whether 1149 // operating on either branch of the select always yields the same value. 1150 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1151 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1152 return V; 1153 1154 // If the operation is with the result of a phi instruction, check whether 1155 // operating on all incoming values of the phi always yields the same value. 1156 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1157 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1158 return V; 1159 1160 return nullptr; 1161 } 1162 1163 /// SimplifySRemInst - Given operands for an SRem, see if we can 1164 /// fold the result. If not, this returns null. 1165 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q, 1166 unsigned MaxRecurse) { 1167 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse)) 1168 return V; 1169 1170 return nullptr; 1171 } 1172 1173 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL, 1174 const TargetLibraryInfo *TLI, 1175 const DominatorTree *DT) { 1176 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1177 } 1178 1179 /// SimplifyURemInst - Given operands for a URem, see if we can 1180 /// fold the result. If not, this returns null. 1181 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q, 1182 unsigned MaxRecurse) { 1183 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse)) 1184 return V; 1185 1186 return nullptr; 1187 } 1188 1189 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL, 1190 const TargetLibraryInfo *TLI, 1191 const DominatorTree *DT) { 1192 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1193 } 1194 1195 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &, 1196 unsigned) { 1197 // undef % X -> undef (the undef could be a snan). 1198 if (match(Op0, m_Undef())) 1199 return Op0; 1200 1201 // X % undef -> undef 1202 if (match(Op1, m_Undef())) 1203 return Op1; 1204 1205 return nullptr; 1206 } 1207 1208 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL, 1209 const TargetLibraryInfo *TLI, 1210 const DominatorTree *DT) { 1211 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1212 } 1213 1214 /// isUndefShift - Returns true if a shift by \c Amount always yields undef. 1215 static bool isUndefShift(Value *Amount) { 1216 Constant *C = dyn_cast<Constant>(Amount); 1217 if (!C) 1218 return false; 1219 1220 // X shift by undef -> undef because it may shift by the bitwidth. 1221 if (isa<UndefValue>(C)) 1222 return true; 1223 1224 // Shifting by the bitwidth or more is undefined. 1225 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) 1226 if (CI->getValue().getLimitedValue() >= 1227 CI->getType()->getScalarSizeInBits()) 1228 return true; 1229 1230 // If all lanes of a vector shift are undefined the whole shift is. 1231 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) { 1232 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I) 1233 if (!isUndefShift(C->getAggregateElement(I))) 1234 return false; 1235 return true; 1236 } 1237 1238 return false; 1239 } 1240 1241 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can 1242 /// fold the result. If not, this returns null. 1243 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1, 1244 const Query &Q, unsigned MaxRecurse) { 1245 if (Constant *C0 = dyn_cast<Constant>(Op0)) { 1246 if (Constant *C1 = dyn_cast<Constant>(Op1)) { 1247 Constant *Ops[] = { C0, C1 }; 1248 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI); 1249 } 1250 } 1251 1252 // 0 shift by X -> 0 1253 if (match(Op0, m_Zero())) 1254 return Op0; 1255 1256 // X shift by 0 -> X 1257 if (match(Op1, m_Zero())) 1258 return Op0; 1259 1260 // Fold undefined shifts. 1261 if (isUndefShift(Op1)) 1262 return UndefValue::get(Op0->getType()); 1263 1264 // If the operation is with the result of a select instruction, check whether 1265 // operating on either branch of the select always yields the same value. 1266 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1267 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse)) 1268 return V; 1269 1270 // If the operation is with the result of a phi instruction, check whether 1271 // operating on all incoming values of the phi always yields the same value. 1272 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1273 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse)) 1274 return V; 1275 1276 return nullptr; 1277 } 1278 1279 /// SimplifyShlInst - Given operands for an Shl, see if we can 1280 /// fold the result. If not, this returns null. 1281 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1282 const Query &Q, unsigned MaxRecurse) { 1283 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse)) 1284 return V; 1285 1286 // undef << X -> 0 1287 if (match(Op0, m_Undef())) 1288 return Constant::getNullValue(Op0->getType()); 1289 1290 // (X >> A) << A -> X 1291 Value *X; 1292 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1))))) 1293 return X; 1294 return nullptr; 1295 } 1296 1297 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW, 1298 const DataLayout *DL, const TargetLibraryInfo *TLI, 1299 const DominatorTree *DT) { 1300 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT), 1301 RecursionLimit); 1302 } 1303 1304 /// SimplifyLShrInst - Given operands for an LShr, see if we can 1305 /// fold the result. If not, this returns null. 1306 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1307 const Query &Q, unsigned MaxRecurse) { 1308 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse)) 1309 return V; 1310 1311 // X >> X -> 0 1312 if (Op0 == Op1) 1313 return Constant::getNullValue(Op0->getType()); 1314 1315 // undef >>l X -> 0 1316 if (match(Op0, m_Undef())) 1317 return Constant::getNullValue(Op0->getType()); 1318 1319 // (X << A) >> A -> X 1320 Value *X; 1321 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) && 1322 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap()) 1323 return X; 1324 1325 return nullptr; 1326 } 1327 1328 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact, 1329 const DataLayout *DL, 1330 const TargetLibraryInfo *TLI, 1331 const DominatorTree *DT) { 1332 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT), 1333 RecursionLimit); 1334 } 1335 1336 /// SimplifyAShrInst - Given operands for an AShr, see if we can 1337 /// fold the result. If not, this returns null. 1338 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1339 const Query &Q, unsigned MaxRecurse) { 1340 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse)) 1341 return V; 1342 1343 // X >> X -> 0 1344 if (Op0 == Op1) 1345 return Constant::getNullValue(Op0->getType()); 1346 1347 // all ones >>a X -> all ones 1348 if (match(Op0, m_AllOnes())) 1349 return Op0; 1350 1351 // undef >>a X -> all ones 1352 if (match(Op0, m_Undef())) 1353 return Constant::getAllOnesValue(Op0->getType()); 1354 1355 // (X << A) >> A -> X 1356 Value *X; 1357 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) && 1358 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap()) 1359 return X; 1360 1361 // Arithmetic shifting an all-sign-bit value is a no-op. 1362 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL); 1363 if (NumSignBits == Op0->getType()->getScalarSizeInBits()) 1364 return Op0; 1365 1366 return nullptr; 1367 } 1368 1369 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact, 1370 const DataLayout *DL, 1371 const TargetLibraryInfo *TLI, 1372 const DominatorTree *DT) { 1373 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT), 1374 RecursionLimit); 1375 } 1376 1377 /// SimplifyAndInst - Given operands for an And, see if we can 1378 /// fold the result. If not, this returns null. 1379 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q, 1380 unsigned MaxRecurse) { 1381 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 1382 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 1383 Constant *Ops[] = { CLHS, CRHS }; 1384 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(), 1385 Ops, Q.DL, Q.TLI); 1386 } 1387 1388 // Canonicalize the constant to the RHS. 1389 std::swap(Op0, Op1); 1390 } 1391 1392 // X & undef -> 0 1393 if (match(Op1, m_Undef())) 1394 return Constant::getNullValue(Op0->getType()); 1395 1396 // X & X = X 1397 if (Op0 == Op1) 1398 return Op0; 1399 1400 // X & 0 = 0 1401 if (match(Op1, m_Zero())) 1402 return Op1; 1403 1404 // X & -1 = X 1405 if (match(Op1, m_AllOnes())) 1406 return Op0; 1407 1408 // A & ~A = ~A & A = 0 1409 if (match(Op0, m_Not(m_Specific(Op1))) || 1410 match(Op1, m_Not(m_Specific(Op0)))) 1411 return Constant::getNullValue(Op0->getType()); 1412 1413 // (A | ?) & A = A 1414 Value *A = nullptr, *B = nullptr; 1415 if (match(Op0, m_Or(m_Value(A), m_Value(B))) && 1416 (A == Op1 || B == Op1)) 1417 return Op1; 1418 1419 // A & (A | ?) = A 1420 if (match(Op1, m_Or(m_Value(A), m_Value(B))) && 1421 (A == Op0 || B == Op0)) 1422 return Op0; 1423 1424 // A & (-A) = A if A is a power of two or zero. 1425 if (match(Op0, m_Neg(m_Specific(Op1))) || 1426 match(Op1, m_Neg(m_Specific(Op0)))) { 1427 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true)) 1428 return Op0; 1429 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true)) 1430 return Op1; 1431 } 1432 1433 // Try some generic simplifications for associative operations. 1434 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, 1435 MaxRecurse)) 1436 return V; 1437 1438 // And distributes over Or. Try some generic simplifications based on this. 1439 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or, 1440 Q, MaxRecurse)) 1441 return V; 1442 1443 // And distributes over Xor. Try some generic simplifications based on this. 1444 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor, 1445 Q, MaxRecurse)) 1446 return V; 1447 1448 // If the operation is with the result of a select instruction, check whether 1449 // operating on either branch of the select always yields the same value. 1450 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1451 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q, 1452 MaxRecurse)) 1453 return V; 1454 1455 // If the operation is with the result of a phi instruction, check whether 1456 // operating on all incoming values of the phi always yields the same value. 1457 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1458 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q, 1459 MaxRecurse)) 1460 return V; 1461 1462 return nullptr; 1463 } 1464 1465 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL, 1466 const TargetLibraryInfo *TLI, 1467 const DominatorTree *DT) { 1468 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1469 } 1470 1471 /// SimplifyOrInst - Given operands for an Or, see if we can 1472 /// fold the result. If not, this returns null. 1473 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q, 1474 unsigned MaxRecurse) { 1475 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 1476 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 1477 Constant *Ops[] = { CLHS, CRHS }; 1478 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(), 1479 Ops, Q.DL, Q.TLI); 1480 } 1481 1482 // Canonicalize the constant to the RHS. 1483 std::swap(Op0, Op1); 1484 } 1485 1486 // X | undef -> -1 1487 if (match(Op1, m_Undef())) 1488 return Constant::getAllOnesValue(Op0->getType()); 1489 1490 // X | X = X 1491 if (Op0 == Op1) 1492 return Op0; 1493 1494 // X | 0 = X 1495 if (match(Op1, m_Zero())) 1496 return Op0; 1497 1498 // X | -1 = -1 1499 if (match(Op1, m_AllOnes())) 1500 return Op1; 1501 1502 // A | ~A = ~A | A = -1 1503 if (match(Op0, m_Not(m_Specific(Op1))) || 1504 match(Op1, m_Not(m_Specific(Op0)))) 1505 return Constant::getAllOnesValue(Op0->getType()); 1506 1507 // (A & ?) | A = A 1508 Value *A = nullptr, *B = nullptr; 1509 if (match(Op0, m_And(m_Value(A), m_Value(B))) && 1510 (A == Op1 || B == Op1)) 1511 return Op1; 1512 1513 // A | (A & ?) = A 1514 if (match(Op1, m_And(m_Value(A), m_Value(B))) && 1515 (A == Op0 || B == Op0)) 1516 return Op0; 1517 1518 // ~(A & ?) | A = -1 1519 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) && 1520 (A == Op1 || B == Op1)) 1521 return Constant::getAllOnesValue(Op1->getType()); 1522 1523 // A | ~(A & ?) = -1 1524 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) && 1525 (A == Op0 || B == Op0)) 1526 return Constant::getAllOnesValue(Op0->getType()); 1527 1528 // Try some generic simplifications for associative operations. 1529 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, 1530 MaxRecurse)) 1531 return V; 1532 1533 // Or distributes over And. Try some generic simplifications based on this. 1534 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q, 1535 MaxRecurse)) 1536 return V; 1537 1538 // If the operation is with the result of a select instruction, check whether 1539 // operating on either branch of the select always yields the same value. 1540 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) 1541 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, 1542 MaxRecurse)) 1543 return V; 1544 1545 // (A & C)|(B & D) 1546 Value *C = nullptr, *D = nullptr; 1547 if (match(Op0, m_And(m_Value(A), m_Value(C))) && 1548 match(Op1, m_And(m_Value(B), m_Value(D)))) { 1549 ConstantInt *C1 = dyn_cast<ConstantInt>(C); 1550 ConstantInt *C2 = dyn_cast<ConstantInt>(D); 1551 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) { 1552 // (A & C1)|(B & C2) 1553 // If we have: ((V + N) & C1) | (V & C2) 1554 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0 1555 // replace with V+N. 1556 Value *V1, *V2; 1557 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+ 1558 match(A, m_Add(m_Value(V1), m_Value(V2)))) { 1559 // Add commutes, try both ways. 1560 if (V1 == B && MaskedValueIsZero(V2, C2->getValue())) 1561 return A; 1562 if (V2 == B && MaskedValueIsZero(V1, C2->getValue())) 1563 return A; 1564 } 1565 // Or commutes, try both ways. 1566 if ((C1->getValue() & (C1->getValue() + 1)) == 0 && 1567 match(B, m_Add(m_Value(V1), m_Value(V2)))) { 1568 // Add commutes, try both ways. 1569 if (V1 == A && MaskedValueIsZero(V2, C1->getValue())) 1570 return B; 1571 if (V2 == A && MaskedValueIsZero(V1, C1->getValue())) 1572 return B; 1573 } 1574 } 1575 } 1576 1577 // If the operation is with the result of a phi instruction, check whether 1578 // operating on all incoming values of the phi always yields the same value. 1579 if (isa<PHINode>(Op0) || isa<PHINode>(Op1)) 1580 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse)) 1581 return V; 1582 1583 return nullptr; 1584 } 1585 1586 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL, 1587 const TargetLibraryInfo *TLI, 1588 const DominatorTree *DT) { 1589 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1590 } 1591 1592 /// SimplifyXorInst - Given operands for a Xor, see if we can 1593 /// fold the result. If not, this returns null. 1594 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q, 1595 unsigned MaxRecurse) { 1596 if (Constant *CLHS = dyn_cast<Constant>(Op0)) { 1597 if (Constant *CRHS = dyn_cast<Constant>(Op1)) { 1598 Constant *Ops[] = { CLHS, CRHS }; 1599 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(), 1600 Ops, Q.DL, Q.TLI); 1601 } 1602 1603 // Canonicalize the constant to the RHS. 1604 std::swap(Op0, Op1); 1605 } 1606 1607 // A ^ undef -> undef 1608 if (match(Op1, m_Undef())) 1609 return Op1; 1610 1611 // A ^ 0 = A 1612 if (match(Op1, m_Zero())) 1613 return Op0; 1614 1615 // A ^ A = 0 1616 if (Op0 == Op1) 1617 return Constant::getNullValue(Op0->getType()); 1618 1619 // A ^ ~A = ~A ^ A = -1 1620 if (match(Op0, m_Not(m_Specific(Op1))) || 1621 match(Op1, m_Not(m_Specific(Op0)))) 1622 return Constant::getAllOnesValue(Op0->getType()); 1623 1624 // Try some generic simplifications for associative operations. 1625 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, 1626 MaxRecurse)) 1627 return V; 1628 1629 // Threading Xor over selects and phi nodes is pointless, so don't bother. 1630 // Threading over the select in "A ^ select(cond, B, C)" means evaluating 1631 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and 1632 // only if B and C are equal. If B and C are equal then (since we assume 1633 // that operands have already been simplified) "select(cond, B, C)" should 1634 // have been simplified to the common value of B and C already. Analysing 1635 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly 1636 // for threading over phi nodes. 1637 1638 return nullptr; 1639 } 1640 1641 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL, 1642 const TargetLibraryInfo *TLI, 1643 const DominatorTree *DT) { 1644 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit); 1645 } 1646 1647 static Type *GetCompareTy(Value *Op) { 1648 return CmpInst::makeCmpResultType(Op->getType()); 1649 } 1650 1651 /// ExtractEquivalentCondition - Rummage around inside V looking for something 1652 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found, 1653 /// otherwise return null. Helper function for analyzing max/min idioms. 1654 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred, 1655 Value *LHS, Value *RHS) { 1656 SelectInst *SI = dyn_cast<SelectInst>(V); 1657 if (!SI) 1658 return nullptr; 1659 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition()); 1660 if (!Cmp) 1661 return nullptr; 1662 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1); 1663 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS) 1664 return Cmp; 1665 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) && 1666 LHS == CmpRHS && RHS == CmpLHS) 1667 return Cmp; 1668 return nullptr; 1669 } 1670 1671 // A significant optimization not implemented here is assuming that alloca 1672 // addresses are not equal to incoming argument values. They don't *alias*, 1673 // as we say, but that doesn't mean they aren't equal, so we take a 1674 // conservative approach. 1675 // 1676 // This is inspired in part by C++11 5.10p1: 1677 // "Two pointers of the same type compare equal if and only if they are both 1678 // null, both point to the same function, or both represent the same 1679 // address." 1680 // 1681 // This is pretty permissive. 1682 // 1683 // It's also partly due to C11 6.5.9p6: 1684 // "Two pointers compare equal if and only if both are null pointers, both are 1685 // pointers to the same object (including a pointer to an object and a 1686 // subobject at its beginning) or function, both are pointers to one past the 1687 // last element of the same array object, or one is a pointer to one past the 1688 // end of one array object and the other is a pointer to the start of a 1689 // different array object that happens to immediately follow the first array 1690 // object in the address space.) 1691 // 1692 // C11's version is more restrictive, however there's no reason why an argument 1693 // couldn't be a one-past-the-end value for a stack object in the caller and be 1694 // equal to the beginning of a stack object in the callee. 1695 // 1696 // If the C and C++ standards are ever made sufficiently restrictive in this 1697 // area, it may be possible to update LLVM's semantics accordingly and reinstate 1698 // this optimization. 1699 static Constant *computePointerICmp(const DataLayout *DL, 1700 const TargetLibraryInfo *TLI, 1701 CmpInst::Predicate Pred, 1702 Value *LHS, Value *RHS) { 1703 // First, skip past any trivial no-ops. 1704 LHS = LHS->stripPointerCasts(); 1705 RHS = RHS->stripPointerCasts(); 1706 1707 // A non-null pointer is not equal to a null pointer. 1708 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) && 1709 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE)) 1710 return ConstantInt::get(GetCompareTy(LHS), 1711 !CmpInst::isTrueWhenEqual(Pred)); 1712 1713 // We can only fold certain predicates on pointer comparisons. 1714 switch (Pred) { 1715 default: 1716 return nullptr; 1717 1718 // Equality comaprisons are easy to fold. 1719 case CmpInst::ICMP_EQ: 1720 case CmpInst::ICMP_NE: 1721 break; 1722 1723 // We can only handle unsigned relational comparisons because 'inbounds' on 1724 // a GEP only protects against unsigned wrapping. 1725 case CmpInst::ICMP_UGT: 1726 case CmpInst::ICMP_UGE: 1727 case CmpInst::ICMP_ULT: 1728 case CmpInst::ICMP_ULE: 1729 // However, we have to switch them to their signed variants to handle 1730 // negative indices from the base pointer. 1731 Pred = ICmpInst::getSignedPredicate(Pred); 1732 break; 1733 } 1734 1735 // Strip off any constant offsets so that we can reason about them. 1736 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets 1737 // here and compare base addresses like AliasAnalysis does, however there are 1738 // numerous hazards. AliasAnalysis and its utilities rely on special rules 1739 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis 1740 // doesn't need to guarantee pointer inequality when it says NoAlias. 1741 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS); 1742 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS); 1743 1744 // If LHS and RHS are related via constant offsets to the same base 1745 // value, we can replace it with an icmp which just compares the offsets. 1746 if (LHS == RHS) 1747 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset); 1748 1749 // Various optimizations for (in)equality comparisons. 1750 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) { 1751 // Different non-empty allocations that exist at the same time have 1752 // different addresses (if the program can tell). Global variables always 1753 // exist, so they always exist during the lifetime of each other and all 1754 // allocas. Two different allocas usually have different addresses... 1755 // 1756 // However, if there's an @llvm.stackrestore dynamically in between two 1757 // allocas, they may have the same address. It's tempting to reduce the 1758 // scope of the problem by only looking at *static* allocas here. That would 1759 // cover the majority of allocas while significantly reducing the likelihood 1760 // of having an @llvm.stackrestore pop up in the middle. However, it's not 1761 // actually impossible for an @llvm.stackrestore to pop up in the middle of 1762 // an entry block. Also, if we have a block that's not attached to a 1763 // function, we can't tell if it's "static" under the current definition. 1764 // Theoretically, this problem could be fixed by creating a new kind of 1765 // instruction kind specifically for static allocas. Such a new instruction 1766 // could be required to be at the top of the entry block, thus preventing it 1767 // from being subject to a @llvm.stackrestore. Instcombine could even 1768 // convert regular allocas into these special allocas. It'd be nifty. 1769 // However, until then, this problem remains open. 1770 // 1771 // So, we'll assume that two non-empty allocas have different addresses 1772 // for now. 1773 // 1774 // With all that, if the offsets are within the bounds of their allocations 1775 // (and not one-past-the-end! so we can't use inbounds!), and their 1776 // allocations aren't the same, the pointers are not equal. 1777 // 1778 // Note that it's not necessary to check for LHS being a global variable 1779 // address, due to canonicalization and constant folding. 1780 if (isa<AllocaInst>(LHS) && 1781 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) { 1782 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset); 1783 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset); 1784 uint64_t LHSSize, RHSSize; 1785 if (LHSOffsetCI && RHSOffsetCI && 1786 getObjectSize(LHS, LHSSize, DL, TLI) && 1787 getObjectSize(RHS, RHSSize, DL, TLI)) { 1788 const APInt &LHSOffsetValue = LHSOffsetCI->getValue(); 1789 const APInt &RHSOffsetValue = RHSOffsetCI->getValue(); 1790 if (!LHSOffsetValue.isNegative() && 1791 !RHSOffsetValue.isNegative() && 1792 LHSOffsetValue.ult(LHSSize) && 1793 RHSOffsetValue.ult(RHSSize)) { 1794 return ConstantInt::get(GetCompareTy(LHS), 1795 !CmpInst::isTrueWhenEqual(Pred)); 1796 } 1797 } 1798 1799 // Repeat the above check but this time without depending on DataLayout 1800 // or being able to compute a precise size. 1801 if (!cast<PointerType>(LHS->getType())->isEmptyTy() && 1802 !cast<PointerType>(RHS->getType())->isEmptyTy() && 1803 LHSOffset->isNullValue() && 1804 RHSOffset->isNullValue()) 1805 return ConstantInt::get(GetCompareTy(LHS), 1806 !CmpInst::isTrueWhenEqual(Pred)); 1807 } 1808 1809 // Even if an non-inbounds GEP occurs along the path we can still optimize 1810 // equality comparisons concerning the result. We avoid walking the whole 1811 // chain again by starting where the last calls to 1812 // stripAndComputeConstantOffsets left off and accumulate the offsets. 1813 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true); 1814 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true); 1815 if (LHS == RHS) 1816 return ConstantExpr::getICmp(Pred, 1817 ConstantExpr::getAdd(LHSOffset, LHSNoBound), 1818 ConstantExpr::getAdd(RHSOffset, RHSNoBound)); 1819 } 1820 1821 // Otherwise, fail. 1822 return nullptr; 1823 } 1824 1825 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can 1826 /// fold the result. If not, this returns null. 1827 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 1828 const Query &Q, unsigned MaxRecurse) { 1829 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 1830 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!"); 1831 1832 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 1833 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 1834 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 1835 1836 // If we have a constant, make sure it is on the RHS. 1837 std::swap(LHS, RHS); 1838 Pred = CmpInst::getSwappedPredicate(Pred); 1839 } 1840 1841 Type *ITy = GetCompareTy(LHS); // The return type. 1842 Type *OpTy = LHS->getType(); // The operand type. 1843 1844 // icmp X, X -> true/false 1845 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false 1846 // because X could be 0. 1847 if (LHS == RHS || isa<UndefValue>(RHS)) 1848 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred)); 1849 1850 // Special case logic when the operands have i1 type. 1851 if (OpTy->getScalarType()->isIntegerTy(1)) { 1852 switch (Pred) { 1853 default: break; 1854 case ICmpInst::ICMP_EQ: 1855 // X == 1 -> X 1856 if (match(RHS, m_One())) 1857 return LHS; 1858 break; 1859 case ICmpInst::ICMP_NE: 1860 // X != 0 -> X 1861 if (match(RHS, m_Zero())) 1862 return LHS; 1863 break; 1864 case ICmpInst::ICMP_UGT: 1865 // X >u 0 -> X 1866 if (match(RHS, m_Zero())) 1867 return LHS; 1868 break; 1869 case ICmpInst::ICMP_UGE: 1870 // X >=u 1 -> X 1871 if (match(RHS, m_One())) 1872 return LHS; 1873 break; 1874 case ICmpInst::ICMP_SLT: 1875 // X <s 0 -> X 1876 if (match(RHS, m_Zero())) 1877 return LHS; 1878 break; 1879 case ICmpInst::ICMP_SLE: 1880 // X <=s -1 -> X 1881 if (match(RHS, m_One())) 1882 return LHS; 1883 break; 1884 } 1885 } 1886 1887 // If we are comparing with zero then try hard since this is a common case. 1888 if (match(RHS, m_Zero())) { 1889 bool LHSKnownNonNegative, LHSKnownNegative; 1890 switch (Pred) { 1891 default: llvm_unreachable("Unknown ICmp predicate!"); 1892 case ICmpInst::ICMP_ULT: 1893 return getFalse(ITy); 1894 case ICmpInst::ICMP_UGE: 1895 return getTrue(ITy); 1896 case ICmpInst::ICMP_EQ: 1897 case ICmpInst::ICMP_ULE: 1898 if (isKnownNonZero(LHS, Q.DL)) 1899 return getFalse(ITy); 1900 break; 1901 case ICmpInst::ICMP_NE: 1902 case ICmpInst::ICMP_UGT: 1903 if (isKnownNonZero(LHS, Q.DL)) 1904 return getTrue(ITy); 1905 break; 1906 case ICmpInst::ICMP_SLT: 1907 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 1908 if (LHSKnownNegative) 1909 return getTrue(ITy); 1910 if (LHSKnownNonNegative) 1911 return getFalse(ITy); 1912 break; 1913 case ICmpInst::ICMP_SLE: 1914 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 1915 if (LHSKnownNegative) 1916 return getTrue(ITy); 1917 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL)) 1918 return getFalse(ITy); 1919 break; 1920 case ICmpInst::ICMP_SGE: 1921 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 1922 if (LHSKnownNegative) 1923 return getFalse(ITy); 1924 if (LHSKnownNonNegative) 1925 return getTrue(ITy); 1926 break; 1927 case ICmpInst::ICMP_SGT: 1928 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL); 1929 if (LHSKnownNegative) 1930 return getFalse(ITy); 1931 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL)) 1932 return getTrue(ITy); 1933 break; 1934 } 1935 } 1936 1937 // See if we are doing a comparison with a constant integer. 1938 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 1939 // Rule out tautological comparisons (eg., ult 0 or uge 0). 1940 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue()); 1941 if (RHS_CR.isEmptySet()) 1942 return ConstantInt::getFalse(CI->getContext()); 1943 if (RHS_CR.isFullSet()) 1944 return ConstantInt::getTrue(CI->getContext()); 1945 1946 // Many binary operators with constant RHS have easy to compute constant 1947 // range. Use them to check whether the comparison is a tautology. 1948 unsigned Width = CI->getBitWidth(); 1949 APInt Lower = APInt(Width, 0); 1950 APInt Upper = APInt(Width, 0); 1951 ConstantInt *CI2; 1952 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) { 1953 // 'urem x, CI2' produces [0, CI2). 1954 Upper = CI2->getValue(); 1955 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) { 1956 // 'srem x, CI2' produces (-|CI2|, |CI2|). 1957 Upper = CI2->getValue().abs(); 1958 Lower = (-Upper) + 1; 1959 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) { 1960 // 'udiv CI2, x' produces [0, CI2]. 1961 Upper = CI2->getValue() + 1; 1962 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) { 1963 // 'udiv x, CI2' produces [0, UINT_MAX / CI2]. 1964 APInt NegOne = APInt::getAllOnesValue(Width); 1965 if (!CI2->isZero()) 1966 Upper = NegOne.udiv(CI2->getValue()) + 1; 1967 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) { 1968 if (CI2->isMinSignedValue()) { 1969 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2]. 1970 Lower = CI2->getValue(); 1971 Upper = Lower.lshr(1) + 1; 1972 } else { 1973 // 'sdiv CI2, x' produces [-|CI2|, |CI2|]. 1974 Upper = CI2->getValue().abs() + 1; 1975 Lower = (-Upper) + 1; 1976 } 1977 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) { 1978 APInt IntMin = APInt::getSignedMinValue(Width); 1979 APInt IntMax = APInt::getSignedMaxValue(Width); 1980 APInt Val = CI2->getValue(); 1981 if (Val.isAllOnesValue()) { 1982 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX] 1983 // where CI2 != -1 and CI2 != 0 and CI2 != 1 1984 Lower = IntMin + 1; 1985 Upper = IntMax + 1; 1986 } else if (Val.countLeadingZeros() < Width - 1) { 1987 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2] 1988 // where CI2 != -1 and CI2 != 0 and CI2 != 1 1989 Lower = IntMin.sdiv(Val); 1990 Upper = IntMax.sdiv(Val); 1991 if (Lower.sgt(Upper)) 1992 std::swap(Lower, Upper); 1993 Upper = Upper + 1; 1994 assert(Upper != Lower && "Upper part of range has wrapped!"); 1995 } 1996 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) { 1997 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)] 1998 Lower = CI2->getValue(); 1999 Upper = Lower.shl(Lower.countLeadingZeros()) + 1; 2000 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) { 2001 if (CI2->isNegative()) { 2002 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2] 2003 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1; 2004 Lower = CI2->getValue().shl(ShiftAmount); 2005 Upper = CI2->getValue() + 1; 2006 } else { 2007 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1] 2008 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1; 2009 Lower = CI2->getValue(); 2010 Upper = CI2->getValue().shl(ShiftAmount) + 1; 2011 } 2012 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) { 2013 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2]. 2014 APInt NegOne = APInt::getAllOnesValue(Width); 2015 if (CI2->getValue().ult(Width)) 2016 Upper = NegOne.lshr(CI2->getValue()) + 1; 2017 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) { 2018 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2]. 2019 unsigned ShiftAmount = Width - 1; 2020 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact()) 2021 ShiftAmount = CI2->getValue().countTrailingZeros(); 2022 Lower = CI2->getValue().lshr(ShiftAmount); 2023 Upper = CI2->getValue() + 1; 2024 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) { 2025 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2]. 2026 APInt IntMin = APInt::getSignedMinValue(Width); 2027 APInt IntMax = APInt::getSignedMaxValue(Width); 2028 if (CI2->getValue().ult(Width)) { 2029 Lower = IntMin.ashr(CI2->getValue()); 2030 Upper = IntMax.ashr(CI2->getValue()) + 1; 2031 } 2032 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) { 2033 unsigned ShiftAmount = Width - 1; 2034 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact()) 2035 ShiftAmount = CI2->getValue().countTrailingZeros(); 2036 if (CI2->isNegative()) { 2037 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)] 2038 Lower = CI2->getValue(); 2039 Upper = CI2->getValue().ashr(ShiftAmount) + 1; 2040 } else { 2041 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2] 2042 Lower = CI2->getValue().ashr(ShiftAmount); 2043 Upper = CI2->getValue() + 1; 2044 } 2045 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) { 2046 // 'or x, CI2' produces [CI2, UINT_MAX]. 2047 Lower = CI2->getValue(); 2048 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) { 2049 // 'and x, CI2' produces [0, CI2]. 2050 Upper = CI2->getValue() + 1; 2051 } 2052 if (Lower != Upper) { 2053 ConstantRange LHS_CR = ConstantRange(Lower, Upper); 2054 if (RHS_CR.contains(LHS_CR)) 2055 return ConstantInt::getTrue(RHS->getContext()); 2056 if (RHS_CR.inverse().contains(LHS_CR)) 2057 return ConstantInt::getFalse(RHS->getContext()); 2058 } 2059 } 2060 2061 // Compare of cast, for example (zext X) != 0 -> X != 0 2062 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) { 2063 Instruction *LI = cast<CastInst>(LHS); 2064 Value *SrcOp = LI->getOperand(0); 2065 Type *SrcTy = SrcOp->getType(); 2066 Type *DstTy = LI->getType(); 2067 2068 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input 2069 // if the integer type is the same size as the pointer type. 2070 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) && 2071 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) { 2072 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 2073 // Transfer the cast to the constant. 2074 if (Value *V = SimplifyICmpInst(Pred, SrcOp, 2075 ConstantExpr::getIntToPtr(RHSC, SrcTy), 2076 Q, MaxRecurse-1)) 2077 return V; 2078 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) { 2079 if (RI->getOperand(0)->getType() == SrcTy) 2080 // Compare without the cast. 2081 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 2082 Q, MaxRecurse-1)) 2083 return V; 2084 } 2085 } 2086 2087 if (isa<ZExtInst>(LHS)) { 2088 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the 2089 // same type. 2090 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) { 2091 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 2092 // Compare X and Y. Note that signed predicates become unsigned. 2093 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 2094 SrcOp, RI->getOperand(0), Q, 2095 MaxRecurse-1)) 2096 return V; 2097 } 2098 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended 2099 // too. If not, then try to deduce the result of the comparison. 2100 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 2101 // Compute the constant that would happen if we truncated to SrcTy then 2102 // reextended to DstTy. 2103 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 2104 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy); 2105 2106 // If the re-extended constant didn't change then this is effectively 2107 // also a case of comparing two zero-extended values. 2108 if (RExt == CI && MaxRecurse) 2109 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), 2110 SrcOp, Trunc, Q, MaxRecurse-1)) 2111 return V; 2112 2113 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit 2114 // there. Use this to work out the result of the comparison. 2115 if (RExt != CI) { 2116 switch (Pred) { 2117 default: llvm_unreachable("Unknown ICmp predicate!"); 2118 // LHS <u RHS. 2119 case ICmpInst::ICMP_EQ: 2120 case ICmpInst::ICMP_UGT: 2121 case ICmpInst::ICMP_UGE: 2122 return ConstantInt::getFalse(CI->getContext()); 2123 2124 case ICmpInst::ICMP_NE: 2125 case ICmpInst::ICMP_ULT: 2126 case ICmpInst::ICMP_ULE: 2127 return ConstantInt::getTrue(CI->getContext()); 2128 2129 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS 2130 // is non-negative then LHS <s RHS. 2131 case ICmpInst::ICMP_SGT: 2132 case ICmpInst::ICMP_SGE: 2133 return CI->getValue().isNegative() ? 2134 ConstantInt::getTrue(CI->getContext()) : 2135 ConstantInt::getFalse(CI->getContext()); 2136 2137 case ICmpInst::ICMP_SLT: 2138 case ICmpInst::ICMP_SLE: 2139 return CI->getValue().isNegative() ? 2140 ConstantInt::getFalse(CI->getContext()) : 2141 ConstantInt::getTrue(CI->getContext()); 2142 } 2143 } 2144 } 2145 } 2146 2147 if (isa<SExtInst>(LHS)) { 2148 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the 2149 // same type. 2150 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) { 2151 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType()) 2152 // Compare X and Y. Note that the predicate does not change. 2153 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0), 2154 Q, MaxRecurse-1)) 2155 return V; 2156 } 2157 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended 2158 // too. If not, then try to deduce the result of the comparison. 2159 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 2160 // Compute the constant that would happen if we truncated to SrcTy then 2161 // reextended to DstTy. 2162 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy); 2163 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy); 2164 2165 // If the re-extended constant didn't change then this is effectively 2166 // also a case of comparing two sign-extended values. 2167 if (RExt == CI && MaxRecurse) 2168 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1)) 2169 return V; 2170 2171 // Otherwise the upper bits of LHS are all equal, while RHS has varying 2172 // bits there. Use this to work out the result of the comparison. 2173 if (RExt != CI) { 2174 switch (Pred) { 2175 default: llvm_unreachable("Unknown ICmp predicate!"); 2176 case ICmpInst::ICMP_EQ: 2177 return ConstantInt::getFalse(CI->getContext()); 2178 case ICmpInst::ICMP_NE: 2179 return ConstantInt::getTrue(CI->getContext()); 2180 2181 // If RHS is non-negative then LHS <s RHS. If RHS is negative then 2182 // LHS >s RHS. 2183 case ICmpInst::ICMP_SGT: 2184 case ICmpInst::ICMP_SGE: 2185 return CI->getValue().isNegative() ? 2186 ConstantInt::getTrue(CI->getContext()) : 2187 ConstantInt::getFalse(CI->getContext()); 2188 case ICmpInst::ICMP_SLT: 2189 case ICmpInst::ICMP_SLE: 2190 return CI->getValue().isNegative() ? 2191 ConstantInt::getFalse(CI->getContext()) : 2192 ConstantInt::getTrue(CI->getContext()); 2193 2194 // If LHS is non-negative then LHS <u RHS. If LHS is negative then 2195 // LHS >u RHS. 2196 case ICmpInst::ICMP_UGT: 2197 case ICmpInst::ICMP_UGE: 2198 // Comparison is true iff the LHS <s 0. 2199 if (MaxRecurse) 2200 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp, 2201 Constant::getNullValue(SrcTy), 2202 Q, MaxRecurse-1)) 2203 return V; 2204 break; 2205 case ICmpInst::ICMP_ULT: 2206 case ICmpInst::ICMP_ULE: 2207 // Comparison is true iff the LHS >=s 0. 2208 if (MaxRecurse) 2209 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp, 2210 Constant::getNullValue(SrcTy), 2211 Q, MaxRecurse-1)) 2212 return V; 2213 break; 2214 } 2215 } 2216 } 2217 } 2218 } 2219 2220 // If a bit is known to be zero for A and known to be one for B, 2221 // then A and B cannot be equal. 2222 if (ICmpInst::isEquality(Pred)) { 2223 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) { 2224 uint32_t BitWidth = CI->getBitWidth(); 2225 APInt LHSKnownZero(BitWidth, 0); 2226 APInt LHSKnownOne(BitWidth, 0); 2227 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne); 2228 APInt RHSKnownZero(BitWidth, 0); 2229 APInt RHSKnownOne(BitWidth, 0); 2230 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne); 2231 if (((LHSKnownOne & RHSKnownZero) != 0) || 2232 ((LHSKnownZero & RHSKnownOne) != 0)) 2233 return (Pred == ICmpInst::ICMP_EQ) 2234 ? ConstantInt::getFalse(CI->getContext()) 2235 : ConstantInt::getTrue(CI->getContext()); 2236 } 2237 } 2238 2239 // Special logic for binary operators. 2240 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS); 2241 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS); 2242 if (MaxRecurse && (LBO || RBO)) { 2243 // Analyze the case when either LHS or RHS is an add instruction. 2244 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr; 2245 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null). 2246 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false; 2247 if (LBO && LBO->getOpcode() == Instruction::Add) { 2248 A = LBO->getOperand(0); B = LBO->getOperand(1); 2249 NoLHSWrapProblem = ICmpInst::isEquality(Pred) || 2250 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) || 2251 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap()); 2252 } 2253 if (RBO && RBO->getOpcode() == Instruction::Add) { 2254 C = RBO->getOperand(0); D = RBO->getOperand(1); 2255 NoRHSWrapProblem = ICmpInst::isEquality(Pred) || 2256 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) || 2257 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap()); 2258 } 2259 2260 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow. 2261 if ((A == RHS || B == RHS) && NoLHSWrapProblem) 2262 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A, 2263 Constant::getNullValue(RHS->getType()), 2264 Q, MaxRecurse-1)) 2265 return V; 2266 2267 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow. 2268 if ((C == LHS || D == LHS) && NoRHSWrapProblem) 2269 if (Value *V = SimplifyICmpInst(Pred, 2270 Constant::getNullValue(LHS->getType()), 2271 C == LHS ? D : C, Q, MaxRecurse-1)) 2272 return V; 2273 2274 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow. 2275 if (A && C && (A == C || A == D || B == C || B == D) && 2276 NoLHSWrapProblem && NoRHSWrapProblem) { 2277 // Determine Y and Z in the form icmp (X+Y), (X+Z). 2278 Value *Y, *Z; 2279 if (A == C) { 2280 // C + B == C + D -> B == D 2281 Y = B; 2282 Z = D; 2283 } else if (A == D) { 2284 // D + B == C + D -> B == C 2285 Y = B; 2286 Z = C; 2287 } else if (B == C) { 2288 // A + C == C + D -> A == D 2289 Y = A; 2290 Z = D; 2291 } else { 2292 assert(B == D); 2293 // A + D == C + D -> A == C 2294 Y = A; 2295 Z = C; 2296 } 2297 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1)) 2298 return V; 2299 } 2300 } 2301 2302 // 0 - (zext X) pred C 2303 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) { 2304 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) { 2305 if (RHSC->getValue().isStrictlyPositive()) { 2306 if (Pred == ICmpInst::ICMP_SLT) 2307 return ConstantInt::getTrue(RHSC->getContext()); 2308 if (Pred == ICmpInst::ICMP_SGE) 2309 return ConstantInt::getFalse(RHSC->getContext()); 2310 if (Pred == ICmpInst::ICMP_EQ) 2311 return ConstantInt::getFalse(RHSC->getContext()); 2312 if (Pred == ICmpInst::ICMP_NE) 2313 return ConstantInt::getTrue(RHSC->getContext()); 2314 } 2315 if (RHSC->getValue().isNonNegative()) { 2316 if (Pred == ICmpInst::ICMP_SLE) 2317 return ConstantInt::getTrue(RHSC->getContext()); 2318 if (Pred == ICmpInst::ICMP_SGT) 2319 return ConstantInt::getFalse(RHSC->getContext()); 2320 } 2321 } 2322 } 2323 2324 // icmp pred (urem X, Y), Y 2325 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) { 2326 bool KnownNonNegative, KnownNegative; 2327 switch (Pred) { 2328 default: 2329 break; 2330 case ICmpInst::ICMP_SGT: 2331 case ICmpInst::ICMP_SGE: 2332 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL); 2333 if (!KnownNonNegative) 2334 break; 2335 // fall-through 2336 case ICmpInst::ICMP_EQ: 2337 case ICmpInst::ICMP_UGT: 2338 case ICmpInst::ICMP_UGE: 2339 return getFalse(ITy); 2340 case ICmpInst::ICMP_SLT: 2341 case ICmpInst::ICMP_SLE: 2342 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL); 2343 if (!KnownNonNegative) 2344 break; 2345 // fall-through 2346 case ICmpInst::ICMP_NE: 2347 case ICmpInst::ICMP_ULT: 2348 case ICmpInst::ICMP_ULE: 2349 return getTrue(ITy); 2350 } 2351 } 2352 2353 // icmp pred X, (urem Y, X) 2354 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) { 2355 bool KnownNonNegative, KnownNegative; 2356 switch (Pred) { 2357 default: 2358 break; 2359 case ICmpInst::ICMP_SGT: 2360 case ICmpInst::ICMP_SGE: 2361 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL); 2362 if (!KnownNonNegative) 2363 break; 2364 // fall-through 2365 case ICmpInst::ICMP_NE: 2366 case ICmpInst::ICMP_UGT: 2367 case ICmpInst::ICMP_UGE: 2368 return getTrue(ITy); 2369 case ICmpInst::ICMP_SLT: 2370 case ICmpInst::ICMP_SLE: 2371 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL); 2372 if (!KnownNonNegative) 2373 break; 2374 // fall-through 2375 case ICmpInst::ICMP_EQ: 2376 case ICmpInst::ICMP_ULT: 2377 case ICmpInst::ICMP_ULE: 2378 return getFalse(ITy); 2379 } 2380 } 2381 2382 // x udiv y <=u x. 2383 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) { 2384 // icmp pred (X /u Y), X 2385 if (Pred == ICmpInst::ICMP_UGT) 2386 return getFalse(ITy); 2387 if (Pred == ICmpInst::ICMP_ULE) 2388 return getTrue(ITy); 2389 } 2390 2391 // handle: 2392 // CI2 << X == CI 2393 // CI2 << X != CI 2394 // 2395 // where CI2 is a power of 2 and CI isn't 2396 if (auto *CI = dyn_cast<ConstantInt>(RHS)) { 2397 const APInt *CI2Val, *CIVal = &CI->getValue(); 2398 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) && 2399 CI2Val->isPowerOf2()) { 2400 if (!CIVal->isPowerOf2()) { 2401 // CI2 << X can equal zero in some circumstances, 2402 // this simplification is unsafe if CI is zero. 2403 // 2404 // We know it is safe if: 2405 // - The shift is nsw, we can't shift out the one bit. 2406 // - The shift is nuw, we can't shift out the one bit. 2407 // - CI2 is one 2408 // - CI isn't zero 2409 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() || 2410 *CI2Val == 1 || !CI->isZero()) { 2411 if (Pred == ICmpInst::ICMP_EQ) 2412 return ConstantInt::getFalse(RHS->getContext()); 2413 if (Pred == ICmpInst::ICMP_NE) 2414 return ConstantInt::getTrue(RHS->getContext()); 2415 } 2416 } 2417 if (CIVal->isSignBit() && *CI2Val == 1) { 2418 if (Pred == ICmpInst::ICMP_UGT) 2419 return ConstantInt::getFalse(RHS->getContext()); 2420 if (Pred == ICmpInst::ICMP_ULE) 2421 return ConstantInt::getTrue(RHS->getContext()); 2422 } 2423 } 2424 } 2425 2426 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() && 2427 LBO->getOperand(1) == RBO->getOperand(1)) { 2428 switch (LBO->getOpcode()) { 2429 default: break; 2430 case Instruction::UDiv: 2431 case Instruction::LShr: 2432 if (ICmpInst::isSigned(Pred)) 2433 break; 2434 // fall-through 2435 case Instruction::SDiv: 2436 case Instruction::AShr: 2437 if (!LBO->isExact() || !RBO->isExact()) 2438 break; 2439 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2440 RBO->getOperand(0), Q, MaxRecurse-1)) 2441 return V; 2442 break; 2443 case Instruction::Shl: { 2444 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap(); 2445 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap(); 2446 if (!NUW && !NSW) 2447 break; 2448 if (!NSW && ICmpInst::isSigned(Pred)) 2449 break; 2450 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0), 2451 RBO->getOperand(0), Q, MaxRecurse-1)) 2452 return V; 2453 break; 2454 } 2455 } 2456 } 2457 2458 // Simplify comparisons involving max/min. 2459 Value *A, *B; 2460 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE; 2461 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B". 2462 2463 // Signed variants on "max(a,b)>=a -> true". 2464 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 2465 if (A != RHS) std::swap(A, B); // smax(A, B) pred A. 2466 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 2467 // We analyze this as smax(A, B) pred A. 2468 P = Pred; 2469 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) && 2470 (A == LHS || B == LHS)) { 2471 if (A != LHS) std::swap(A, B); // A pred smax(A, B). 2472 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B". 2473 // We analyze this as smax(A, B) swapped-pred A. 2474 P = CmpInst::getSwappedPredicate(Pred); 2475 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 2476 (A == RHS || B == RHS)) { 2477 if (A != RHS) std::swap(A, B); // smin(A, B) pred A. 2478 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 2479 // We analyze this as smax(-A, -B) swapped-pred -A. 2480 // Note that we do not need to actually form -A or -B thanks to EqP. 2481 P = CmpInst::getSwappedPredicate(Pred); 2482 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) && 2483 (A == LHS || B == LHS)) { 2484 if (A != LHS) std::swap(A, B); // A pred smin(A, B). 2485 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B". 2486 // We analyze this as smax(-A, -B) pred -A. 2487 // Note that we do not need to actually form -A or -B thanks to EqP. 2488 P = Pred; 2489 } 2490 if (P != CmpInst::BAD_ICMP_PREDICATE) { 2491 // Cases correspond to "max(A, B) p A". 2492 switch (P) { 2493 default: 2494 break; 2495 case CmpInst::ICMP_EQ: 2496 case CmpInst::ICMP_SLE: 2497 // Equivalent to "A EqP B". This may be the same as the condition tested 2498 // in the max/min; if so, we can just return that. 2499 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 2500 return V; 2501 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 2502 return V; 2503 // Otherwise, see if "A EqP B" simplifies. 2504 if (MaxRecurse) 2505 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1)) 2506 return V; 2507 break; 2508 case CmpInst::ICMP_NE: 2509 case CmpInst::ICMP_SGT: { 2510 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 2511 // Equivalent to "A InvEqP B". This may be the same as the condition 2512 // tested in the max/min; if so, we can just return that. 2513 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 2514 return V; 2515 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 2516 return V; 2517 // Otherwise, see if "A InvEqP B" simplifies. 2518 if (MaxRecurse) 2519 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1)) 2520 return V; 2521 break; 2522 } 2523 case CmpInst::ICMP_SGE: 2524 // Always true. 2525 return getTrue(ITy); 2526 case CmpInst::ICMP_SLT: 2527 // Always false. 2528 return getFalse(ITy); 2529 } 2530 } 2531 2532 // Unsigned variants on "max(a,b)>=a -> true". 2533 P = CmpInst::BAD_ICMP_PREDICATE; 2534 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) { 2535 if (A != RHS) std::swap(A, B); // umax(A, B) pred A. 2536 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 2537 // We analyze this as umax(A, B) pred A. 2538 P = Pred; 2539 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) && 2540 (A == LHS || B == LHS)) { 2541 if (A != LHS) std::swap(A, B); // A pred umax(A, B). 2542 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B". 2543 // We analyze this as umax(A, B) swapped-pred A. 2544 P = CmpInst::getSwappedPredicate(Pred); 2545 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 2546 (A == RHS || B == RHS)) { 2547 if (A != RHS) std::swap(A, B); // umin(A, B) pred A. 2548 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 2549 // We analyze this as umax(-A, -B) swapped-pred -A. 2550 // Note that we do not need to actually form -A or -B thanks to EqP. 2551 P = CmpInst::getSwappedPredicate(Pred); 2552 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) && 2553 (A == LHS || B == LHS)) { 2554 if (A != LHS) std::swap(A, B); // A pred umin(A, B). 2555 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B". 2556 // We analyze this as umax(-A, -B) pred -A. 2557 // Note that we do not need to actually form -A or -B thanks to EqP. 2558 P = Pred; 2559 } 2560 if (P != CmpInst::BAD_ICMP_PREDICATE) { 2561 // Cases correspond to "max(A, B) p A". 2562 switch (P) { 2563 default: 2564 break; 2565 case CmpInst::ICMP_EQ: 2566 case CmpInst::ICMP_ULE: 2567 // Equivalent to "A EqP B". This may be the same as the condition tested 2568 // in the max/min; if so, we can just return that. 2569 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B)) 2570 return V; 2571 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B)) 2572 return V; 2573 // Otherwise, see if "A EqP B" simplifies. 2574 if (MaxRecurse) 2575 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1)) 2576 return V; 2577 break; 2578 case CmpInst::ICMP_NE: 2579 case CmpInst::ICMP_UGT: { 2580 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP); 2581 // Equivalent to "A InvEqP B". This may be the same as the condition 2582 // tested in the max/min; if so, we can just return that. 2583 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B)) 2584 return V; 2585 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B)) 2586 return V; 2587 // Otherwise, see if "A InvEqP B" simplifies. 2588 if (MaxRecurse) 2589 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1)) 2590 return V; 2591 break; 2592 } 2593 case CmpInst::ICMP_UGE: 2594 // Always true. 2595 return getTrue(ITy); 2596 case CmpInst::ICMP_ULT: 2597 // Always false. 2598 return getFalse(ITy); 2599 } 2600 } 2601 2602 // Variants on "max(x,y) >= min(x,z)". 2603 Value *C, *D; 2604 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && 2605 match(RHS, m_SMin(m_Value(C), m_Value(D))) && 2606 (A == C || A == D || B == C || B == D)) { 2607 // max(x, ?) pred min(x, ?). 2608 if (Pred == CmpInst::ICMP_SGE) 2609 // Always true. 2610 return getTrue(ITy); 2611 if (Pred == CmpInst::ICMP_SLT) 2612 // Always false. 2613 return getFalse(ITy); 2614 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) && 2615 match(RHS, m_SMax(m_Value(C), m_Value(D))) && 2616 (A == C || A == D || B == C || B == D)) { 2617 // min(x, ?) pred max(x, ?). 2618 if (Pred == CmpInst::ICMP_SLE) 2619 // Always true. 2620 return getTrue(ITy); 2621 if (Pred == CmpInst::ICMP_SGT) 2622 // Always false. 2623 return getFalse(ITy); 2624 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && 2625 match(RHS, m_UMin(m_Value(C), m_Value(D))) && 2626 (A == C || A == D || B == C || B == D)) { 2627 // max(x, ?) pred min(x, ?). 2628 if (Pred == CmpInst::ICMP_UGE) 2629 // Always true. 2630 return getTrue(ITy); 2631 if (Pred == CmpInst::ICMP_ULT) 2632 // Always false. 2633 return getFalse(ITy); 2634 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) && 2635 match(RHS, m_UMax(m_Value(C), m_Value(D))) && 2636 (A == C || A == D || B == C || B == D)) { 2637 // min(x, ?) pred max(x, ?). 2638 if (Pred == CmpInst::ICMP_ULE) 2639 // Always true. 2640 return getTrue(ITy); 2641 if (Pred == CmpInst::ICMP_UGT) 2642 // Always false. 2643 return getFalse(ITy); 2644 } 2645 2646 // Simplify comparisons of related pointers using a powerful, recursive 2647 // GEP-walk when we have target data available.. 2648 if (LHS->getType()->isPointerTy()) 2649 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS)) 2650 return C; 2651 2652 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) { 2653 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) { 2654 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() && 2655 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() && 2656 (ICmpInst::isEquality(Pred) || 2657 (GLHS->isInBounds() && GRHS->isInBounds() && 2658 Pred == ICmpInst::getSignedPredicate(Pred)))) { 2659 // The bases are equal and the indices are constant. Build a constant 2660 // expression GEP with the same indices and a null base pointer to see 2661 // what constant folding can make out of it. 2662 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType()); 2663 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end()); 2664 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS); 2665 2666 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end()); 2667 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS); 2668 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS); 2669 } 2670 } 2671 } 2672 2673 // If the comparison is with the result of a select instruction, check whether 2674 // comparing with either branch of the select always yields the same value. 2675 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 2676 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 2677 return V; 2678 2679 // If the comparison is with the result of a phi instruction, check whether 2680 // doing the compare with each incoming phi value yields a common result. 2681 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 2682 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 2683 return V; 2684 2685 return nullptr; 2686 } 2687 2688 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS, 2689 const DataLayout *DL, 2690 const TargetLibraryInfo *TLI, 2691 const DominatorTree *DT) { 2692 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT), 2693 RecursionLimit); 2694 } 2695 2696 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can 2697 /// fold the result. If not, this returns null. 2698 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 2699 const Query &Q, unsigned MaxRecurse) { 2700 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate; 2701 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!"); 2702 2703 if (Constant *CLHS = dyn_cast<Constant>(LHS)) { 2704 if (Constant *CRHS = dyn_cast<Constant>(RHS)) 2705 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI); 2706 2707 // If we have a constant, make sure it is on the RHS. 2708 std::swap(LHS, RHS); 2709 Pred = CmpInst::getSwappedPredicate(Pred); 2710 } 2711 2712 // Fold trivial predicates. 2713 if (Pred == FCmpInst::FCMP_FALSE) 2714 return ConstantInt::get(GetCompareTy(LHS), 0); 2715 if (Pred == FCmpInst::FCMP_TRUE) 2716 return ConstantInt::get(GetCompareTy(LHS), 1); 2717 2718 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef 2719 return UndefValue::get(GetCompareTy(LHS)); 2720 2721 // fcmp x,x -> true/false. Not all compares are foldable. 2722 if (LHS == RHS) { 2723 if (CmpInst::isTrueWhenEqual(Pred)) 2724 return ConstantInt::get(GetCompareTy(LHS), 1); 2725 if (CmpInst::isFalseWhenEqual(Pred)) 2726 return ConstantInt::get(GetCompareTy(LHS), 0); 2727 } 2728 2729 // Handle fcmp with constant RHS 2730 if (Constant *RHSC = dyn_cast<Constant>(RHS)) { 2731 // If the constant is a nan, see if we can fold the comparison based on it. 2732 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) { 2733 if (CFP->getValueAPF().isNaN()) { 2734 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo" 2735 return ConstantInt::getFalse(CFP->getContext()); 2736 assert(FCmpInst::isUnordered(Pred) && 2737 "Comparison must be either ordered or unordered!"); 2738 // True if unordered. 2739 return ConstantInt::getTrue(CFP->getContext()); 2740 } 2741 // Check whether the constant is an infinity. 2742 if (CFP->getValueAPF().isInfinity()) { 2743 if (CFP->getValueAPF().isNegative()) { 2744 switch (Pred) { 2745 case FCmpInst::FCMP_OLT: 2746 // No value is ordered and less than negative infinity. 2747 return ConstantInt::getFalse(CFP->getContext()); 2748 case FCmpInst::FCMP_UGE: 2749 // All values are unordered with or at least negative infinity. 2750 return ConstantInt::getTrue(CFP->getContext()); 2751 default: 2752 break; 2753 } 2754 } else { 2755 switch (Pred) { 2756 case FCmpInst::FCMP_OGT: 2757 // No value is ordered and greater than infinity. 2758 return ConstantInt::getFalse(CFP->getContext()); 2759 case FCmpInst::FCMP_ULE: 2760 // All values are unordered with and at most infinity. 2761 return ConstantInt::getTrue(CFP->getContext()); 2762 default: 2763 break; 2764 } 2765 } 2766 } 2767 } 2768 } 2769 2770 // If the comparison is with the result of a select instruction, check whether 2771 // comparing with either branch of the select always yields the same value. 2772 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 2773 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse)) 2774 return V; 2775 2776 // If the comparison is with the result of a phi instruction, check whether 2777 // doing the compare with each incoming phi value yields a common result. 2778 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 2779 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse)) 2780 return V; 2781 2782 return nullptr; 2783 } 2784 2785 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 2786 const DataLayout *DL, 2787 const TargetLibraryInfo *TLI, 2788 const DominatorTree *DT) { 2789 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT), 2790 RecursionLimit); 2791 } 2792 2793 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold 2794 /// the result. If not, this returns null. 2795 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal, 2796 Value *FalseVal, const Query &Q, 2797 unsigned MaxRecurse) { 2798 // select true, X, Y -> X 2799 // select false, X, Y -> Y 2800 if (Constant *CB = dyn_cast<Constant>(CondVal)) { 2801 if (CB->isAllOnesValue()) 2802 return TrueVal; 2803 if (CB->isNullValue()) 2804 return FalseVal; 2805 } 2806 2807 // select C, X, X -> X 2808 if (TrueVal == FalseVal) 2809 return TrueVal; 2810 2811 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y 2812 if (isa<Constant>(TrueVal)) 2813 return TrueVal; 2814 return FalseVal; 2815 } 2816 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X 2817 return FalseVal; 2818 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X 2819 return TrueVal; 2820 2821 return nullptr; 2822 } 2823 2824 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, 2825 const DataLayout *DL, 2826 const TargetLibraryInfo *TLI, 2827 const DominatorTree *DT) { 2828 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (DL, TLI, DT), 2829 RecursionLimit); 2830 } 2831 2832 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can 2833 /// fold the result. If not, this returns null. 2834 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) { 2835 // The type of the GEP pointer operand. 2836 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType()); 2837 unsigned AS = PtrTy->getAddressSpace(); 2838 2839 // getelementptr P -> P. 2840 if (Ops.size() == 1) 2841 return Ops[0]; 2842 2843 // Compute the (pointer) type returned by the GEP instruction. 2844 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1)); 2845 Type *GEPTy = PointerType::get(LastType, AS); 2846 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType())) 2847 GEPTy = VectorType::get(GEPTy, VT->getNumElements()); 2848 2849 if (isa<UndefValue>(Ops[0])) 2850 return UndefValue::get(GEPTy); 2851 2852 if (Ops.size() == 2) { 2853 // getelementptr P, 0 -> P. 2854 if (match(Ops[1], m_Zero())) 2855 return Ops[0]; 2856 2857 Type *Ty = PtrTy->getElementType(); 2858 if (Q.DL && Ty->isSized()) { 2859 Value *P; 2860 uint64_t C; 2861 uint64_t TyAllocSize = Q.DL->getTypeAllocSize(Ty); 2862 // getelementptr P, N -> P if P points to a type of zero size. 2863 if (TyAllocSize == 0) 2864 return Ops[0]; 2865 2866 // The following transforms are only safe if the ptrtoint cast 2867 // doesn't truncate the pointers. 2868 if (Ops[1]->getType()->getScalarSizeInBits() == 2869 Q.DL->getPointerSizeInBits(AS)) { 2870 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * { 2871 if (match(P, m_Zero())) 2872 return Constant::getNullValue(GEPTy); 2873 Value *Temp; 2874 if (match(P, m_PtrToInt(m_Value(Temp)))) 2875 if (Temp->getType() == GEPTy) 2876 return Temp; 2877 return nullptr; 2878 }; 2879 2880 // getelementptr V, (sub P, V) -> P if P points to a type of size 1. 2881 if (TyAllocSize == 1 && 2882 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))))) 2883 if (Value *R = PtrToIntOrZero(P)) 2884 return R; 2885 2886 // getelementptr V, (ashr (sub P, V), C) -> Q 2887 // if P points to a type of size 1 << C. 2888 if (match(Ops[1], 2889 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))), 2890 m_ConstantInt(C))) && 2891 TyAllocSize == 1ULL << C) 2892 if (Value *R = PtrToIntOrZero(P)) 2893 return R; 2894 2895 // getelementptr V, (sdiv (sub P, V), C) -> Q 2896 // if P points to a type of size C. 2897 if (match(Ops[1], 2898 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))), 2899 m_SpecificInt(TyAllocSize)))) 2900 if (Value *R = PtrToIntOrZero(P)) 2901 return R; 2902 } 2903 } 2904 } 2905 2906 // Check to see if this is constant foldable. 2907 for (unsigned i = 0, e = Ops.size(); i != e; ++i) 2908 if (!isa<Constant>(Ops[i])) 2909 return nullptr; 2910 2911 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1)); 2912 } 2913 2914 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL, 2915 const TargetLibraryInfo *TLI, 2916 const DominatorTree *DT) { 2917 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT), RecursionLimit); 2918 } 2919 2920 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we 2921 /// can fold the result. If not, this returns null. 2922 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val, 2923 ArrayRef<unsigned> Idxs, const Query &Q, 2924 unsigned) { 2925 if (Constant *CAgg = dyn_cast<Constant>(Agg)) 2926 if (Constant *CVal = dyn_cast<Constant>(Val)) 2927 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs); 2928 2929 // insertvalue x, undef, n -> x 2930 if (match(Val, m_Undef())) 2931 return Agg; 2932 2933 // insertvalue x, (extractvalue y, n), n 2934 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val)) 2935 if (EV->getAggregateOperand()->getType() == Agg->getType() && 2936 EV->getIndices() == Idxs) { 2937 // insertvalue undef, (extractvalue y, n), n -> y 2938 if (match(Agg, m_Undef())) 2939 return EV->getAggregateOperand(); 2940 2941 // insertvalue y, (extractvalue y, n), n -> y 2942 if (Agg == EV->getAggregateOperand()) 2943 return Agg; 2944 } 2945 2946 return nullptr; 2947 } 2948 2949 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val, 2950 ArrayRef<unsigned> Idxs, 2951 const DataLayout *DL, 2952 const TargetLibraryInfo *TLI, 2953 const DominatorTree *DT) { 2954 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (DL, TLI, DT), 2955 RecursionLimit); 2956 } 2957 2958 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null. 2959 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) { 2960 // If all of the PHI's incoming values are the same then replace the PHI node 2961 // with the common value. 2962 Value *CommonValue = nullptr; 2963 bool HasUndefInput = false; 2964 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 2965 Value *Incoming = PN->getIncomingValue(i); 2966 // If the incoming value is the phi node itself, it can safely be skipped. 2967 if (Incoming == PN) continue; 2968 if (isa<UndefValue>(Incoming)) { 2969 // Remember that we saw an undef value, but otherwise ignore them. 2970 HasUndefInput = true; 2971 continue; 2972 } 2973 if (CommonValue && Incoming != CommonValue) 2974 return nullptr; // Not the same, bail out. 2975 CommonValue = Incoming; 2976 } 2977 2978 // If CommonValue is null then all of the incoming values were either undef or 2979 // equal to the phi node itself. 2980 if (!CommonValue) 2981 return UndefValue::get(PN->getType()); 2982 2983 // If we have a PHI node like phi(X, undef, X), where X is defined by some 2984 // instruction, we cannot return X as the result of the PHI node unless it 2985 // dominates the PHI block. 2986 if (HasUndefInput) 2987 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr; 2988 2989 return CommonValue; 2990 } 2991 2992 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) { 2993 if (Constant *C = dyn_cast<Constant>(Op)) 2994 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI); 2995 2996 return nullptr; 2997 } 2998 2999 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL, 3000 const TargetLibraryInfo *TLI, 3001 const DominatorTree *DT) { 3002 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT), RecursionLimit); 3003 } 3004 3005 //=== Helper functions for higher up the class hierarchy. 3006 3007 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can 3008 /// fold the result. If not, this returns null. 3009 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 3010 const Query &Q, unsigned MaxRecurse) { 3011 switch (Opcode) { 3012 case Instruction::Add: 3013 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 3014 Q, MaxRecurse); 3015 case Instruction::FAdd: 3016 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 3017 3018 case Instruction::Sub: 3019 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 3020 Q, MaxRecurse); 3021 case Instruction::FSub: 3022 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse); 3023 3024 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse); 3025 case Instruction::FMul: 3026 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse); 3027 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse); 3028 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse); 3029 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse); 3030 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse); 3031 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse); 3032 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse); 3033 case Instruction::Shl: 3034 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false, 3035 Q, MaxRecurse); 3036 case Instruction::LShr: 3037 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse); 3038 case Instruction::AShr: 3039 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse); 3040 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse); 3041 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse); 3042 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse); 3043 default: 3044 if (Constant *CLHS = dyn_cast<Constant>(LHS)) 3045 if (Constant *CRHS = dyn_cast<Constant>(RHS)) { 3046 Constant *COps[] = {CLHS, CRHS}; 3047 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL, 3048 Q.TLI); 3049 } 3050 3051 // If the operation is associative, try some generic simplifications. 3052 if (Instruction::isAssociative(Opcode)) 3053 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse)) 3054 return V; 3055 3056 // If the operation is with the result of a select instruction check whether 3057 // operating on either branch of the select always yields the same value. 3058 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)) 3059 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse)) 3060 return V; 3061 3062 // If the operation is with the result of a phi instruction, check whether 3063 // operating on all incoming values of the phi always yields the same value. 3064 if (isa<PHINode>(LHS) || isa<PHINode>(RHS)) 3065 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse)) 3066 return V; 3067 3068 return nullptr; 3069 } 3070 } 3071 3072 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, 3073 const DataLayout *DL, const TargetLibraryInfo *TLI, 3074 const DominatorTree *DT) { 3075 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT), RecursionLimit); 3076 } 3077 3078 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can 3079 /// fold the result. 3080 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3081 const Query &Q, unsigned MaxRecurse) { 3082 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate)) 3083 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 3084 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse); 3085 } 3086 3087 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, 3088 const DataLayout *DL, const TargetLibraryInfo *TLI, 3089 const DominatorTree *DT) { 3090 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT), 3091 RecursionLimit); 3092 } 3093 3094 static bool IsIdempotent(Intrinsic::ID ID) { 3095 switch (ID) { 3096 default: return false; 3097 3098 // Unary idempotent: f(f(x)) = f(x) 3099 case Intrinsic::fabs: 3100 case Intrinsic::floor: 3101 case Intrinsic::ceil: 3102 case Intrinsic::trunc: 3103 case Intrinsic::rint: 3104 case Intrinsic::nearbyint: 3105 case Intrinsic::round: 3106 return true; 3107 } 3108 } 3109 3110 template <typename IterTy> 3111 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd, 3112 const Query &Q, unsigned MaxRecurse) { 3113 // Perform idempotent optimizations 3114 if (!IsIdempotent(IID)) 3115 return nullptr; 3116 3117 // Unary Ops 3118 if (std::distance(ArgBegin, ArgEnd) == 1) 3119 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) 3120 if (II->getIntrinsicID() == IID) 3121 return II; 3122 3123 return nullptr; 3124 } 3125 3126 template <typename IterTy> 3127 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd, 3128 const Query &Q, unsigned MaxRecurse) { 3129 Type *Ty = V->getType(); 3130 if (PointerType *PTy = dyn_cast<PointerType>(Ty)) 3131 Ty = PTy->getElementType(); 3132 FunctionType *FTy = cast<FunctionType>(Ty); 3133 3134 // call undef -> undef 3135 if (isa<UndefValue>(V)) 3136 return UndefValue::get(FTy->getReturnType()); 3137 3138 Function *F = dyn_cast<Function>(V); 3139 if (!F) 3140 return nullptr; 3141 3142 if (unsigned IID = F->getIntrinsicID()) 3143 if (Value *Ret = 3144 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse)) 3145 return Ret; 3146 3147 if (!canConstantFoldCallTo(F)) 3148 return nullptr; 3149 3150 SmallVector<Constant *, 4> ConstantArgs; 3151 ConstantArgs.reserve(ArgEnd - ArgBegin); 3152 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) { 3153 Constant *C = dyn_cast<Constant>(*I); 3154 if (!C) 3155 return nullptr; 3156 ConstantArgs.push_back(C); 3157 } 3158 3159 return ConstantFoldCall(F, ConstantArgs, Q.TLI); 3160 } 3161 3162 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin, 3163 User::op_iterator ArgEnd, const DataLayout *DL, 3164 const TargetLibraryInfo *TLI, 3165 const DominatorTree *DT) { 3166 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT), 3167 RecursionLimit); 3168 } 3169 3170 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args, 3171 const DataLayout *DL, const TargetLibraryInfo *TLI, 3172 const DominatorTree *DT) { 3173 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(DL, TLI, DT), 3174 RecursionLimit); 3175 } 3176 3177 /// SimplifyInstruction - See if we can compute a simplified version of this 3178 /// instruction. If not, this returns null. 3179 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL, 3180 const TargetLibraryInfo *TLI, 3181 const DominatorTree *DT) { 3182 Value *Result; 3183 3184 switch (I->getOpcode()) { 3185 default: 3186 Result = ConstantFoldInstruction(I, DL, TLI); 3187 break; 3188 case Instruction::FAdd: 3189 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1), 3190 I->getFastMathFlags(), DL, TLI, DT); 3191 break; 3192 case Instruction::Add: 3193 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1), 3194 cast<BinaryOperator>(I)->hasNoSignedWrap(), 3195 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 3196 DL, TLI, DT); 3197 break; 3198 case Instruction::FSub: 3199 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1), 3200 I->getFastMathFlags(), DL, TLI, DT); 3201 break; 3202 case Instruction::Sub: 3203 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1), 3204 cast<BinaryOperator>(I)->hasNoSignedWrap(), 3205 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 3206 DL, TLI, DT); 3207 break; 3208 case Instruction::FMul: 3209 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1), 3210 I->getFastMathFlags(), DL, TLI, DT); 3211 break; 3212 case Instruction::Mul: 3213 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3214 break; 3215 case Instruction::SDiv: 3216 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3217 break; 3218 case Instruction::UDiv: 3219 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3220 break; 3221 case Instruction::FDiv: 3222 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3223 break; 3224 case Instruction::SRem: 3225 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3226 break; 3227 case Instruction::URem: 3228 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3229 break; 3230 case Instruction::FRem: 3231 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3232 break; 3233 case Instruction::Shl: 3234 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1), 3235 cast<BinaryOperator>(I)->hasNoSignedWrap(), 3236 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), 3237 DL, TLI, DT); 3238 break; 3239 case Instruction::LShr: 3240 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), 3241 cast<BinaryOperator>(I)->isExact(), 3242 DL, TLI, DT); 3243 break; 3244 case Instruction::AShr: 3245 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), 3246 cast<BinaryOperator>(I)->isExact(), 3247 DL, TLI, DT); 3248 break; 3249 case Instruction::And: 3250 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3251 break; 3252 case Instruction::Or: 3253 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3254 break; 3255 case Instruction::Xor: 3256 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3257 break; 3258 case Instruction::ICmp: 3259 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), 3260 I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3261 break; 3262 case Instruction::FCmp: 3263 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), 3264 I->getOperand(0), I->getOperand(1), DL, TLI, DT); 3265 break; 3266 case Instruction::Select: 3267 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1), 3268 I->getOperand(2), DL, TLI, DT); 3269 break; 3270 case Instruction::GetElementPtr: { 3271 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end()); 3272 Result = SimplifyGEPInst(Ops, DL, TLI, DT); 3273 break; 3274 } 3275 case Instruction::InsertValue: { 3276 InsertValueInst *IV = cast<InsertValueInst>(I); 3277 Result = SimplifyInsertValueInst(IV->getAggregateOperand(), 3278 IV->getInsertedValueOperand(), 3279 IV->getIndices(), DL, TLI, DT); 3280 break; 3281 } 3282 case Instruction::PHI: 3283 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT)); 3284 break; 3285 case Instruction::Call: { 3286 CallSite CS(cast<CallInst>(I)); 3287 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), 3288 DL, TLI, DT); 3289 break; 3290 } 3291 case Instruction::Trunc: 3292 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT); 3293 break; 3294 } 3295 3296 /// If called on unreachable code, the above logic may report that the 3297 /// instruction simplified to itself. Make life easier for users by 3298 /// detecting that case here, returning a safe value instead. 3299 return Result == I ? UndefValue::get(I->getType()) : Result; 3300 } 3301 3302 /// \brief Implementation of recursive simplification through an instructions 3303 /// uses. 3304 /// 3305 /// This is the common implementation of the recursive simplification routines. 3306 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to 3307 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of 3308 /// instructions to process and attempt to simplify it using 3309 /// InstructionSimplify. 3310 /// 3311 /// This routine returns 'true' only when *it* simplifies something. The passed 3312 /// in simplified value does not count toward this. 3313 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV, 3314 const DataLayout *DL, 3315 const TargetLibraryInfo *TLI, 3316 const DominatorTree *DT) { 3317 bool Simplified = false; 3318 SmallSetVector<Instruction *, 8> Worklist; 3319 3320 // If we have an explicit value to collapse to, do that round of the 3321 // simplification loop by hand initially. 3322 if (SimpleV) { 3323 for (User *U : I->users()) 3324 if (U != I) 3325 Worklist.insert(cast<Instruction>(U)); 3326 3327 // Replace the instruction with its simplified value. 3328 I->replaceAllUsesWith(SimpleV); 3329 3330 // Gracefully handle edge cases where the instruction is not wired into any 3331 // parent block. 3332 if (I->getParent()) 3333 I->eraseFromParent(); 3334 } else { 3335 Worklist.insert(I); 3336 } 3337 3338 // Note that we must test the size on each iteration, the worklist can grow. 3339 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) { 3340 I = Worklist[Idx]; 3341 3342 // See if this instruction simplifies. 3343 SimpleV = SimplifyInstruction(I, DL, TLI, DT); 3344 if (!SimpleV) 3345 continue; 3346 3347 Simplified = true; 3348 3349 // Stash away all the uses of the old instruction so we can check them for 3350 // recursive simplifications after a RAUW. This is cheaper than checking all 3351 // uses of To on the recursive step in most cases. 3352 for (User *U : I->users()) 3353 Worklist.insert(cast<Instruction>(U)); 3354 3355 // Replace the instruction with its simplified value. 3356 I->replaceAllUsesWith(SimpleV); 3357 3358 // Gracefully handle edge cases where the instruction is not wired into any 3359 // parent block. 3360 if (I->getParent()) 3361 I->eraseFromParent(); 3362 } 3363 return Simplified; 3364 } 3365 3366 bool llvm::recursivelySimplifyInstruction(Instruction *I, 3367 const DataLayout *DL, 3368 const TargetLibraryInfo *TLI, 3369 const DominatorTree *DT) { 3370 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT); 3371 } 3372 3373 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV, 3374 const DataLayout *DL, 3375 const TargetLibraryInfo *TLI, 3376 const DominatorTree *DT) { 3377 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!"); 3378 assert(SimpleV && "Must provide a simplified value."); 3379 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT); 3380 } 3381