1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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).
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/Analysis/CaptureTracking.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Analysis/VectorUtils.h"
29 #include "llvm/IR/ConstantRange.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Dominators.h"
32 #include "llvm/IR/GetElementPtrTypeIterator.h"
33 #include "llvm/IR/GlobalAlias.h"
34 #include "llvm/IR/Operator.h"
35 #include "llvm/IR/PatternMatch.h"
36 #include "llvm/IR/ValueHandle.h"
39 using namespace llvm::PatternMatch;
41 #define DEBUG_TYPE "instsimplify"
43 enum { RecursionLimit = 3 };
45 STATISTIC(NumExpand, "Number of expansions");
46 STATISTIC(NumReassoc, "Number of reassociations");
51 const TargetLibraryInfo *TLI;
52 const DominatorTree *DT;
54 const Instruction *CxtI;
56 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
57 const DominatorTree *dt, AssumptionCache *ac = nullptr,
58 const Instruction *cxti = nullptr)
59 : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
61 } // end anonymous namespace
63 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
64 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
66 static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
67 const Query &, unsigned);
68 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
70 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
71 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
72 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
74 /// For a boolean type, or a vector of boolean type, return false, or
75 /// a vector with every element false, as appropriate for the type.
76 static Constant *getFalse(Type *Ty) {
77 assert(Ty->getScalarType()->isIntegerTy(1) &&
78 "Expected i1 type or a vector of i1!");
79 return Constant::getNullValue(Ty);
82 /// For a boolean type, or a vector of boolean type, return true, or
83 /// a vector with every element true, as appropriate for the type.
84 static Constant *getTrue(Type *Ty) {
85 assert(Ty->getScalarType()->isIntegerTy(1) &&
86 "Expected i1 type or a vector of i1!");
87 return Constant::getAllOnesValue(Ty);
90 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
91 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
93 CmpInst *Cmp = dyn_cast<CmpInst>(V);
96 CmpInst::Predicate CPred = Cmp->getPredicate();
97 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
98 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
100 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
104 /// Does the given value dominate the specified phi node?
105 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
106 Instruction *I = dyn_cast<Instruction>(V);
108 // Arguments and constants dominate all instructions.
111 // If we are processing instructions (and/or basic blocks) that have not been
112 // fully added to a function, the parent nodes may still be null. Simply
113 // return the conservative answer in these cases.
114 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
117 // If we have a DominatorTree then do a precise test.
119 if (!DT->isReachableFromEntry(P->getParent()))
121 if (!DT->isReachableFromEntry(I->getParent()))
123 return DT->dominates(I, P);
126 // Otherwise, if the instruction is in the entry block and is not an invoke,
127 // then it obviously dominates all phi nodes.
128 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
135 /// Simplify "A op (B op' C)" by distributing op over op', turning it into
136 /// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
137 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
138 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
139 /// Returns the simplified value, or null if no simplification was performed.
140 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
141 unsigned OpcToExpand, const Query &Q,
142 unsigned MaxRecurse) {
143 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
144 // Recursion is always used, so bail out at once if we already hit the limit.
148 // Check whether the expression has the form "(A op' B) op C".
149 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
150 if (Op0->getOpcode() == OpcodeToExpand) {
151 // It does! Try turning it into "(A op C) op' (B op C)".
152 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
153 // Do "A op C" and "B op C" both simplify?
154 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
155 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
156 // They do! Return "L op' R" if it simplifies or is already available.
157 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
158 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
159 && L == B && R == A)) {
163 // Otherwise return "L op' R" if it simplifies.
164 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
171 // Check whether the expression has the form "A op (B op' C)".
172 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
173 if (Op1->getOpcode() == OpcodeToExpand) {
174 // It does! Try turning it into "(A op B) op' (A op C)".
175 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
176 // Do "A op B" and "A op C" both simplify?
177 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
178 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
179 // They do! Return "L op' R" if it simplifies or is already available.
180 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
181 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
182 && L == C && R == B)) {
186 // Otherwise return "L op' R" if it simplifies.
187 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
197 /// Generic simplifications for associative binary operations.
198 /// Returns the simpler value, or null if none was found.
199 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
200 const Query &Q, unsigned MaxRecurse) {
201 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
202 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
204 // Recursion is always used, so bail out at once if we already hit the limit.
208 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
209 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
211 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
212 if (Op0 && Op0->getOpcode() == Opcode) {
213 Value *A = Op0->getOperand(0);
214 Value *B = Op0->getOperand(1);
217 // Does "B op C" simplify?
218 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
219 // It does! Return "A op V" if it simplifies or is already available.
220 // If V equals B then "A op V" is just the LHS.
221 if (V == B) return LHS;
222 // Otherwise return "A op V" if it simplifies.
223 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
230 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
231 if (Op1 && Op1->getOpcode() == Opcode) {
233 Value *B = Op1->getOperand(0);
234 Value *C = Op1->getOperand(1);
236 // Does "A op B" simplify?
237 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
238 // It does! Return "V op C" if it simplifies or is already available.
239 // If V equals B then "V op C" is just the RHS.
240 if (V == B) return RHS;
241 // Otherwise return "V op C" if it simplifies.
242 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
249 // The remaining transforms require commutativity as well as associativity.
250 if (!Instruction::isCommutative(Opcode))
253 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
254 if (Op0 && Op0->getOpcode() == Opcode) {
255 Value *A = Op0->getOperand(0);
256 Value *B = Op0->getOperand(1);
259 // Does "C op A" simplify?
260 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
261 // It does! Return "V op B" if it simplifies or is already available.
262 // If V equals A then "V op B" is just the LHS.
263 if (V == A) return LHS;
264 // Otherwise return "V op B" if it simplifies.
265 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
272 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
273 if (Op1 && Op1->getOpcode() == Opcode) {
275 Value *B = Op1->getOperand(0);
276 Value *C = Op1->getOperand(1);
278 // Does "C op A" simplify?
279 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
280 // It does! Return "B op V" if it simplifies or is already available.
281 // If V equals C then "B op V" is just the RHS.
282 if (V == C) return RHS;
283 // Otherwise return "B op V" if it simplifies.
284 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
294 /// In the case of a binary operation with a select instruction as an operand,
295 /// try to simplify the binop by seeing whether evaluating it on both branches
296 /// of the select results in the same value. Returns the common value if so,
297 /// otherwise returns null.
298 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
299 const Query &Q, unsigned MaxRecurse) {
300 // Recursion is always used, so bail out at once if we already hit the limit.
305 if (isa<SelectInst>(LHS)) {
306 SI = cast<SelectInst>(LHS);
308 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
309 SI = cast<SelectInst>(RHS);
312 // Evaluate the BinOp on the true and false branches of the select.
316 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
317 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
319 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
320 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
323 // If they simplified to the same value, then return the common value.
324 // If they both failed to simplify then return null.
328 // If one branch simplified to undef, return the other one.
329 if (TV && isa<UndefValue>(TV))
331 if (FV && isa<UndefValue>(FV))
334 // If applying the operation did not change the true and false select values,
335 // then the result of the binop is the select itself.
336 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
339 // If one branch simplified and the other did not, and the simplified
340 // value is equal to the unsimplified one, return the simplified value.
341 // For example, select (cond, X, X & Z) & Z -> X & Z.
342 if ((FV && !TV) || (TV && !FV)) {
343 // Check that the simplified value has the form "X op Y" where "op" is the
344 // same as the original operation.
345 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
346 if (Simplified && Simplified->getOpcode() == Opcode) {
347 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
348 // We already know that "op" is the same as for the simplified value. See
349 // if the operands match too. If so, return the simplified value.
350 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
351 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
352 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
353 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
354 Simplified->getOperand(1) == UnsimplifiedRHS)
356 if (Simplified->isCommutative() &&
357 Simplified->getOperand(1) == UnsimplifiedLHS &&
358 Simplified->getOperand(0) == UnsimplifiedRHS)
366 /// In the case of a comparison with a select instruction, try to simplify the
367 /// comparison by seeing whether both branches of the select result in the same
368 /// value. Returns the common value if so, otherwise returns null.
369 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
370 Value *RHS, const Query &Q,
371 unsigned MaxRecurse) {
372 // Recursion is always used, so bail out at once if we already hit the limit.
376 // Make sure the select is on the LHS.
377 if (!isa<SelectInst>(LHS)) {
379 Pred = CmpInst::getSwappedPredicate(Pred);
381 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
382 SelectInst *SI = cast<SelectInst>(LHS);
383 Value *Cond = SI->getCondition();
384 Value *TV = SI->getTrueValue();
385 Value *FV = SI->getFalseValue();
387 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
388 // Does "cmp TV, RHS" simplify?
389 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
391 // It not only simplified, it simplified to the select condition. Replace
393 TCmp = getTrue(Cond->getType());
395 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
396 // condition then we can replace it with 'true'. Otherwise give up.
397 if (!isSameCompare(Cond, Pred, TV, RHS))
399 TCmp = getTrue(Cond->getType());
402 // Does "cmp FV, RHS" simplify?
403 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
405 // It not only simplified, it simplified to the select condition. Replace
407 FCmp = getFalse(Cond->getType());
409 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
410 // condition then we can replace it with 'false'. Otherwise give up.
411 if (!isSameCompare(Cond, Pred, FV, RHS))
413 FCmp = getFalse(Cond->getType());
416 // If both sides simplified to the same value, then use it as the result of
417 // the original comparison.
421 // The remaining cases only make sense if the select condition has the same
422 // type as the result of the comparison, so bail out if this is not so.
423 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
425 // If the false value simplified to false, then the result of the compare
426 // is equal to "Cond && TCmp". This also catches the case when the false
427 // value simplified to false and the true value to true, returning "Cond".
428 if (match(FCmp, m_Zero()))
429 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
431 // If the true value simplified to true, then the result of the compare
432 // is equal to "Cond || FCmp".
433 if (match(TCmp, m_One()))
434 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
436 // Finally, if the false value simplified to true and the true value to
437 // false, then the result of the compare is equal to "!Cond".
438 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
440 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
447 /// In the case of a binary operation with an operand that is a PHI instruction,
448 /// try to simplify the binop by seeing whether evaluating it on the incoming
449 /// phi values yields the same result for every value. If so returns the common
450 /// value, otherwise returns null.
451 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
452 const Query &Q, unsigned MaxRecurse) {
453 // Recursion is always used, so bail out at once if we already hit the limit.
458 if (isa<PHINode>(LHS)) {
459 PI = cast<PHINode>(LHS);
460 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
461 if (!ValueDominatesPHI(RHS, PI, Q.DT))
464 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
465 PI = cast<PHINode>(RHS);
466 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
467 if (!ValueDominatesPHI(LHS, PI, Q.DT))
471 // Evaluate the BinOp on the incoming phi values.
472 Value *CommonValue = nullptr;
473 for (Value *Incoming : PI->incoming_values()) {
474 // If the incoming value is the phi node itself, it can safely be skipped.
475 if (Incoming == PI) continue;
476 Value *V = PI == LHS ?
477 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
478 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
479 // If the operation failed to simplify, or simplified to a different value
480 // to previously, then give up.
481 if (!V || (CommonValue && V != CommonValue))
489 /// In the case of a comparison with a PHI instruction, try to simplify the
490 /// comparison by seeing whether comparing with all of the incoming phi values
491 /// yields the same result every time. If so returns the common result,
492 /// otherwise returns null.
493 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
494 const Query &Q, unsigned MaxRecurse) {
495 // Recursion is always used, so bail out at once if we already hit the limit.
499 // Make sure the phi is on the LHS.
500 if (!isa<PHINode>(LHS)) {
502 Pred = CmpInst::getSwappedPredicate(Pred);
504 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
505 PHINode *PI = cast<PHINode>(LHS);
507 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
508 if (!ValueDominatesPHI(RHS, PI, Q.DT))
511 // Evaluate the BinOp on the incoming phi values.
512 Value *CommonValue = nullptr;
513 for (Value *Incoming : PI->incoming_values()) {
514 // If the incoming value is the phi node itself, it can safely be skipped.
515 if (Incoming == PI) continue;
516 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
517 // If the operation failed to simplify, or simplified to a different value
518 // to previously, then give up.
519 if (!V || (CommonValue && V != CommonValue))
527 /// Given operands for an Add, see if we can fold the result.
528 /// If not, this returns null.
529 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
530 const Query &Q, unsigned MaxRecurse) {
531 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
532 if (Constant *CRHS = dyn_cast<Constant>(Op1))
533 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
535 // Canonicalize the constant to the RHS.
539 // X + undef -> undef
540 if (match(Op1, m_Undef()))
544 if (match(Op1, m_Zero()))
551 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
555 // X + ~X -> -1 since ~X = -X-1
556 if (match(Op0, m_Not(m_Specific(Op1))) ||
557 match(Op1, m_Not(m_Specific(Op0))))
558 return Constant::getAllOnesValue(Op0->getType());
561 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
562 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
565 // Try some generic simplifications for associative operations.
566 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
570 // Threading Add over selects and phi nodes is pointless, so don't bother.
571 // Threading over the select in "A + select(cond, B, C)" means evaluating
572 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573 // only if B and C are equal. If B and C are equal then (since we assume
574 // that operands have already been simplified) "select(cond, B, C)" should
575 // have been simplified to the common value of B and C already. Analysing
576 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
577 // for threading over phi nodes.
582 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
583 const DataLayout &DL, const TargetLibraryInfo *TLI,
584 const DominatorTree *DT, AssumptionCache *AC,
585 const Instruction *CxtI) {
586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
590 /// \brief Compute the base pointer and cumulative constant offsets for V.
592 /// This strips all constant offsets off of V, leaving it the base pointer, and
593 /// accumulates the total constant offset applied in the returned constant. It
594 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
595 /// no constant offsets applied.
597 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
600 static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
601 bool AllowNonInbounds = false) {
602 assert(V->getType()->getScalarType()->isPointerTy());
604 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
605 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
607 // Even though we don't look through PHI nodes, we could be called on an
608 // instruction in an unreachable block, which may be on a cycle.
609 SmallPtrSet<Value *, 4> Visited;
612 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
613 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
614 !GEP->accumulateConstantOffset(DL, Offset))
616 V = GEP->getPointerOperand();
617 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
618 V = cast<Operator>(V)->getOperand(0);
619 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
620 if (GA->isInterposable())
622 V = GA->getAliasee();
624 if (auto CS = CallSite(V))
625 if (Value *RV = CS.getReturnedArgOperand()) {
631 assert(V->getType()->getScalarType()->isPointerTy() &&
632 "Unexpected operand type!");
633 } while (Visited.insert(V).second);
635 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
636 if (V->getType()->isVectorTy())
637 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
642 /// \brief Compute the constant difference between two pointer values.
643 /// If the difference is not a constant, returns zero.
644 static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
646 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
647 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
649 // If LHS and RHS are not related via constant offsets to the same base
650 // value, there is nothing we can do here.
654 // Otherwise, the difference of LHS - RHS can be computed as:
656 // = (LHSOffset + Base) - (RHSOffset + Base)
657 // = LHSOffset - RHSOffset
658 return ConstantExpr::getSub(LHSOffset, RHSOffset);
661 /// Given operands for a Sub, see if we can fold the result.
662 /// If not, this returns null.
663 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
664 const Query &Q, unsigned MaxRecurse) {
665 if (Constant *CLHS = dyn_cast<Constant>(Op0))
666 if (Constant *CRHS = dyn_cast<Constant>(Op1))
667 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
669 // X - undef -> undef
670 // undef - X -> undef
671 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
672 return UndefValue::get(Op0->getType());
675 if (match(Op1, m_Zero()))
680 return Constant::getNullValue(Op0->getType());
682 // 0 - X -> 0 if the sub is NUW.
683 if (isNUW && match(Op0, m_Zero()))
686 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
687 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
688 Value *X = nullptr, *Y = nullptr, *Z = Op1;
689 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
690 // See if "V === Y - Z" simplifies.
691 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
692 // It does! Now see if "X + V" simplifies.
693 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
694 // It does, we successfully reassociated!
698 // See if "V === X - Z" simplifies.
699 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
700 // It does! Now see if "Y + V" simplifies.
701 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
702 // It does, we successfully reassociated!
708 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
709 // For example, X - (X + 1) -> -1
711 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
712 // See if "V === X - Y" simplifies.
713 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
714 // It does! Now see if "V - Z" simplifies.
715 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
716 // It does, we successfully reassociated!
720 // See if "V === X - Z" simplifies.
721 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
722 // It does! Now see if "V - Y" simplifies.
723 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
724 // It does, we successfully reassociated!
730 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
731 // For example, X - (X - Y) -> Y.
733 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
734 // See if "V === Z - X" simplifies.
735 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
736 // It does! Now see if "V + Y" simplifies.
737 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
738 // It does, we successfully reassociated!
743 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
744 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
745 match(Op1, m_Trunc(m_Value(Y))))
746 if (X->getType() == Y->getType())
747 // See if "V === X - Y" simplifies.
748 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
749 // It does! Now see if "trunc V" simplifies.
750 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
751 // It does, return the simplified "trunc V".
754 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
755 if (match(Op0, m_PtrToInt(m_Value(X))) &&
756 match(Op1, m_PtrToInt(m_Value(Y))))
757 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
758 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
761 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
762 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
765 // Threading Sub over selects and phi nodes is pointless, so don't bother.
766 // Threading over the select in "A - select(cond, B, C)" means evaluating
767 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
768 // only if B and C are equal. If B and C are equal then (since we assume
769 // that operands have already been simplified) "select(cond, B, C)" should
770 // have been simplified to the common value of B and C already. Analysing
771 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
772 // for threading over phi nodes.
777 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
778 const DataLayout &DL, const TargetLibraryInfo *TLI,
779 const DominatorTree *DT, AssumptionCache *AC,
780 const Instruction *CxtI) {
781 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
785 /// Given operands for an FAdd, see if we can fold the result. If not, this
787 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
788 const Query &Q, unsigned MaxRecurse) {
789 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
790 if (Constant *CRHS = dyn_cast<Constant>(Op1))
791 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
793 // Canonicalize the constant to the RHS.
798 if (match(Op1, m_NegZero()))
801 // fadd X, 0 ==> X, when we know X is not -0
802 if (match(Op1, m_Zero()) &&
803 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
806 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
807 // where nnan and ninf have to occur at least once somewhere in this
809 Value *SubOp = nullptr;
810 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
812 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
815 Instruction *FSub = cast<Instruction>(SubOp);
816 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
817 (FMF.noInfs() || FSub->hasNoInfs()))
818 return Constant::getNullValue(Op0->getType());
824 /// Given operands for an FSub, see if we can fold the result. If not, this
826 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
827 const Query &Q, unsigned MaxRecurse) {
828 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
829 if (Constant *CRHS = dyn_cast<Constant>(Op1))
830 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
834 if (match(Op1, m_Zero()))
837 // fsub X, -0 ==> X, when we know X is not -0
838 if (match(Op1, m_NegZero()) &&
839 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
842 // fsub -0.0, (fsub -0.0, X) ==> X
844 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
847 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
848 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
849 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
852 // fsub nnan x, x ==> 0.0
853 if (FMF.noNaNs() && Op0 == Op1)
854 return Constant::getNullValue(Op0->getType());
859 /// Given the operands for an FMul, see if we can fold the result
860 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
863 unsigned MaxRecurse) {
864 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
865 if (Constant *CRHS = dyn_cast<Constant>(Op1))
866 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
868 // Canonicalize the constant to the RHS.
873 if (match(Op1, m_FPOne()))
876 // fmul nnan nsz X, 0 ==> 0
877 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
883 /// Given operands for a Mul, see if we can fold the result.
884 /// If not, this returns null.
885 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
886 unsigned MaxRecurse) {
887 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
888 if (Constant *CRHS = dyn_cast<Constant>(Op1))
889 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
891 // Canonicalize the constant to the RHS.
896 if (match(Op1, m_Undef()))
897 return Constant::getNullValue(Op0->getType());
900 if (match(Op1, m_Zero()))
904 if (match(Op1, m_One()))
907 // (X / Y) * Y -> X if the division is exact.
909 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
910 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
914 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
915 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
918 // Try some generic simplifications for associative operations.
919 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
923 // Mul distributes over Add. Try some generic simplifications based on this.
924 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
928 // If the operation is with the result of a select instruction, check whether
929 // operating on either branch of the select always yields the same value.
930 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
931 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
935 // If the operation is with the result of a phi instruction, check whether
936 // operating on all incoming values of the phi always yields the same value.
937 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
938 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
945 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
946 const DataLayout &DL,
947 const TargetLibraryInfo *TLI,
948 const DominatorTree *DT, AssumptionCache *AC,
949 const Instruction *CxtI) {
950 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
954 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
955 const DataLayout &DL,
956 const TargetLibraryInfo *TLI,
957 const DominatorTree *DT, AssumptionCache *AC,
958 const Instruction *CxtI) {
959 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
963 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
964 const DataLayout &DL,
965 const TargetLibraryInfo *TLI,
966 const DominatorTree *DT, AssumptionCache *AC,
967 const Instruction *CxtI) {
968 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
972 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
973 const TargetLibraryInfo *TLI,
974 const DominatorTree *DT, AssumptionCache *AC,
975 const Instruction *CxtI) {
976 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
980 /// Given operands for an SDiv or UDiv, see if we can fold the result.
981 /// If not, this returns null.
982 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
983 const Query &Q, unsigned MaxRecurse) {
984 if (Constant *C0 = dyn_cast<Constant>(Op0))
985 if (Constant *C1 = dyn_cast<Constant>(Op1))
986 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
988 bool isSigned = Opcode == Instruction::SDiv;
990 // X / undef -> undef
991 if (match(Op1, m_Undef()))
994 // X / 0 -> undef, we don't need to preserve faults!
995 if (match(Op1, m_Zero()))
996 return UndefValue::get(Op1->getType());
999 if (match(Op0, m_Undef()))
1000 return Constant::getNullValue(Op0->getType());
1002 // 0 / X -> 0, we don't need to preserve faults!
1003 if (match(Op0, m_Zero()))
1007 if (match(Op1, m_One()))
1010 if (Op0->getType()->isIntegerTy(1))
1011 // It can't be division by zero, hence it must be division by one.
1016 return ConstantInt::get(Op0->getType(), 1);
1018 // (X * Y) / Y -> X if the multiplication does not overflow.
1019 Value *X = nullptr, *Y = nullptr;
1020 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1021 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1022 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1023 // If the Mul knows it does not overflow, then we are good to go.
1024 if ((isSigned && Mul->hasNoSignedWrap()) ||
1025 (!isSigned && Mul->hasNoUnsignedWrap()))
1027 // If X has the form X = A / Y then X * Y cannot overflow.
1028 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1029 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1033 // (X rem Y) / Y -> 0
1034 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1035 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1036 return Constant::getNullValue(Op0->getType());
1038 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1039 ConstantInt *C1, *C2;
1040 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1041 match(Op1, m_ConstantInt(C2))) {
1043 C1->getValue().umul_ov(C2->getValue(), Overflow);
1045 return Constant::getNullValue(Op0->getType());
1048 // If the operation is with the result of a select instruction, check whether
1049 // operating on either branch of the select always yields the same value.
1050 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1051 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1054 // If the operation is with the result of a phi instruction, check whether
1055 // operating on all incoming values of the phi always yields the same value.
1056 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1057 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1063 /// Given operands for an SDiv, see if we can fold the result.
1064 /// If not, this returns null.
1065 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1066 unsigned MaxRecurse) {
1067 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1073 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1074 const TargetLibraryInfo *TLI,
1075 const DominatorTree *DT, AssumptionCache *AC,
1076 const Instruction *CxtI) {
1077 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1081 /// Given operands for a UDiv, see if we can fold the result.
1082 /// If not, this returns null.
1083 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1084 unsigned MaxRecurse) {
1085 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1091 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
1092 const TargetLibraryInfo *TLI,
1093 const DominatorTree *DT, AssumptionCache *AC,
1094 const Instruction *CxtI) {
1095 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1099 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1100 const Query &Q, unsigned) {
1101 // undef / X -> undef (the undef could be a snan).
1102 if (match(Op0, m_Undef()))
1105 // X / undef -> undef
1106 if (match(Op1, m_Undef()))
1110 // Requires that NaNs are off (X could be zero) and signed zeroes are
1111 // ignored (X could be positive or negative, so the output sign is unknown).
1112 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1116 // X / X -> 1.0 is legal when NaNs are ignored.
1118 return ConstantFP::get(Op0->getType(), 1.0);
1120 // -X / X -> -1.0 and
1121 // X / -X -> -1.0 are legal when NaNs are ignored.
1122 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1123 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1124 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1125 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1126 BinaryOperator::getFNegArgument(Op1) == Op0))
1127 return ConstantFP::get(Op0->getType(), -1.0);
1133 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1134 const DataLayout &DL,
1135 const TargetLibraryInfo *TLI,
1136 const DominatorTree *DT, AssumptionCache *AC,
1137 const Instruction *CxtI) {
1138 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1142 /// Given operands for an SRem or URem, see if we can fold the result.
1143 /// If not, this returns null.
1144 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1145 const Query &Q, unsigned MaxRecurse) {
1146 if (Constant *C0 = dyn_cast<Constant>(Op0))
1147 if (Constant *C1 = dyn_cast<Constant>(Op1))
1148 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1150 // X % undef -> undef
1151 if (match(Op1, m_Undef()))
1155 if (match(Op0, m_Undef()))
1156 return Constant::getNullValue(Op0->getType());
1158 // 0 % X -> 0, we don't need to preserve faults!
1159 if (match(Op0, m_Zero()))
1162 // X % 0 -> undef, we don't need to preserve faults!
1163 if (match(Op1, m_Zero()))
1164 return UndefValue::get(Op0->getType());
1167 if (match(Op1, m_One()))
1168 return Constant::getNullValue(Op0->getType());
1170 if (Op0->getType()->isIntegerTy(1))
1171 // It can't be remainder by zero, hence it must be remainder by one.
1172 return Constant::getNullValue(Op0->getType());
1176 return Constant::getNullValue(Op0->getType());
1178 // (X % Y) % Y -> X % Y
1179 if ((Opcode == Instruction::SRem &&
1180 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1181 (Opcode == Instruction::URem &&
1182 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1185 // If the operation is with the result of a select instruction, check whether
1186 // operating on either branch of the select always yields the same value.
1187 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1188 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1191 // If the operation is with the result of a phi instruction, check whether
1192 // operating on all incoming values of the phi always yields the same value.
1193 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1194 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1200 /// Given operands for an SRem, see if we can fold the result.
1201 /// If not, this returns null.
1202 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1203 unsigned MaxRecurse) {
1204 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1210 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1211 const TargetLibraryInfo *TLI,
1212 const DominatorTree *DT, AssumptionCache *AC,
1213 const Instruction *CxtI) {
1214 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1218 /// Given operands for a URem, see if we can fold the result.
1219 /// If not, this returns null.
1220 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1221 unsigned MaxRecurse) {
1222 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1228 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
1229 const TargetLibraryInfo *TLI,
1230 const DominatorTree *DT, AssumptionCache *AC,
1231 const Instruction *CxtI) {
1232 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1236 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1237 const Query &, unsigned) {
1238 // undef % X -> undef (the undef could be a snan).
1239 if (match(Op0, m_Undef()))
1242 // X % undef -> undef
1243 if (match(Op1, m_Undef()))
1247 // Requires that NaNs are off (X could be zero) and signed zeroes are
1248 // ignored (X could be positive or negative, so the output sign is unknown).
1249 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1255 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1256 const DataLayout &DL,
1257 const TargetLibraryInfo *TLI,
1258 const DominatorTree *DT, AssumptionCache *AC,
1259 const Instruction *CxtI) {
1260 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
1264 /// Returns true if a shift by \c Amount always yields undef.
1265 static bool isUndefShift(Value *Amount) {
1266 Constant *C = dyn_cast<Constant>(Amount);
1270 // X shift by undef -> undef because it may shift by the bitwidth.
1271 if (isa<UndefValue>(C))
1274 // Shifting by the bitwidth or more is undefined.
1275 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1276 if (CI->getValue().getLimitedValue() >=
1277 CI->getType()->getScalarSizeInBits())
1280 // If all lanes of a vector shift are undefined the whole shift is.
1281 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1282 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1283 if (!isUndefShift(C->getAggregateElement(I)))
1291 /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1292 /// If not, this returns null.
1293 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1294 const Query &Q, unsigned MaxRecurse) {
1295 if (Constant *C0 = dyn_cast<Constant>(Op0))
1296 if (Constant *C1 = dyn_cast<Constant>(Op1))
1297 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
1299 // 0 shift by X -> 0
1300 if (match(Op0, m_Zero()))
1303 // X shift by 0 -> X
1304 if (match(Op1, m_Zero()))
1307 // Fold undefined shifts.
1308 if (isUndefShift(Op1))
1309 return UndefValue::get(Op0->getType());
1311 // If the operation is with the result of a select instruction, check whether
1312 // operating on either branch of the select always yields the same value.
1313 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1314 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1317 // If the operation is with the result of a phi instruction, check whether
1318 // operating on all incoming values of the phi always yields the same value.
1319 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1320 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1323 // If any bits in the shift amount make that value greater than or equal to
1324 // the number of bits in the type, the shift is undefined.
1325 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1326 APInt KnownZero(BitWidth, 0);
1327 APInt KnownOne(BitWidth, 0);
1328 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1329 if (KnownOne.getLimitedValue() >= BitWidth)
1330 return UndefValue::get(Op0->getType());
1332 // If all valid bits in the shift amount are known zero, the first operand is
1334 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1335 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1336 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1342 /// \brief Given operands for an Shl, LShr or AShr, see if we can
1343 /// fold the result. If not, this returns null.
1344 static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1345 bool isExact, const Query &Q,
1346 unsigned MaxRecurse) {
1347 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1352 return Constant::getNullValue(Op0->getType());
1355 // undef >> X -> undef (if it's exact)
1356 if (match(Op0, m_Undef()))
1357 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1359 // The low bit cannot be shifted out of an exact shift if it is set.
1361 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1362 APInt Op0KnownZero(BitWidth, 0);
1363 APInt Op0KnownOne(BitWidth, 0);
1364 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1373 /// Given operands for an Shl, see if we can fold the result.
1374 /// If not, this returns null.
1375 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1376 const Query &Q, unsigned MaxRecurse) {
1377 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1381 // undef << X -> undef if (if it's NSW/NUW)
1382 if (match(Op0, m_Undef()))
1383 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
1385 // (X >> A) << A -> X
1387 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1392 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1393 const DataLayout &DL, const TargetLibraryInfo *TLI,
1394 const DominatorTree *DT, AssumptionCache *AC,
1395 const Instruction *CxtI) {
1396 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
1400 /// Given operands for an LShr, see if we can fold the result.
1401 /// If not, this returns null.
1402 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1403 const Query &Q, unsigned MaxRecurse) {
1404 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1408 // (X << A) >> A -> X
1410 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
1416 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1417 const DataLayout &DL,
1418 const TargetLibraryInfo *TLI,
1419 const DominatorTree *DT, AssumptionCache *AC,
1420 const Instruction *CxtI) {
1421 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1425 /// Given operands for an AShr, see if we can fold the result.
1426 /// If not, this returns null.
1427 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1428 const Query &Q, unsigned MaxRecurse) {
1429 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1433 // all ones >>a X -> all ones
1434 if (match(Op0, m_AllOnes()))
1437 // (X << A) >> A -> X
1439 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
1442 // Arithmetic shifting an all-sign-bit value is a no-op.
1443 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1444 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1450 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1451 const DataLayout &DL,
1452 const TargetLibraryInfo *TLI,
1453 const DominatorTree *DT, AssumptionCache *AC,
1454 const Instruction *CxtI) {
1455 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
1459 static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1460 ICmpInst *UnsignedICmp, bool IsAnd) {
1463 ICmpInst::Predicate EqPred;
1464 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1465 !ICmpInst::isEquality(EqPred))
1468 ICmpInst::Predicate UnsignedPred;
1469 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1470 ICmpInst::isUnsigned(UnsignedPred))
1472 else if (match(UnsignedICmp,
1473 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1474 ICmpInst::isUnsigned(UnsignedPred))
1475 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1479 // X < Y && Y != 0 --> X < Y
1480 // X < Y || Y != 0 --> Y != 0
1481 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1482 return IsAnd ? UnsignedICmp : ZeroICmp;
1484 // X >= Y || Y != 0 --> true
1485 // X >= Y || Y == 0 --> X >= Y
1486 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1487 if (EqPred == ICmpInst::ICMP_NE)
1488 return getTrue(UnsignedICmp->getType());
1489 return UnsignedICmp;
1492 // X < Y && Y == 0 --> false
1493 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1495 return getFalse(UnsignedICmp->getType());
1500 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1501 Type *ITy = Op0->getType();
1502 ICmpInst::Predicate Pred0, Pred1;
1503 ConstantInt *CI1, *CI2;
1506 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1509 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
1510 const APInt *C0, *C1;
1511 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1512 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1513 // Make a constant range that's the intersection of the two icmp ranges.
1514 // If the intersection is empty, we know that the result is false.
1515 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1516 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1517 if (Range0.intersectWith(Range1).isEmptySet())
1518 return getFalse(ITy);
1521 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1522 m_ConstantInt(CI2))))
1525 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1528 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1529 bool isNSW = AddInst->hasNoSignedWrap();
1530 bool isNUW = AddInst->hasNoUnsignedWrap();
1532 const APInt &CI1V = CI1->getValue();
1533 const APInt &CI2V = CI2->getValue();
1534 const APInt Delta = CI2V - CI1V;
1535 if (CI1V.isStrictlyPositive()) {
1537 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1538 return getFalse(ITy);
1539 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1540 return getFalse(ITy);
1543 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1544 return getFalse(ITy);
1545 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1546 return getFalse(ITy);
1549 if (CI1V.getBoolValue() && isNUW) {
1551 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1552 return getFalse(ITy);
1554 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1555 return getFalse(ITy);
1561 /// Given operands for an And, see if we can fold the result.
1562 /// If not, this returns null.
1563 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1564 unsigned MaxRecurse) {
1565 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1566 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1567 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
1569 // Canonicalize the constant to the RHS.
1570 std::swap(Op0, Op1);
1574 if (match(Op1, m_Undef()))
1575 return Constant::getNullValue(Op0->getType());
1582 if (match(Op1, m_Zero()))
1586 if (match(Op1, m_AllOnes()))
1589 // A & ~A = ~A & A = 0
1590 if (match(Op0, m_Not(m_Specific(Op1))) ||
1591 match(Op1, m_Not(m_Specific(Op0))))
1592 return Constant::getNullValue(Op0->getType());
1595 Value *A = nullptr, *B = nullptr;
1596 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1597 (A == Op1 || B == Op1))
1601 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1602 (A == Op0 || B == Op0))
1605 // A & (-A) = A if A is a power of two or zero.
1606 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1607 match(Op1, m_Neg(m_Specific(Op0)))) {
1608 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1611 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1616 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1617 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1618 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1620 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1625 // The compares may be hidden behind casts. Look through those and try the
1626 // same folds as above.
1627 auto *Cast0 = dyn_cast<CastInst>(Op0);
1628 auto *Cast1 = dyn_cast<CastInst>(Op1);
1629 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1630 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1631 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1632 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1634 Instruction::CastOps CastOpc = Cast0->getOpcode();
1635 Type *ResultType = Cast0->getType();
1636 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1637 return ConstantExpr::getCast(CastOpc, V, ResultType);
1638 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1639 return ConstantExpr::getCast(CastOpc, V, ResultType);
1643 // Try some generic simplifications for associative operations.
1644 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1648 // And distributes over Or. Try some generic simplifications based on this.
1649 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1653 // And distributes over Xor. Try some generic simplifications based on this.
1654 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1658 // If the operation is with the result of a select instruction, check whether
1659 // operating on either branch of the select always yields the same value.
1660 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1661 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1665 // If the operation is with the result of a phi instruction, check whether
1666 // operating on all incoming values of the phi always yields the same value.
1667 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1668 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1675 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
1676 const TargetLibraryInfo *TLI,
1677 const DominatorTree *DT, AssumptionCache *AC,
1678 const Instruction *CxtI) {
1679 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1683 /// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1684 /// contains all possible values.
1685 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1686 ICmpInst::Predicate Pred0, Pred1;
1687 ConstantInt *CI1, *CI2;
1690 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1693 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1694 m_ConstantInt(CI2))))
1697 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1700 Type *ITy = Op0->getType();
1702 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1703 bool isNSW = AddInst->hasNoSignedWrap();
1704 bool isNUW = AddInst->hasNoUnsignedWrap();
1706 const APInt &CI1V = CI1->getValue();
1707 const APInt &CI2V = CI2->getValue();
1708 const APInt Delta = CI2V - CI1V;
1709 if (CI1V.isStrictlyPositive()) {
1711 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1712 return getTrue(ITy);
1713 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1714 return getTrue(ITy);
1717 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1718 return getTrue(ITy);
1719 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1720 return getTrue(ITy);
1723 if (CI1V.getBoolValue() && isNUW) {
1725 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1726 return getTrue(ITy);
1728 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1729 return getTrue(ITy);
1735 /// Given operands for an Or, see if we can fold the result.
1736 /// If not, this returns null.
1737 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1738 unsigned MaxRecurse) {
1739 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1740 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1741 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
1743 // Canonicalize the constant to the RHS.
1744 std::swap(Op0, Op1);
1748 if (match(Op1, m_Undef()))
1749 return Constant::getAllOnesValue(Op0->getType());
1756 if (match(Op1, m_Zero()))
1760 if (match(Op1, m_AllOnes()))
1763 // A | ~A = ~A | A = -1
1764 if (match(Op0, m_Not(m_Specific(Op1))) ||
1765 match(Op1, m_Not(m_Specific(Op0))))
1766 return Constant::getAllOnesValue(Op0->getType());
1769 Value *A = nullptr, *B = nullptr;
1770 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1771 (A == Op1 || B == Op1))
1775 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1776 (A == Op0 || B == Op0))
1779 // ~(A & ?) | A = -1
1780 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1781 (A == Op1 || B == Op1))
1782 return Constant::getAllOnesValue(Op1->getType());
1784 // A | ~(A & ?) = -1
1785 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1786 (A == Op0 || B == Op0))
1787 return Constant::getAllOnesValue(Op0->getType());
1789 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1790 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1791 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1793 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1798 // Try some generic simplifications for associative operations.
1799 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1803 // Or distributes over And. Try some generic simplifications based on this.
1804 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1808 // If the operation is with the result of a select instruction, check whether
1809 // operating on either branch of the select always yields the same value.
1810 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1811 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1816 Value *C = nullptr, *D = nullptr;
1817 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1818 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1819 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1820 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1821 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1822 // (A & C1)|(B & C2)
1823 // If we have: ((V + N) & C1) | (V & C2)
1824 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1825 // replace with V+N.
1827 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1828 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1829 // Add commutes, try both ways.
1831 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1834 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1837 // Or commutes, try both ways.
1838 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1839 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1840 // Add commutes, try both ways.
1842 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1845 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
1851 // If the operation is with the result of a phi instruction, check whether
1852 // operating on all incoming values of the phi always yields the same value.
1853 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1854 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1860 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
1861 const TargetLibraryInfo *TLI,
1862 const DominatorTree *DT, AssumptionCache *AC,
1863 const Instruction *CxtI) {
1864 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1868 /// Given operands for a Xor, see if we can fold the result.
1869 /// If not, this returns null.
1870 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1871 unsigned MaxRecurse) {
1872 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1873 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1874 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
1876 // Canonicalize the constant to the RHS.
1877 std::swap(Op0, Op1);
1880 // A ^ undef -> undef
1881 if (match(Op1, m_Undef()))
1885 if (match(Op1, m_Zero()))
1890 return Constant::getNullValue(Op0->getType());
1892 // A ^ ~A = ~A ^ A = -1
1893 if (match(Op0, m_Not(m_Specific(Op1))) ||
1894 match(Op1, m_Not(m_Specific(Op0))))
1895 return Constant::getAllOnesValue(Op0->getType());
1897 // Try some generic simplifications for associative operations.
1898 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1902 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1903 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1904 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1905 // only if B and C are equal. If B and C are equal then (since we assume
1906 // that operands have already been simplified) "select(cond, B, C)" should
1907 // have been simplified to the common value of B and C already. Analysing
1908 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1909 // for threading over phi nodes.
1914 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
1915 const TargetLibraryInfo *TLI,
1916 const DominatorTree *DT, AssumptionCache *AC,
1917 const Instruction *CxtI) {
1918 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
1922 static Type *GetCompareTy(Value *Op) {
1923 return CmpInst::makeCmpResultType(Op->getType());
1926 /// Rummage around inside V looking for something equivalent to the comparison
1927 /// "LHS Pred RHS". Return such a value if found, otherwise return null.
1928 /// Helper function for analyzing max/min idioms.
1929 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1930 Value *LHS, Value *RHS) {
1931 SelectInst *SI = dyn_cast<SelectInst>(V);
1934 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1937 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1938 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1940 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1941 LHS == CmpRHS && RHS == CmpLHS)
1946 // A significant optimization not implemented here is assuming that alloca
1947 // addresses are not equal to incoming argument values. They don't *alias*,
1948 // as we say, but that doesn't mean they aren't equal, so we take a
1949 // conservative approach.
1951 // This is inspired in part by C++11 5.10p1:
1952 // "Two pointers of the same type compare equal if and only if they are both
1953 // null, both point to the same function, or both represent the same
1956 // This is pretty permissive.
1958 // It's also partly due to C11 6.5.9p6:
1959 // "Two pointers compare equal if and only if both are null pointers, both are
1960 // pointers to the same object (including a pointer to an object and a
1961 // subobject at its beginning) or function, both are pointers to one past the
1962 // last element of the same array object, or one is a pointer to one past the
1963 // end of one array object and the other is a pointer to the start of a
1964 // different array object that happens to immediately follow the first array
1965 // object in the address space.)
1967 // C11's version is more restrictive, however there's no reason why an argument
1968 // couldn't be a one-past-the-end value for a stack object in the caller and be
1969 // equal to the beginning of a stack object in the callee.
1971 // If the C and C++ standards are ever made sufficiently restrictive in this
1972 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1973 // this optimization.
1975 computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1976 const DominatorTree *DT, CmpInst::Predicate Pred,
1977 const Instruction *CxtI, Value *LHS, Value *RHS) {
1978 // First, skip past any trivial no-ops.
1979 LHS = LHS->stripPointerCasts();
1980 RHS = RHS->stripPointerCasts();
1982 // A non-null pointer is not equal to a null pointer.
1983 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
1984 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1985 return ConstantInt::get(GetCompareTy(LHS),
1986 !CmpInst::isTrueWhenEqual(Pred));
1988 // We can only fold certain predicates on pointer comparisons.
1993 // Equality comaprisons are easy to fold.
1994 case CmpInst::ICMP_EQ:
1995 case CmpInst::ICMP_NE:
1998 // We can only handle unsigned relational comparisons because 'inbounds' on
1999 // a GEP only protects against unsigned wrapping.
2000 case CmpInst::ICMP_UGT:
2001 case CmpInst::ICMP_UGE:
2002 case CmpInst::ICMP_ULT:
2003 case CmpInst::ICMP_ULE:
2004 // However, we have to switch them to their signed variants to handle
2005 // negative indices from the base pointer.
2006 Pred = ICmpInst::getSignedPredicate(Pred);
2010 // Strip off any constant offsets so that we can reason about them.
2011 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2012 // here and compare base addresses like AliasAnalysis does, however there are
2013 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2014 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2015 // doesn't need to guarantee pointer inequality when it says NoAlias.
2016 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2017 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
2019 // If LHS and RHS are related via constant offsets to the same base
2020 // value, we can replace it with an icmp which just compares the offsets.
2022 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
2024 // Various optimizations for (in)equality comparisons.
2025 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2026 // Different non-empty allocations that exist at the same time have
2027 // different addresses (if the program can tell). Global variables always
2028 // exist, so they always exist during the lifetime of each other and all
2029 // allocas. Two different allocas usually have different addresses...
2031 // However, if there's an @llvm.stackrestore dynamically in between two
2032 // allocas, they may have the same address. It's tempting to reduce the
2033 // scope of the problem by only looking at *static* allocas here. That would
2034 // cover the majority of allocas while significantly reducing the likelihood
2035 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2036 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2037 // an entry block. Also, if we have a block that's not attached to a
2038 // function, we can't tell if it's "static" under the current definition.
2039 // Theoretically, this problem could be fixed by creating a new kind of
2040 // instruction kind specifically for static allocas. Such a new instruction
2041 // could be required to be at the top of the entry block, thus preventing it
2042 // from being subject to a @llvm.stackrestore. Instcombine could even
2043 // convert regular allocas into these special allocas. It'd be nifty.
2044 // However, until then, this problem remains open.
2046 // So, we'll assume that two non-empty allocas have different addresses
2049 // With all that, if the offsets are within the bounds of their allocations
2050 // (and not one-past-the-end! so we can't use inbounds!), and their
2051 // allocations aren't the same, the pointers are not equal.
2053 // Note that it's not necessary to check for LHS being a global variable
2054 // address, due to canonicalization and constant folding.
2055 if (isa<AllocaInst>(LHS) &&
2056 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
2057 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2058 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
2059 uint64_t LHSSize, RHSSize;
2060 if (LHSOffsetCI && RHSOffsetCI &&
2061 getObjectSize(LHS, LHSSize, DL, TLI) &&
2062 getObjectSize(RHS, RHSSize, DL, TLI)) {
2063 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2064 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
2065 if (!LHSOffsetValue.isNegative() &&
2066 !RHSOffsetValue.isNegative() &&
2067 LHSOffsetValue.ult(LHSSize) &&
2068 RHSOffsetValue.ult(RHSSize)) {
2069 return ConstantInt::get(GetCompareTy(LHS),
2070 !CmpInst::isTrueWhenEqual(Pred));
2074 // Repeat the above check but this time without depending on DataLayout
2075 // or being able to compute a precise size.
2076 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2077 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2078 LHSOffset->isNullValue() &&
2079 RHSOffset->isNullValue())
2080 return ConstantInt::get(GetCompareTy(LHS),
2081 !CmpInst::isTrueWhenEqual(Pred));
2084 // Even if an non-inbounds GEP occurs along the path we can still optimize
2085 // equality comparisons concerning the result. We avoid walking the whole
2086 // chain again by starting where the last calls to
2087 // stripAndComputeConstantOffsets left off and accumulate the offsets.
2088 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2089 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
2091 return ConstantExpr::getICmp(Pred,
2092 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2093 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2095 // If one side of the equality comparison must come from a noalias call
2096 // (meaning a system memory allocation function), and the other side must
2097 // come from a pointer that cannot overlap with dynamically-allocated
2098 // memory within the lifetime of the current function (allocas, byval
2099 // arguments, globals), then determine the comparison result here.
2100 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2101 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2102 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2104 // Is the set of underlying objects all noalias calls?
2105 auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
2106 return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
2109 // Is the set of underlying objects all things which must be disjoint from
2110 // noalias calls. For allocas, we consider only static ones (dynamic
2111 // allocas might be transformed into calls to malloc not simultaneously
2112 // live with the compared-to allocation). For globals, we exclude symbols
2113 // that might be resolve lazily to symbols in another dynamically-loaded
2114 // library (and, thus, could be malloc'ed by the implementation).
2115 auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
2116 return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2117 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2118 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2119 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2120 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
2121 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
2122 !GV->isThreadLocal();
2123 if (const Argument *A = dyn_cast<Argument>(V))
2124 return A->hasByValAttr();
2129 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2130 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2131 return ConstantInt::get(GetCompareTy(LHS),
2132 !CmpInst::isTrueWhenEqual(Pred));
2134 // Fold comparisons for non-escaping pointer even if the allocation call
2135 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2136 // dynamic allocation call could be either of the operands.
2137 Value *MI = nullptr;
2138 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
2140 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
2142 // FIXME: We should also fold the compare when the pointer escapes, but the
2143 // compare dominates the pointer escape
2144 if (MI && !PointerMayBeCaptured(MI, true, true))
2145 return ConstantInt::get(GetCompareTy(LHS),
2146 CmpInst::isFalseWhenEqual(Pred));
2153 /// Given operands for an ICmpInst, see if we can fold the result.
2154 /// If not, this returns null.
2155 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2156 const Query &Q, unsigned MaxRecurse) {
2157 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2158 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2160 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2161 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2162 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2164 // If we have a constant, make sure it is on the RHS.
2165 std::swap(LHS, RHS);
2166 Pred = CmpInst::getSwappedPredicate(Pred);
2169 Type *ITy = GetCompareTy(LHS); // The return type.
2170 Type *OpTy = LHS->getType(); // The operand type.
2172 // icmp X, X -> true/false
2173 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2174 // because X could be 0.
2175 if (LHS == RHS || isa<UndefValue>(RHS))
2176 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2178 // Special case logic when the operands have i1 type.
2179 if (OpTy->getScalarType()->isIntegerTy(1)) {
2182 case ICmpInst::ICMP_EQ:
2184 if (match(RHS, m_One()))
2187 case ICmpInst::ICMP_NE:
2189 if (match(RHS, m_Zero()))
2192 case ICmpInst::ICMP_UGT:
2194 if (match(RHS, m_Zero()))
2197 case ICmpInst::ICMP_UGE: {
2199 if (match(RHS, m_One()))
2201 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2202 return getTrue(ITy);
2205 case ICmpInst::ICMP_SGE: {
2206 /// For signed comparison, the values for an i1 are 0 and -1
2207 /// respectively. This maps into a truth table of:
2208 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2209 /// 0 | 0 | 1 (0 >= 0) | 1
2210 /// 0 | 1 | 1 (0 >= -1) | 1
2211 /// 1 | 0 | 0 (-1 >= 0) | 0
2212 /// 1 | 1 | 1 (-1 >= -1) | 1
2213 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2214 return getTrue(ITy);
2217 case ICmpInst::ICMP_SLT:
2219 if (match(RHS, m_Zero()))
2222 case ICmpInst::ICMP_SLE:
2224 if (match(RHS, m_One()))
2227 case ICmpInst::ICMP_ULE: {
2228 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2229 return getTrue(ITy);
2235 // If we are comparing with zero then try hard since this is a common case.
2236 if (match(RHS, m_Zero())) {
2237 bool LHSKnownNonNegative, LHSKnownNegative;
2239 default: llvm_unreachable("Unknown ICmp predicate!");
2240 case ICmpInst::ICMP_ULT:
2241 return getFalse(ITy);
2242 case ICmpInst::ICMP_UGE:
2243 return getTrue(ITy);
2244 case ICmpInst::ICMP_EQ:
2245 case ICmpInst::ICMP_ULE:
2246 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2247 return getFalse(ITy);
2249 case ICmpInst::ICMP_NE:
2250 case ICmpInst::ICMP_UGT:
2251 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2252 return getTrue(ITy);
2254 case ICmpInst::ICMP_SLT:
2255 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2257 if (LHSKnownNegative)
2258 return getTrue(ITy);
2259 if (LHSKnownNonNegative)
2260 return getFalse(ITy);
2262 case ICmpInst::ICMP_SLE:
2263 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2265 if (LHSKnownNegative)
2266 return getTrue(ITy);
2267 if (LHSKnownNonNegative &&
2268 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2269 return getFalse(ITy);
2271 case ICmpInst::ICMP_SGE:
2272 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2274 if (LHSKnownNegative)
2275 return getFalse(ITy);
2276 if (LHSKnownNonNegative)
2277 return getTrue(ITy);
2279 case ICmpInst::ICMP_SGT:
2280 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2282 if (LHSKnownNegative)
2283 return getFalse(ITy);
2284 if (LHSKnownNonNegative &&
2285 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
2286 return getTrue(ITy);
2291 // See if we are doing a comparison with a constant integer.
2292 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2293 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2294 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2295 if (RHS_CR.isEmptySet())
2296 return ConstantInt::getFalse(CI->getContext());
2297 if (RHS_CR.isFullSet())
2298 return ConstantInt::getTrue(CI->getContext());
2300 // Many binary operators with constant RHS have easy to compute constant
2301 // range. Use them to check whether the comparison is a tautology.
2302 unsigned Width = CI->getBitWidth();
2303 APInt Lower = APInt(Width, 0);
2304 APInt Upper = APInt(Width, 0);
2306 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2307 // 'urem x, CI2' produces [0, CI2).
2308 Upper = CI2->getValue();
2309 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2310 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2311 Upper = CI2->getValue().abs();
2312 Lower = (-Upper) + 1;
2313 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2314 // 'udiv CI2, x' produces [0, CI2].
2315 Upper = CI2->getValue() + 1;
2316 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2317 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2318 APInt NegOne = APInt::getAllOnesValue(Width);
2320 Upper = NegOne.udiv(CI2->getValue()) + 1;
2321 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2322 if (CI2->isMinSignedValue()) {
2323 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2324 Lower = CI2->getValue();
2325 Upper = Lower.lshr(1) + 1;
2327 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2328 Upper = CI2->getValue().abs() + 1;
2329 Lower = (-Upper) + 1;
2331 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2332 APInt IntMin = APInt::getSignedMinValue(Width);
2333 APInt IntMax = APInt::getSignedMaxValue(Width);
2334 const APInt &Val = CI2->getValue();
2335 if (Val.isAllOnesValue()) {
2336 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2337 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2340 } else if (Val.countLeadingZeros() < Width - 1) {
2341 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2342 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2343 Lower = IntMin.sdiv(Val);
2344 Upper = IntMax.sdiv(Val);
2345 if (Lower.sgt(Upper))
2346 std::swap(Lower, Upper);
2348 assert(Upper != Lower && "Upper part of range has wrapped!");
2350 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2351 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2352 Lower = CI2->getValue();
2353 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2354 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2355 if (CI2->isNegative()) {
2356 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2357 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2358 Lower = CI2->getValue().shl(ShiftAmount);
2359 Upper = CI2->getValue() + 1;
2361 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2362 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2363 Lower = CI2->getValue();
2364 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2366 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2367 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2368 APInt NegOne = APInt::getAllOnesValue(Width);
2369 if (CI2->getValue().ult(Width))
2370 Upper = NegOne.lshr(CI2->getValue()) + 1;
2371 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2372 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2373 unsigned ShiftAmount = Width - 1;
2374 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2375 ShiftAmount = CI2->getValue().countTrailingZeros();
2376 Lower = CI2->getValue().lshr(ShiftAmount);
2377 Upper = CI2->getValue() + 1;
2378 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2379 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2380 APInt IntMin = APInt::getSignedMinValue(Width);
2381 APInt IntMax = APInt::getSignedMaxValue(Width);
2382 if (CI2->getValue().ult(Width)) {
2383 Lower = IntMin.ashr(CI2->getValue());
2384 Upper = IntMax.ashr(CI2->getValue()) + 1;
2386 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2387 unsigned ShiftAmount = Width - 1;
2388 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2389 ShiftAmount = CI2->getValue().countTrailingZeros();
2390 if (CI2->isNegative()) {
2391 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2392 Lower = CI2->getValue();
2393 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2395 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2396 Lower = CI2->getValue().ashr(ShiftAmount);
2397 Upper = CI2->getValue() + 1;
2399 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2400 // 'or x, CI2' produces [CI2, UINT_MAX].
2401 Lower = CI2->getValue();
2402 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2403 // 'and x, CI2' produces [0, CI2].
2404 Upper = CI2->getValue() + 1;
2405 } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2406 // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2407 Lower = CI2->getValue();
2410 ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2411 : ConstantRange(Width, true);
2413 if (auto *I = dyn_cast<Instruction>(LHS))
2414 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2415 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2417 if (!LHS_CR.isFullSet()) {
2418 if (RHS_CR.contains(LHS_CR))
2419 return ConstantInt::getTrue(RHS->getContext());
2420 if (RHS_CR.inverse().contains(LHS_CR))
2421 return ConstantInt::getFalse(RHS->getContext());
2425 // If both operands have range metadata, use the metadata
2426 // to simplify the comparison.
2427 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2428 auto RHS_Instr = dyn_cast<Instruction>(RHS);
2429 auto LHS_Instr = dyn_cast<Instruction>(LHS);
2431 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2432 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
2433 auto RHS_CR = getConstantRangeFromMetadata(
2434 *RHS_Instr->getMetadata(LLVMContext::MD_range));
2435 auto LHS_CR = getConstantRangeFromMetadata(
2436 *LHS_Instr->getMetadata(LLVMContext::MD_range));
2438 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2439 if (Satisfied_CR.contains(LHS_CR))
2440 return ConstantInt::getTrue(RHS->getContext());
2442 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2443 CmpInst::getInversePredicate(Pred), RHS_CR);
2444 if (InversedSatisfied_CR.contains(LHS_CR))
2445 return ConstantInt::getFalse(RHS->getContext());
2449 // Compare of cast, for example (zext X) != 0 -> X != 0
2450 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2451 Instruction *LI = cast<CastInst>(LHS);
2452 Value *SrcOp = LI->getOperand(0);
2453 Type *SrcTy = SrcOp->getType();
2454 Type *DstTy = LI->getType();
2456 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2457 // if the integer type is the same size as the pointer type.
2458 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2459 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2460 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2461 // Transfer the cast to the constant.
2462 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2463 ConstantExpr::getIntToPtr(RHSC, SrcTy),
2466 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2467 if (RI->getOperand(0)->getType() == SrcTy)
2468 // Compare without the cast.
2469 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2475 if (isa<ZExtInst>(LHS)) {
2476 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2478 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2479 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2480 // Compare X and Y. Note that signed predicates become unsigned.
2481 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2482 SrcOp, RI->getOperand(0), Q,
2486 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2487 // too. If not, then try to deduce the result of the comparison.
2488 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2489 // Compute the constant that would happen if we truncated to SrcTy then
2490 // reextended to DstTy.
2491 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2492 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2494 // If the re-extended constant didn't change then this is effectively
2495 // also a case of comparing two zero-extended values.
2496 if (RExt == CI && MaxRecurse)
2497 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2498 SrcOp, Trunc, Q, MaxRecurse-1))
2501 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2502 // there. Use this to work out the result of the comparison.
2505 default: llvm_unreachable("Unknown ICmp predicate!");
2507 case ICmpInst::ICMP_EQ:
2508 case ICmpInst::ICMP_UGT:
2509 case ICmpInst::ICMP_UGE:
2510 return ConstantInt::getFalse(CI->getContext());
2512 case ICmpInst::ICMP_NE:
2513 case ICmpInst::ICMP_ULT:
2514 case ICmpInst::ICMP_ULE:
2515 return ConstantInt::getTrue(CI->getContext());
2517 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2518 // is non-negative then LHS <s RHS.
2519 case ICmpInst::ICMP_SGT:
2520 case ICmpInst::ICMP_SGE:
2521 return CI->getValue().isNegative() ?
2522 ConstantInt::getTrue(CI->getContext()) :
2523 ConstantInt::getFalse(CI->getContext());
2525 case ICmpInst::ICMP_SLT:
2526 case ICmpInst::ICMP_SLE:
2527 return CI->getValue().isNegative() ?
2528 ConstantInt::getFalse(CI->getContext()) :
2529 ConstantInt::getTrue(CI->getContext());
2535 if (isa<SExtInst>(LHS)) {
2536 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2538 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2539 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2540 // Compare X and Y. Note that the predicate does not change.
2541 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2545 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2546 // too. If not, then try to deduce the result of the comparison.
2547 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2548 // Compute the constant that would happen if we truncated to SrcTy then
2549 // reextended to DstTy.
2550 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2551 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2553 // If the re-extended constant didn't change then this is effectively
2554 // also a case of comparing two sign-extended values.
2555 if (RExt == CI && MaxRecurse)
2556 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2559 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2560 // bits there. Use this to work out the result of the comparison.
2563 default: llvm_unreachable("Unknown ICmp predicate!");
2564 case ICmpInst::ICMP_EQ:
2565 return ConstantInt::getFalse(CI->getContext());
2566 case ICmpInst::ICMP_NE:
2567 return ConstantInt::getTrue(CI->getContext());
2569 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2571 case ICmpInst::ICMP_SGT:
2572 case ICmpInst::ICMP_SGE:
2573 return CI->getValue().isNegative() ?
2574 ConstantInt::getTrue(CI->getContext()) :
2575 ConstantInt::getFalse(CI->getContext());
2576 case ICmpInst::ICMP_SLT:
2577 case ICmpInst::ICMP_SLE:
2578 return CI->getValue().isNegative() ?
2579 ConstantInt::getFalse(CI->getContext()) :
2580 ConstantInt::getTrue(CI->getContext());
2582 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2584 case ICmpInst::ICMP_UGT:
2585 case ICmpInst::ICMP_UGE:
2586 // Comparison is true iff the LHS <s 0.
2588 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2589 Constant::getNullValue(SrcTy),
2593 case ICmpInst::ICMP_ULT:
2594 case ICmpInst::ICMP_ULE:
2595 // Comparison is true iff the LHS >=s 0.
2597 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2598 Constant::getNullValue(SrcTy),
2608 // icmp eq|ne X, Y -> false|true if X != Y
2609 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2610 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2611 LLVMContext &Ctx = LHS->getType()->getContext();
2612 return Pred == ICmpInst::ICMP_NE ?
2613 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2616 // Special logic for binary operators.
2617 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2618 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2619 if (MaxRecurse && (LBO || RBO)) {
2620 // Analyze the case when either LHS or RHS is an add instruction.
2621 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2622 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2623 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2624 if (LBO && LBO->getOpcode() == Instruction::Add) {
2625 A = LBO->getOperand(0); B = LBO->getOperand(1);
2626 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2627 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2628 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2630 if (RBO && RBO->getOpcode() == Instruction::Add) {
2631 C = RBO->getOperand(0); D = RBO->getOperand(1);
2632 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2633 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2634 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2637 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2638 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2639 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2640 Constant::getNullValue(RHS->getType()),
2644 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2645 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2646 if (Value *V = SimplifyICmpInst(Pred,
2647 Constant::getNullValue(LHS->getType()),
2648 C == LHS ? D : C, Q, MaxRecurse-1))
2651 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2652 if (A && C && (A == C || A == D || B == C || B == D) &&
2653 NoLHSWrapProblem && NoRHSWrapProblem) {
2654 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2657 // C + B == C + D -> B == D
2660 } else if (A == D) {
2661 // D + B == C + D -> B == C
2664 } else if (B == C) {
2665 // A + C == C + D -> A == D
2670 // A + D == C + D -> A == C
2674 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2681 // icmp pred (or X, Y), X
2682 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2683 if (Pred == ICmpInst::ICMP_ULT)
2684 return getFalse(ITy);
2685 if (Pred == ICmpInst::ICMP_UGE)
2686 return getTrue(ITy);
2688 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2689 bool RHSKnownNonNegative, RHSKnownNegative;
2690 bool YKnownNonNegative, YKnownNegative;
2691 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2692 Q.AC, Q.CxtI, Q.DT);
2693 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2695 if (RHSKnownNonNegative && YKnownNegative)
2696 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2697 if (RHSKnownNegative || YKnownNonNegative)
2698 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2701 // icmp pred X, (or X, Y)
2702 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2703 if (Pred == ICmpInst::ICMP_ULE)
2704 return getTrue(ITy);
2705 if (Pred == ICmpInst::ICMP_UGT)
2706 return getFalse(ITy);
2708 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2709 bool LHSKnownNonNegative, LHSKnownNegative;
2710 bool YKnownNonNegative, YKnownNegative;
2711 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2712 Q.AC, Q.CxtI, Q.DT);
2713 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2715 if (LHSKnownNonNegative && YKnownNegative)
2716 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2717 if (LHSKnownNegative || YKnownNonNegative)
2718 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2723 // icmp pred (and X, Y), X
2724 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2725 m_And(m_Specific(RHS), m_Value())))) {
2726 if (Pred == ICmpInst::ICMP_UGT)
2727 return getFalse(ITy);
2728 if (Pred == ICmpInst::ICMP_ULE)
2729 return getTrue(ITy);
2731 // icmp pred X, (and X, Y)
2732 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2733 m_And(m_Specific(LHS), m_Value())))) {
2734 if (Pred == ICmpInst::ICMP_UGE)
2735 return getTrue(ITy);
2736 if (Pred == ICmpInst::ICMP_ULT)
2737 return getFalse(ITy);
2740 // 0 - (zext X) pred C
2741 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2742 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2743 if (RHSC->getValue().isStrictlyPositive()) {
2744 if (Pred == ICmpInst::ICMP_SLT)
2745 return ConstantInt::getTrue(RHSC->getContext());
2746 if (Pred == ICmpInst::ICMP_SGE)
2747 return ConstantInt::getFalse(RHSC->getContext());
2748 if (Pred == ICmpInst::ICMP_EQ)
2749 return ConstantInt::getFalse(RHSC->getContext());
2750 if (Pred == ICmpInst::ICMP_NE)
2751 return ConstantInt::getTrue(RHSC->getContext());
2753 if (RHSC->getValue().isNonNegative()) {
2754 if (Pred == ICmpInst::ICMP_SLE)
2755 return ConstantInt::getTrue(RHSC->getContext());
2756 if (Pred == ICmpInst::ICMP_SGT)
2757 return ConstantInt::getFalse(RHSC->getContext());
2762 // icmp pred (urem X, Y), Y
2763 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2764 bool KnownNonNegative, KnownNegative;
2768 case ICmpInst::ICMP_SGT:
2769 case ICmpInst::ICMP_SGE:
2770 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2772 if (!KnownNonNegative)
2775 case ICmpInst::ICMP_EQ:
2776 case ICmpInst::ICMP_UGT:
2777 case ICmpInst::ICMP_UGE:
2778 return getFalse(ITy);
2779 case ICmpInst::ICMP_SLT:
2780 case ICmpInst::ICMP_SLE:
2781 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2783 if (!KnownNonNegative)
2786 case ICmpInst::ICMP_NE:
2787 case ICmpInst::ICMP_ULT:
2788 case ICmpInst::ICMP_ULE:
2789 return getTrue(ITy);
2793 // icmp pred X, (urem Y, X)
2794 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2795 bool KnownNonNegative, KnownNegative;
2799 case ICmpInst::ICMP_SGT:
2800 case ICmpInst::ICMP_SGE:
2801 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2803 if (!KnownNonNegative)
2806 case ICmpInst::ICMP_NE:
2807 case ICmpInst::ICMP_UGT:
2808 case ICmpInst::ICMP_UGE:
2809 return getTrue(ITy);
2810 case ICmpInst::ICMP_SLT:
2811 case ICmpInst::ICMP_SLE:
2812 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2814 if (!KnownNonNegative)
2817 case ICmpInst::ICMP_EQ:
2818 case ICmpInst::ICMP_ULT:
2819 case ICmpInst::ICMP_ULE:
2820 return getFalse(ITy);
2826 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2827 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2828 // icmp pred (X op Y), X
2829 if (Pred == ICmpInst::ICMP_UGT)
2830 return getFalse(ITy);
2831 if (Pred == ICmpInst::ICMP_ULE)
2832 return getTrue(ITy);
2839 // where CI2 is a power of 2 and CI isn't
2840 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2841 const APInt *CI2Val, *CIVal = &CI->getValue();
2842 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2843 CI2Val->isPowerOf2()) {
2844 if (!CIVal->isPowerOf2()) {
2845 // CI2 << X can equal zero in some circumstances,
2846 // this simplification is unsafe if CI is zero.
2848 // We know it is safe if:
2849 // - The shift is nsw, we can't shift out the one bit.
2850 // - The shift is nuw, we can't shift out the one bit.
2853 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2854 *CI2Val == 1 || !CI->isZero()) {
2855 if (Pred == ICmpInst::ICMP_EQ)
2856 return ConstantInt::getFalse(RHS->getContext());
2857 if (Pred == ICmpInst::ICMP_NE)
2858 return ConstantInt::getTrue(RHS->getContext());
2861 if (CIVal->isSignBit() && *CI2Val == 1) {
2862 if (Pred == ICmpInst::ICMP_UGT)
2863 return ConstantInt::getFalse(RHS->getContext());
2864 if (Pred == ICmpInst::ICMP_ULE)
2865 return ConstantInt::getTrue(RHS->getContext());
2870 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2871 LBO->getOperand(1) == RBO->getOperand(1)) {
2872 switch (LBO->getOpcode()) {
2874 case Instruction::UDiv:
2875 case Instruction::LShr:
2876 if (ICmpInst::isSigned(Pred))
2879 case Instruction::SDiv:
2880 case Instruction::AShr:
2881 if (!LBO->isExact() || !RBO->isExact())
2883 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2884 RBO->getOperand(0), Q, MaxRecurse-1))
2887 case Instruction::Shl: {
2888 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2889 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2892 if (!NSW && ICmpInst::isSigned(Pred))
2894 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2895 RBO->getOperand(0), Q, MaxRecurse-1))
2902 // Simplify comparisons involving max/min.
2904 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2905 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2907 // Signed variants on "max(a,b)>=a -> true".
2908 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2909 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2910 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2911 // We analyze this as smax(A, B) pred A.
2913 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2914 (A == LHS || B == LHS)) {
2915 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2916 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2917 // We analyze this as smax(A, B) swapped-pred A.
2918 P = CmpInst::getSwappedPredicate(Pred);
2919 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2920 (A == RHS || B == RHS)) {
2921 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2922 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2923 // We analyze this as smax(-A, -B) swapped-pred -A.
2924 // Note that we do not need to actually form -A or -B thanks to EqP.
2925 P = CmpInst::getSwappedPredicate(Pred);
2926 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2927 (A == LHS || B == LHS)) {
2928 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2929 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2930 // We analyze this as smax(-A, -B) pred -A.
2931 // Note that we do not need to actually form -A or -B thanks to EqP.
2934 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2935 // Cases correspond to "max(A, B) p A".
2939 case CmpInst::ICMP_EQ:
2940 case CmpInst::ICMP_SLE:
2941 // Equivalent to "A EqP B". This may be the same as the condition tested
2942 // in the max/min; if so, we can just return that.
2943 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2945 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2947 // Otherwise, see if "A EqP B" simplifies.
2949 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2952 case CmpInst::ICMP_NE:
2953 case CmpInst::ICMP_SGT: {
2954 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2955 // Equivalent to "A InvEqP B". This may be the same as the condition
2956 // tested in the max/min; if so, we can just return that.
2957 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2959 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2961 // Otherwise, see if "A InvEqP B" simplifies.
2963 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2967 case CmpInst::ICMP_SGE:
2969 return getTrue(ITy);
2970 case CmpInst::ICMP_SLT:
2972 return getFalse(ITy);
2976 // Unsigned variants on "max(a,b)>=a -> true".
2977 P = CmpInst::BAD_ICMP_PREDICATE;
2978 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2979 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2980 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2981 // We analyze this as umax(A, B) pred A.
2983 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2984 (A == LHS || B == LHS)) {
2985 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2986 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2987 // We analyze this as umax(A, B) swapped-pred A.
2988 P = CmpInst::getSwappedPredicate(Pred);
2989 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2990 (A == RHS || B == RHS)) {
2991 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2992 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2993 // We analyze this as umax(-A, -B) swapped-pred -A.
2994 // Note that we do not need to actually form -A or -B thanks to EqP.
2995 P = CmpInst::getSwappedPredicate(Pred);
2996 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2997 (A == LHS || B == LHS)) {
2998 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2999 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3000 // We analyze this as umax(-A, -B) pred -A.
3001 // Note that we do not need to actually form -A or -B thanks to EqP.
3004 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3005 // Cases correspond to "max(A, B) p A".
3009 case CmpInst::ICMP_EQ:
3010 case CmpInst::ICMP_ULE:
3011 // Equivalent to "A EqP B". This may be the same as the condition tested
3012 // in the max/min; if so, we can just return that.
3013 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3015 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3017 // Otherwise, see if "A EqP B" simplifies.
3019 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
3022 case CmpInst::ICMP_NE:
3023 case CmpInst::ICMP_UGT: {
3024 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3025 // Equivalent to "A InvEqP B". This may be the same as the condition
3026 // tested in the max/min; if so, we can just return that.
3027 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3029 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3031 // Otherwise, see if "A InvEqP B" simplifies.
3033 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
3037 case CmpInst::ICMP_UGE:
3039 return getTrue(ITy);
3040 case CmpInst::ICMP_ULT:
3042 return getFalse(ITy);
3046 // Variants on "max(x,y) >= min(x,z)".
3048 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3049 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3050 (A == C || A == D || B == C || B == D)) {
3051 // max(x, ?) pred min(x, ?).
3052 if (Pred == CmpInst::ICMP_SGE)
3054 return getTrue(ITy);
3055 if (Pred == CmpInst::ICMP_SLT)
3057 return getFalse(ITy);
3058 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3059 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3060 (A == C || A == D || B == C || B == D)) {
3061 // min(x, ?) pred max(x, ?).
3062 if (Pred == CmpInst::ICMP_SLE)
3064 return getTrue(ITy);
3065 if (Pred == CmpInst::ICMP_SGT)
3067 return getFalse(ITy);
3068 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3069 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3070 (A == C || A == D || B == C || B == D)) {
3071 // max(x, ?) pred min(x, ?).
3072 if (Pred == CmpInst::ICMP_UGE)
3074 return getTrue(ITy);
3075 if (Pred == CmpInst::ICMP_ULT)
3077 return getFalse(ITy);
3078 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3079 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3080 (A == C || A == D || B == C || B == D)) {
3081 // min(x, ?) pred max(x, ?).
3082 if (Pred == CmpInst::ICMP_ULE)
3084 return getTrue(ITy);
3085 if (Pred == CmpInst::ICMP_UGT)
3087 return getFalse(ITy);
3090 // Simplify comparisons of related pointers using a powerful, recursive
3091 // GEP-walk when we have target data available..
3092 if (LHS->getType()->isPointerTy())
3093 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
3096 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3097 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3098 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3099 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3100 (ICmpInst::isEquality(Pred) ||
3101 (GLHS->isInBounds() && GRHS->isInBounds() &&
3102 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3103 // The bases are equal and the indices are constant. Build a constant
3104 // expression GEP with the same indices and a null base pointer to see
3105 // what constant folding can make out of it.
3106 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3107 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
3108 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3109 GLHS->getSourceElementType(), Null, IndicesLHS);
3111 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
3112 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3113 GLHS->getSourceElementType(), Null, IndicesRHS);
3114 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3119 // If a bit is known to be zero for A and known to be one for B,
3120 // then A and B cannot be equal.
3121 if (ICmpInst::isEquality(Pred)) {
3122 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3123 uint32_t BitWidth = CI->getBitWidth();
3124 APInt LHSKnownZero(BitWidth, 0);
3125 APInt LHSKnownOne(BitWidth, 0);
3126 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
3128 const APInt &RHSVal = CI->getValue();
3129 if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3130 return Pred == ICmpInst::ICMP_EQ
3131 ? ConstantInt::getFalse(CI->getContext())
3132 : ConstantInt::getTrue(CI->getContext());
3136 // If the comparison is with the result of a select instruction, check whether
3137 // comparing with either branch of the select always yields the same value.
3138 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3139 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3142 // If the comparison is with the result of a phi instruction, check whether
3143 // doing the compare with each incoming phi value yields a common result.
3144 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3145 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3151 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3152 const DataLayout &DL,
3153 const TargetLibraryInfo *TLI,
3154 const DominatorTree *DT, AssumptionCache *AC,
3155 const Instruction *CxtI) {
3156 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3160 /// Given operands for an FCmpInst, see if we can fold the result.
3161 /// If not, this returns null.
3162 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3163 FastMathFlags FMF, const Query &Q,
3164 unsigned MaxRecurse) {
3165 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3166 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3168 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
3169 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3170 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
3172 // If we have a constant, make sure it is on the RHS.
3173 std::swap(LHS, RHS);
3174 Pred = CmpInst::getSwappedPredicate(Pred);
3177 // Fold trivial predicates.
3178 if (Pred == FCmpInst::FCMP_FALSE)
3179 return ConstantInt::get(GetCompareTy(LHS), 0);
3180 if (Pred == FCmpInst::FCMP_TRUE)
3181 return ConstantInt::get(GetCompareTy(LHS), 1);
3183 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3185 if (Pred == FCmpInst::FCMP_UNO)
3186 return ConstantInt::get(GetCompareTy(LHS), 0);
3187 if (Pred == FCmpInst::FCMP_ORD)
3188 return ConstantInt::get(GetCompareTy(LHS), 1);
3191 // fcmp pred x, undef and fcmp pred undef, x
3192 // fold to true if unordered, false if ordered
3193 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3194 // Choosing NaN for the undef will always make unordered comparison succeed
3195 // and ordered comparison fail.
3196 return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3199 // fcmp x,x -> true/false. Not all compares are foldable.
3201 if (CmpInst::isTrueWhenEqual(Pred))
3202 return ConstantInt::get(GetCompareTy(LHS), 1);
3203 if (CmpInst::isFalseWhenEqual(Pred))
3204 return ConstantInt::get(GetCompareTy(LHS), 0);
3207 // Handle fcmp with constant RHS
3208 const ConstantFP *CFP = nullptr;
3209 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3210 if (RHS->getType()->isVectorTy())
3211 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3213 CFP = dyn_cast<ConstantFP>(RHSC);
3216 // If the constant is a nan, see if we can fold the comparison based on it.
3217 if (CFP->getValueAPF().isNaN()) {
3218 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3219 return ConstantInt::getFalse(CFP->getContext());
3220 assert(FCmpInst::isUnordered(Pred) &&
3221 "Comparison must be either ordered or unordered!");
3222 // True if unordered.
3223 return ConstantInt::get(GetCompareTy(LHS), 1);
3225 // Check whether the constant is an infinity.
3226 if (CFP->getValueAPF().isInfinity()) {
3227 if (CFP->getValueAPF().isNegative()) {
3229 case FCmpInst::FCMP_OLT:
3230 // No value is ordered and less than negative infinity.
3231 return ConstantInt::get(GetCompareTy(LHS), 0);
3232 case FCmpInst::FCMP_UGE:
3233 // All values are unordered with or at least negative infinity.
3234 return ConstantInt::get(GetCompareTy(LHS), 1);
3240 case FCmpInst::FCMP_OGT:
3241 // No value is ordered and greater than infinity.
3242 return ConstantInt::get(GetCompareTy(LHS), 0);
3243 case FCmpInst::FCMP_ULE:
3244 // All values are unordered with and at most infinity.
3245 return ConstantInt::get(GetCompareTy(LHS), 1);
3251 if (CFP->getValueAPF().isZero()) {
3253 case FCmpInst::FCMP_UGE:
3254 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3255 return ConstantInt::get(GetCompareTy(LHS), 1);
3257 case FCmpInst::FCMP_OLT:
3259 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3260 return ConstantInt::get(GetCompareTy(LHS), 0);
3268 // If the comparison is with the result of a select instruction, check whether
3269 // comparing with either branch of the select always yields the same value.
3270 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3271 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
3274 // If the comparison is with the result of a phi instruction, check whether
3275 // doing the compare with each incoming phi value yields a common result.
3276 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3277 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
3283 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3284 FastMathFlags FMF, const DataLayout &DL,
3285 const TargetLibraryInfo *TLI,
3286 const DominatorTree *DT, AssumptionCache *AC,
3287 const Instruction *CxtI) {
3288 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3289 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3292 /// See if V simplifies when its operand Op is replaced with RepOp.
3293 static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3295 unsigned MaxRecurse) {
3296 // Trivial replacement.
3300 auto *I = dyn_cast<Instruction>(V);
3304 // If this is a binary operator, try to simplify it with the replaced op.
3305 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3307 // %cmp = icmp eq i32 %x, 2147483647
3308 // %add = add nsw i32 %x, 1
3309 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3311 // We can't replace %sel with %add unless we strip away the flags.
3312 if (isa<OverflowingBinaryOperator>(B))
3313 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3315 if (isa<PossiblyExactOperator>(B))
3320 if (B->getOperand(0) == Op)
3321 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3323 if (B->getOperand(1) == Op)
3324 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3329 // Same for CmpInsts.
3330 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3332 if (C->getOperand(0) == Op)
3333 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3335 if (C->getOperand(1) == Op)
3336 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3341 // TODO: We could hand off more cases to instsimplify here.
3343 // If all operands are constant after substituting Op for RepOp then we can
3344 // constant fold the instruction.
3345 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3346 // Build a list of all constant operands.
3347 SmallVector<Constant *, 8> ConstOps;
3348 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3349 if (I->getOperand(i) == Op)
3350 ConstOps.push_back(CRepOp);
3351 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3352 ConstOps.push_back(COp);
3357 // All operands were constants, fold it.
3358 if (ConstOps.size() == I->getNumOperands()) {
3359 if (CmpInst *C = dyn_cast<CmpInst>(I))
3360 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3361 ConstOps[1], Q.DL, Q.TLI);
3363 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3364 if (!LI->isVolatile())
3365 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
3367 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
3374 /// Given operands for a SelectInst, see if we can fold the result.
3375 /// If not, this returns null.
3376 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3377 Value *FalseVal, const Query &Q,
3378 unsigned MaxRecurse) {
3379 // select true, X, Y -> X
3380 // select false, X, Y -> Y
3381 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3382 if (CB->isAllOnesValue())
3384 if (CB->isNullValue())
3388 // select C, X, X -> X
3389 if (TrueVal == FalseVal)
3392 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3393 if (isa<Constant>(TrueVal))
3397 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3399 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3402 if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
3403 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3404 // decomposeBitTestICmp() might help.
3406 Q.DL.getTypeSizeInBits(TrueVal->getType()->getScalarType());
3407 ICmpInst::Predicate Pred = ICI->getPredicate();
3408 Value *CmpLHS = ICI->getOperand(0);
3409 Value *CmpRHS = ICI->getOperand(1);
3410 APInt MinSignedValue = APInt::getSignBit(BitWidth);
3414 bool IsBitTest = false;
3415 if (ICmpInst::isEquality(Pred) &&
3416 match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
3417 match(CmpRHS, m_Zero())) {
3419 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
3420 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3422 Y = &MinSignedValue;
3424 TrueWhenUnset = false;
3425 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3427 Y = &MinSignedValue;
3429 TrueWhenUnset = true;
3433 // (X & Y) == 0 ? X & ~Y : X --> X
3434 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3435 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3437 return TrueWhenUnset ? FalseVal : TrueVal;
3438 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3439 // (X & Y) != 0 ? X : X & ~Y --> X
3440 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3442 return TrueWhenUnset ? FalseVal : TrueVal;
3444 if (Y->isPowerOf2()) {
3445 // (X & Y) == 0 ? X | Y : X --> X | Y
3446 // (X & Y) != 0 ? X | Y : X --> X
3447 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3449 return TrueWhenUnset ? TrueVal : FalseVal;
3450 // (X & Y) == 0 ? X : X | Y --> X
3451 // (X & Y) != 0 ? X : X | Y --> X | Y
3452 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3454 return TrueWhenUnset ? TrueVal : FalseVal;
3457 if (ICI->hasOneUse()) {
3459 if (match(CmpRHS, m_APInt(C))) {
3460 // X < MIN ? T : F --> F
3461 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3463 // X < MIN ? T : F --> F
3464 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3466 // X > MAX ? T : F --> F
3467 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3469 // X > MAX ? T : F --> F
3470 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3475 // If we have an equality comparison then we know the value in one of the
3476 // arms of the select. See if substituting this value into the arm and
3477 // simplifying the result yields the same value as the other arm.
3478 if (Pred == ICmpInst::ICMP_EQ) {
3479 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3481 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3484 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3486 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3489 } else if (Pred == ICmpInst::ICMP_NE) {
3490 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3492 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3495 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3497 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3506 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3507 const DataLayout &DL,
3508 const TargetLibraryInfo *TLI,
3509 const DominatorTree *DT, AssumptionCache *AC,
3510 const Instruction *CxtI) {
3511 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3512 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3515 /// Given operands for an GetElementPtrInst, see if we can fold the result.
3516 /// If not, this returns null.
3517 static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3518 const Query &Q, unsigned) {
3519 // The type of the GEP pointer operand.
3521 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
3523 // getelementptr P -> P.
3524 if (Ops.size() == 1)
3527 // Compute the (pointer) type returned by the GEP instruction.
3528 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
3529 Type *GEPTy = PointerType::get(LastType, AS);
3530 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3531 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3533 if (isa<UndefValue>(Ops[0]))
3534 return UndefValue::get(GEPTy);
3536 if (Ops.size() == 2) {
3537 // getelementptr P, 0 -> P.
3538 if (match(Ops[1], m_Zero()))
3542 if (Ty->isSized()) {
3545 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
3546 // getelementptr P, N -> P if P points to a type of zero size.
3547 if (TyAllocSize == 0)
3550 // The following transforms are only safe if the ptrtoint cast
3551 // doesn't truncate the pointers.
3552 if (Ops[1]->getType()->getScalarSizeInBits() ==
3553 Q.DL.getPointerSizeInBits(AS)) {
3554 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3555 if (match(P, m_Zero()))
3556 return Constant::getNullValue(GEPTy);
3558 if (match(P, m_PtrToInt(m_Value(Temp))))
3559 if (Temp->getType() == GEPTy)
3564 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3565 if (TyAllocSize == 1 &&
3566 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3567 if (Value *R = PtrToIntOrZero(P))
3570 // getelementptr V, (ashr (sub P, V), C) -> Q
3571 // if P points to a type of size 1 << C.
3573 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3574 m_ConstantInt(C))) &&
3575 TyAllocSize == 1ULL << C)
3576 if (Value *R = PtrToIntOrZero(P))
3579 // getelementptr V, (sdiv (sub P, V), C) -> Q
3580 // if P points to a type of size C.
3582 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3583 m_SpecificInt(TyAllocSize))))
3584 if (Value *R = PtrToIntOrZero(P))
3590 // Check to see if this is constant foldable.
3591 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3592 if (!isa<Constant>(Ops[i]))
3595 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3599 Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3600 const DataLayout &DL,
3601 const TargetLibraryInfo *TLI,
3602 const DominatorTree *DT, AssumptionCache *AC,
3603 const Instruction *CxtI) {
3604 return ::SimplifyGEPInst(SrcTy, Ops,
3605 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
3608 /// Given operands for an InsertValueInst, see if we can fold the result.
3609 /// If not, this returns null.
3610 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3611 ArrayRef<unsigned> Idxs, const Query &Q,
3613 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3614 if (Constant *CVal = dyn_cast<Constant>(Val))
3615 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3617 // insertvalue x, undef, n -> x
3618 if (match(Val, m_Undef()))
3621 // insertvalue x, (extractvalue y, n), n
3622 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3623 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3624 EV->getIndices() == Idxs) {
3625 // insertvalue undef, (extractvalue y, n), n -> y
3626 if (match(Agg, m_Undef()))
3627 return EV->getAggregateOperand();
3629 // insertvalue y, (extractvalue y, n), n -> y
3630 if (Agg == EV->getAggregateOperand())
3637 Value *llvm::SimplifyInsertValueInst(
3638 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
3639 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3640 const Instruction *CxtI) {
3641 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
3645 /// Given operands for an ExtractValueInst, see if we can fold the result.
3646 /// If not, this returns null.
3647 static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3648 const Query &, unsigned) {
3649 if (auto *CAgg = dyn_cast<Constant>(Agg))
3650 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3652 // extractvalue x, (insertvalue y, elt, n), n -> elt
3653 unsigned NumIdxs = Idxs.size();
3654 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3655 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3656 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3657 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3658 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3659 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3660 Idxs.slice(0, NumCommonIdxs)) {
3661 if (NumIdxs == NumInsertValueIdxs)
3662 return IVI->getInsertedValueOperand();
3670 Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3671 const DataLayout &DL,
3672 const TargetLibraryInfo *TLI,
3673 const DominatorTree *DT,
3674 AssumptionCache *AC,
3675 const Instruction *CxtI) {
3676 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3680 /// Given operands for an ExtractElementInst, see if we can fold the result.
3681 /// If not, this returns null.
3682 static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3684 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3685 if (auto *CIdx = dyn_cast<Constant>(Idx))
3686 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3688 // The index is not relevant if our vector is a splat.
3689 if (auto *Splat = CVec->getSplatValue())
3692 if (isa<UndefValue>(Vec))
3693 return UndefValue::get(Vec->getType()->getVectorElementType());
3696 // If extracting a specified index from the vector, see if we can recursively
3697 // find a previously computed scalar that was inserted into the vector.
3698 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3699 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
3705 Value *llvm::SimplifyExtractElementInst(
3706 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3707 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3708 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3712 /// See if we can fold the given phi. If not, returns null.
3713 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3714 // If all of the PHI's incoming values are the same then replace the PHI node
3715 // with the common value.
3716 Value *CommonValue = nullptr;
3717 bool HasUndefInput = false;
3718 for (Value *Incoming : PN->incoming_values()) {
3719 // If the incoming value is the phi node itself, it can safely be skipped.
3720 if (Incoming == PN) continue;
3721 if (isa<UndefValue>(Incoming)) {
3722 // Remember that we saw an undef value, but otherwise ignore them.
3723 HasUndefInput = true;
3726 if (CommonValue && Incoming != CommonValue)
3727 return nullptr; // Not the same, bail out.
3728 CommonValue = Incoming;
3731 // If CommonValue is null then all of the incoming values were either undef or
3732 // equal to the phi node itself.
3734 return UndefValue::get(PN->getType());
3736 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3737 // instruction, we cannot return X as the result of the PHI node unless it
3738 // dominates the PHI block.
3740 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3745 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3746 if (Constant *C = dyn_cast<Constant>(Op))
3747 return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
3752 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
3753 const TargetLibraryInfo *TLI,
3754 const DominatorTree *DT, AssumptionCache *AC,
3755 const Instruction *CxtI) {
3756 return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3760 //=== Helper functions for higher up the class hierarchy.
3762 /// Given operands for a BinaryOperator, see if we can fold the result.
3763 /// If not, this returns null.
3764 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3765 const Query &Q, unsigned MaxRecurse) {
3767 case Instruction::Add:
3768 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3770 case Instruction::FAdd:
3771 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3773 case Instruction::Sub:
3774 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3776 case Instruction::FSub:
3777 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3779 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3780 case Instruction::FMul:
3781 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3782 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3783 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3784 case Instruction::FDiv:
3785 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3786 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3787 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3788 case Instruction::FRem:
3789 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3790 case Instruction::Shl:
3791 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3793 case Instruction::LShr:
3794 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3795 case Instruction::AShr:
3796 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3797 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3798 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3799 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3801 if (Constant *CLHS = dyn_cast<Constant>(LHS))
3802 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3803 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
3805 // If the operation is associative, try some generic simplifications.
3806 if (Instruction::isAssociative(Opcode))
3807 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3810 // If the operation is with the result of a select instruction check whether
3811 // operating on either branch of the select always yields the same value.
3812 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3813 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3816 // If the operation is with the result of a phi instruction, check whether
3817 // operating on all incoming values of the phi always yields the same value.
3818 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3819 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3826 /// Given operands for a BinaryOperator, see if we can fold the result.
3827 /// If not, this returns null.
3828 /// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3829 /// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3830 static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3831 const FastMathFlags &FMF, const Query &Q,
3832 unsigned MaxRecurse) {
3834 case Instruction::FAdd:
3835 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3836 case Instruction::FSub:
3837 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3838 case Instruction::FMul:
3839 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3841 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3845 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3846 const DataLayout &DL, const TargetLibraryInfo *TLI,
3847 const DominatorTree *DT, AssumptionCache *AC,
3848 const Instruction *CxtI) {
3849 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3853 Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3854 const FastMathFlags &FMF, const DataLayout &DL,
3855 const TargetLibraryInfo *TLI,
3856 const DominatorTree *DT, AssumptionCache *AC,
3857 const Instruction *CxtI) {
3858 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3862 /// Given operands for a CmpInst, see if we can fold the result.
3863 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3864 const Query &Q, unsigned MaxRecurse) {
3865 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3866 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3867 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3870 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3871 const DataLayout &DL, const TargetLibraryInfo *TLI,
3872 const DominatorTree *DT, AssumptionCache *AC,
3873 const Instruction *CxtI) {
3874 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
3878 static bool IsIdempotent(Intrinsic::ID ID) {
3880 default: return false;
3882 // Unary idempotent: f(f(x)) = f(x)
3883 case Intrinsic::fabs:
3884 case Intrinsic::floor:
3885 case Intrinsic::ceil:
3886 case Intrinsic::trunc:
3887 case Intrinsic::rint:
3888 case Intrinsic::nearbyint:
3889 case Intrinsic::round:
3894 static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
3895 const DataLayout &DL) {
3896 GlobalValue *PtrSym;
3898 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
3901 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
3902 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
3903 Type *Int32PtrTy = Int32Ty->getPointerTo();
3904 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
3906 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
3907 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
3910 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
3911 if (OffsetInt % 4 != 0)
3914 Constant *C = ConstantExpr::getGetElementPtr(
3915 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
3916 ConstantInt::get(Int64Ty, OffsetInt / 4));
3917 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
3921 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
3925 if (LoadedCE->getOpcode() == Instruction::Trunc) {
3926 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3931 if (LoadedCE->getOpcode() != Instruction::Sub)
3934 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3935 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
3937 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
3939 Constant *LoadedRHS = LoadedCE->getOperand(1);
3940 GlobalValue *LoadedRHSSym;
3941 APInt LoadedRHSOffset;
3942 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
3944 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
3947 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
3950 static bool maskIsAllZeroOrUndef(Value *Mask) {
3951 auto *ConstMask = dyn_cast<Constant>(Mask);
3954 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
3956 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
3958 if (auto *MaskElt = ConstMask->getAggregateElement(I))
3959 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
3966 template <typename IterTy>
3967 static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
3968 const Query &Q, unsigned MaxRecurse) {
3969 Intrinsic::ID IID = F->getIntrinsicID();
3970 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
3971 Type *ReturnType = F->getReturnType();
3974 if (NumOperands == 2) {
3975 Value *LHS = *ArgBegin;
3976 Value *RHS = *(ArgBegin + 1);
3977 if (IID == Intrinsic::usub_with_overflow ||
3978 IID == Intrinsic::ssub_with_overflow) {
3979 // X - X -> { 0, false }
3981 return Constant::getNullValue(ReturnType);
3983 // X - undef -> undef
3984 // undef - X -> undef
3985 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
3986 return UndefValue::get(ReturnType);
3989 if (IID == Intrinsic::uadd_with_overflow ||
3990 IID == Intrinsic::sadd_with_overflow) {
3991 // X + undef -> undef
3992 if (isa<UndefValue>(RHS))
3993 return UndefValue::get(ReturnType);
3996 if (IID == Intrinsic::umul_with_overflow ||
3997 IID == Intrinsic::smul_with_overflow) {
3998 // X * 0 -> { 0, false }
3999 if (match(RHS, m_Zero()))
4000 return Constant::getNullValue(ReturnType);
4002 // X * undef -> { 0, false }
4003 if (match(RHS, m_Undef()))
4004 return Constant::getNullValue(ReturnType);
4007 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4009 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4013 // Simplify calls to llvm.masked.load.*
4014 if (IID == Intrinsic::masked_load) {
4015 Value *MaskArg = ArgBegin[2];
4016 Value *PassthruArg = ArgBegin[3];
4017 // If the mask is all zeros or undef, the "passthru" argument is the result.
4018 if (maskIsAllZeroOrUndef(MaskArg))
4022 // Perform idempotent optimizations
4023 if (!IsIdempotent(IID))
4027 if (NumOperands == 1)
4028 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4029 if (II->getIntrinsicID() == IID)
4035 template <typename IterTy>
4036 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
4037 const Query &Q, unsigned MaxRecurse) {
4038 Type *Ty = V->getType();
4039 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4040 Ty = PTy->getElementType();
4041 FunctionType *FTy = cast<FunctionType>(Ty);
4043 // call undef -> undef
4044 // call null -> undef
4045 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
4046 return UndefValue::get(FTy->getReturnType());
4048 Function *F = dyn_cast<Function>(V);
4052 if (F->isIntrinsic())
4053 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
4056 if (!canConstantFoldCallTo(F))
4059 SmallVector<Constant *, 4> ConstantArgs;
4060 ConstantArgs.reserve(ArgEnd - ArgBegin);
4061 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4062 Constant *C = dyn_cast<Constant>(*I);
4065 ConstantArgs.push_back(C);
4068 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
4071 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
4072 User::op_iterator ArgEnd, const DataLayout &DL,
4073 const TargetLibraryInfo *TLI, const DominatorTree *DT,
4074 AssumptionCache *AC, const Instruction *CxtI) {
4075 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
4079 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
4080 const DataLayout &DL, const TargetLibraryInfo *TLI,
4081 const DominatorTree *DT, AssumptionCache *AC,
4082 const Instruction *CxtI) {
4083 return ::SimplifyCall(V, Args.begin(), Args.end(),
4084 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
4087 /// See if we can compute a simplified version of this instruction.
4088 /// If not, this returns null.
4089 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
4090 const TargetLibraryInfo *TLI,
4091 const DominatorTree *DT, AssumptionCache *AC) {
4094 switch (I->getOpcode()) {
4096 Result = ConstantFoldInstruction(I, DL, TLI);
4098 case Instruction::FAdd:
4099 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
4100 I->getFastMathFlags(), DL, TLI, DT, AC, I);
4102 case Instruction::Add:
4103 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4104 cast<BinaryOperator>(I)->hasNoSignedWrap(),
4105 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4108 case Instruction::FSub:
4109 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
4110 I->getFastMathFlags(), DL, TLI, DT, AC, I);
4112 case Instruction::Sub:
4113 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4114 cast<BinaryOperator>(I)->hasNoSignedWrap(),
4115 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4118 case Instruction::FMul:
4119 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
4120 I->getFastMathFlags(), DL, TLI, DT, AC, I);
4122 case Instruction::Mul:
4124 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4126 case Instruction::SDiv:
4127 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4130 case Instruction::UDiv:
4131 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4134 case Instruction::FDiv:
4135 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4136 I->getFastMathFlags(), DL, TLI, DT, AC, I);
4138 case Instruction::SRem:
4139 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4142 case Instruction::URem:
4143 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4146 case Instruction::FRem:
4147 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4148 I->getFastMathFlags(), DL, TLI, DT, AC, I);
4150 case Instruction::Shl:
4151 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4152 cast<BinaryOperator>(I)->hasNoSignedWrap(),
4153 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4156 case Instruction::LShr:
4157 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
4158 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4161 case Instruction::AShr:
4162 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
4163 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4166 case Instruction::And:
4168 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4170 case Instruction::Or:
4172 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4174 case Instruction::Xor:
4176 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
4178 case Instruction::ICmp:
4180 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4181 I->getOperand(1), DL, TLI, DT, AC, I);
4183 case Instruction::FCmp:
4184 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4185 I->getOperand(0), I->getOperand(1),
4186 I->getFastMathFlags(), DL, TLI, DT, AC, I);
4188 case Instruction::Select:
4189 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
4190 I->getOperand(2), DL, TLI, DT, AC, I);
4192 case Instruction::GetElementPtr: {
4193 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
4194 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4195 Ops, DL, TLI, DT, AC, I);
4198 case Instruction::InsertValue: {
4199 InsertValueInst *IV = cast<InsertValueInst>(I);
4200 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4201 IV->getInsertedValueOperand(),
4202 IV->getIndices(), DL, TLI, DT, AC, I);
4205 case Instruction::ExtractValue: {
4206 auto *EVI = cast<ExtractValueInst>(I);
4207 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4208 EVI->getIndices(), DL, TLI, DT, AC, I);
4211 case Instruction::ExtractElement: {
4212 auto *EEI = cast<ExtractElementInst>(I);
4213 Result = SimplifyExtractElementInst(
4214 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4217 case Instruction::PHI:
4218 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
4220 case Instruction::Call: {
4221 CallSite CS(cast<CallInst>(I));
4222 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4226 case Instruction::Trunc:
4228 SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
4232 // In general, it is possible for computeKnownBits to determine all bits in a
4233 // value even when the operands are not all constants.
4234 if (!Result && I->getType()->isIntegerTy()) {
4235 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4236 APInt KnownZero(BitWidth, 0);
4237 APInt KnownOne(BitWidth, 0);
4238 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4239 if ((KnownZero | KnownOne).isAllOnesValue())
4240 Result = ConstantInt::get(I->getContext(), KnownOne);
4243 /// If called on unreachable code, the above logic may report that the
4244 /// instruction simplified to itself. Make life easier for users by
4245 /// detecting that case here, returning a safe value instead.
4246 return Result == I ? UndefValue::get(I->getType()) : Result;
4249 /// \brief Implementation of recursive simplification through an instruction's
4252 /// This is the common implementation of the recursive simplification routines.
4253 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4254 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4255 /// instructions to process and attempt to simplify it using
4256 /// InstructionSimplify.
4258 /// This routine returns 'true' only when *it* simplifies something. The passed
4259 /// in simplified value does not count toward this.
4260 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
4261 const TargetLibraryInfo *TLI,
4262 const DominatorTree *DT,
4263 AssumptionCache *AC) {
4264 bool Simplified = false;
4265 SmallSetVector<Instruction *, 8> Worklist;
4266 const DataLayout &DL = I->getModule()->getDataLayout();
4268 // If we have an explicit value to collapse to, do that round of the
4269 // simplification loop by hand initially.
4271 for (User *U : I->users())
4273 Worklist.insert(cast<Instruction>(U));
4275 // Replace the instruction with its simplified value.
4276 I->replaceAllUsesWith(SimpleV);
4278 // Gracefully handle edge cases where the instruction is not wired into any
4280 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4281 !I->mayHaveSideEffects())
4282 I->eraseFromParent();
4287 // Note that we must test the size on each iteration, the worklist can grow.
4288 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4291 // See if this instruction simplifies.
4292 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
4298 // Stash away all the uses of the old instruction so we can check them for
4299 // recursive simplifications after a RAUW. This is cheaper than checking all
4300 // uses of To on the recursive step in most cases.
4301 for (User *U : I->users())
4302 Worklist.insert(cast<Instruction>(U));
4304 // Replace the instruction with its simplified value.
4305 I->replaceAllUsesWith(SimpleV);
4307 // Gracefully handle edge cases where the instruction is not wired into any
4309 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4310 !I->mayHaveSideEffects())
4311 I->eraseFromParent();
4316 bool llvm::recursivelySimplifyInstruction(Instruction *I,
4317 const TargetLibraryInfo *TLI,
4318 const DominatorTree *DT,
4319 AssumptionCache *AC) {
4320 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
4323 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
4324 const TargetLibraryInfo *TLI,
4325 const DominatorTree *DT,
4326 AssumptionCache *AC) {
4327 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4328 assert(SimpleV && "Must provide a simplified value.");
4329 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);