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/ConstantFolding.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/ValueHandle.h"
35 using namespace llvm::PatternMatch;
37 #define DEBUG_TYPE "instsimplify"
39 enum { RecursionLimit = 3 };
41 STATISTIC(NumExpand, "Number of expansions");
42 STATISTIC(NumReassoc, "Number of reassociations");
47 const TargetLibraryInfo *TLI;
48 const DominatorTree *DT;
49 AssumptionTracker *AT;
50 const Instruction *CxtI;
52 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
53 const DominatorTree *dt, AssumptionTracker *at = nullptr,
54 const Instruction *cxti = nullptr)
55 : DL(DL), TLI(tli), DT(dt), AT(at), CxtI(cxti) {}
57 } // end anonymous namespace
59 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
60 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
62 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
64 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
65 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
66 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
68 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
69 /// a vector with every element false, as appropriate for the type.
70 static Constant *getFalse(Type *Ty) {
71 assert(Ty->getScalarType()->isIntegerTy(1) &&
72 "Expected i1 type or a vector of i1!");
73 return Constant::getNullValue(Ty);
76 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
77 /// a vector with every element true, as appropriate for the type.
78 static Constant *getTrue(Type *Ty) {
79 assert(Ty->getScalarType()->isIntegerTy(1) &&
80 "Expected i1 type or a vector of i1!");
81 return Constant::getAllOnesValue(Ty);
84 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
85 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
87 CmpInst *Cmp = dyn_cast<CmpInst>(V);
90 CmpInst::Predicate CPred = Cmp->getPredicate();
91 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
92 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
94 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
98 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
99 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
100 Instruction *I = dyn_cast<Instruction>(V);
102 // Arguments and constants dominate all instructions.
105 // If we are processing instructions (and/or basic blocks) that have not been
106 // fully added to a function, the parent nodes may still be null. Simply
107 // return the conservative answer in these cases.
108 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
111 // If we have a DominatorTree then do a precise test.
113 if (!DT->isReachableFromEntry(P->getParent()))
115 if (!DT->isReachableFromEntry(I->getParent()))
117 return DT->dominates(I, P);
120 // Otherwise, if the instruction is in the entry block, and is not an invoke,
121 // then it obviously dominates all phi nodes.
122 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
129 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
130 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
131 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
132 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
133 /// Returns the simplified value, or null if no simplification was performed.
134 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
135 unsigned OpcToExpand, const Query &Q,
136 unsigned MaxRecurse) {
137 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
138 // Recursion is always used, so bail out at once if we already hit the limit.
142 // Check whether the expression has the form "(A op' B) op C".
143 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
144 if (Op0->getOpcode() == OpcodeToExpand) {
145 // It does! Try turning it into "(A op C) op' (B op C)".
146 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
147 // Do "A op C" and "B op C" both simplify?
148 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
149 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
150 // They do! Return "L op' R" if it simplifies or is already available.
151 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
152 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
153 && L == B && R == A)) {
157 // Otherwise return "L op' R" if it simplifies.
158 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
165 // Check whether the expression has the form "A op (B op' C)".
166 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
167 if (Op1->getOpcode() == OpcodeToExpand) {
168 // It does! Try turning it into "(A op B) op' (A op C)".
169 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
170 // Do "A op B" and "A op C" both simplify?
171 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
172 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
173 // They do! Return "L op' R" if it simplifies or is already available.
174 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
175 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
176 && L == C && R == B)) {
180 // Otherwise return "L op' R" if it simplifies.
181 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
191 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
192 /// operations. Returns the simpler value, or null if none was found.
193 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
194 const Query &Q, unsigned MaxRecurse) {
195 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
196 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
198 // Recursion is always used, so bail out at once if we already hit the limit.
202 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
203 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
205 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
206 if (Op0 && Op0->getOpcode() == Opcode) {
207 Value *A = Op0->getOperand(0);
208 Value *B = Op0->getOperand(1);
211 // Does "B op C" simplify?
212 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
213 // It does! Return "A op V" if it simplifies or is already available.
214 // If V equals B then "A op V" is just the LHS.
215 if (V == B) return LHS;
216 // Otherwise return "A op V" if it simplifies.
217 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
224 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
225 if (Op1 && Op1->getOpcode() == Opcode) {
227 Value *B = Op1->getOperand(0);
228 Value *C = Op1->getOperand(1);
230 // Does "A op B" simplify?
231 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
232 // It does! Return "V op C" if it simplifies or is already available.
233 // If V equals B then "V op C" is just the RHS.
234 if (V == B) return RHS;
235 // Otherwise return "V op C" if it simplifies.
236 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
243 // The remaining transforms require commutativity as well as associativity.
244 if (!Instruction::isCommutative(Opcode))
247 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
248 if (Op0 && Op0->getOpcode() == Opcode) {
249 Value *A = Op0->getOperand(0);
250 Value *B = Op0->getOperand(1);
253 // Does "C op A" simplify?
254 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
255 // It does! Return "V op B" if it simplifies or is already available.
256 // If V equals A then "V op B" is just the LHS.
257 if (V == A) return LHS;
258 // Otherwise return "V op B" if it simplifies.
259 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
266 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
267 if (Op1 && Op1->getOpcode() == Opcode) {
269 Value *B = Op1->getOperand(0);
270 Value *C = Op1->getOperand(1);
272 // Does "C op A" simplify?
273 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
274 // It does! Return "B op V" if it simplifies or is already available.
275 // If V equals C then "B op V" is just the RHS.
276 if (V == C) return RHS;
277 // Otherwise return "B op V" if it simplifies.
278 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
288 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
289 /// instruction as an operand, try to simplify the binop by seeing whether
290 /// evaluating it on both branches of the select results in the same value.
291 /// Returns the common value if so, otherwise returns null.
292 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
293 const Query &Q, unsigned MaxRecurse) {
294 // Recursion is always used, so bail out at once if we already hit the limit.
299 if (isa<SelectInst>(LHS)) {
300 SI = cast<SelectInst>(LHS);
302 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
303 SI = cast<SelectInst>(RHS);
306 // Evaluate the BinOp on the true and false branches of the select.
310 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
311 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
313 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
314 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
317 // If they simplified to the same value, then return the common value.
318 // If they both failed to simplify then return null.
322 // If one branch simplified to undef, return the other one.
323 if (TV && isa<UndefValue>(TV))
325 if (FV && isa<UndefValue>(FV))
328 // If applying the operation did not change the true and false select values,
329 // then the result of the binop is the select itself.
330 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
333 // If one branch simplified and the other did not, and the simplified
334 // value is equal to the unsimplified one, return the simplified value.
335 // For example, select (cond, X, X & Z) & Z -> X & Z.
336 if ((FV && !TV) || (TV && !FV)) {
337 // Check that the simplified value has the form "X op Y" where "op" is the
338 // same as the original operation.
339 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
340 if (Simplified && Simplified->getOpcode() == Opcode) {
341 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
342 // We already know that "op" is the same as for the simplified value. See
343 // if the operands match too. If so, return the simplified value.
344 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
345 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
346 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
347 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
348 Simplified->getOperand(1) == UnsimplifiedRHS)
350 if (Simplified->isCommutative() &&
351 Simplified->getOperand(1) == UnsimplifiedLHS &&
352 Simplified->getOperand(0) == UnsimplifiedRHS)
360 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
361 /// try to simplify the comparison by seeing whether both branches of the select
362 /// result in the same value. Returns the common value if so, otherwise returns
364 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
365 Value *RHS, const Query &Q,
366 unsigned MaxRecurse) {
367 // Recursion is always used, so bail out at once if we already hit the limit.
371 // Make sure the select is on the LHS.
372 if (!isa<SelectInst>(LHS)) {
374 Pred = CmpInst::getSwappedPredicate(Pred);
376 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
377 SelectInst *SI = cast<SelectInst>(LHS);
378 Value *Cond = SI->getCondition();
379 Value *TV = SI->getTrueValue();
380 Value *FV = SI->getFalseValue();
382 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
383 // Does "cmp TV, RHS" simplify?
384 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
386 // It not only simplified, it simplified to the select condition. Replace
388 TCmp = getTrue(Cond->getType());
390 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
391 // condition then we can replace it with 'true'. Otherwise give up.
392 if (!isSameCompare(Cond, Pred, TV, RHS))
394 TCmp = getTrue(Cond->getType());
397 // Does "cmp FV, RHS" simplify?
398 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
400 // It not only simplified, it simplified to the select condition. Replace
402 FCmp = getFalse(Cond->getType());
404 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
405 // condition then we can replace it with 'false'. Otherwise give up.
406 if (!isSameCompare(Cond, Pred, FV, RHS))
408 FCmp = getFalse(Cond->getType());
411 // If both sides simplified to the same value, then use it as the result of
412 // the original comparison.
416 // The remaining cases only make sense if the select condition has the same
417 // type as the result of the comparison, so bail out if this is not so.
418 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
420 // If the false value simplified to false, then the result of the compare
421 // is equal to "Cond && TCmp". This also catches the case when the false
422 // value simplified to false and the true value to true, returning "Cond".
423 if (match(FCmp, m_Zero()))
424 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
426 // If the true value simplified to true, then the result of the compare
427 // is equal to "Cond || FCmp".
428 if (match(TCmp, m_One()))
429 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
431 // Finally, if the false value simplified to true and the true value to
432 // false, then the result of the compare is equal to "!Cond".
433 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
435 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
442 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
443 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
444 /// it on the incoming phi values yields the same result for every value. If so
445 /// returns the common value, otherwise returns null.
446 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
447 const Query &Q, unsigned MaxRecurse) {
448 // Recursion is always used, so bail out at once if we already hit the limit.
453 if (isa<PHINode>(LHS)) {
454 PI = cast<PHINode>(LHS);
455 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
456 if (!ValueDominatesPHI(RHS, PI, Q.DT))
459 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
460 PI = cast<PHINode>(RHS);
461 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
462 if (!ValueDominatesPHI(LHS, PI, Q.DT))
466 // Evaluate the BinOp on the incoming phi values.
467 Value *CommonValue = nullptr;
468 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
469 Value *Incoming = PI->getIncomingValue(i);
470 // If the incoming value is the phi node itself, it can safely be skipped.
471 if (Incoming == PI) continue;
472 Value *V = PI == LHS ?
473 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
474 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
475 // If the operation failed to simplify, or simplified to a different value
476 // to previously, then give up.
477 if (!V || (CommonValue && V != CommonValue))
485 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
486 /// try to simplify the comparison by seeing whether comparing with all of the
487 /// incoming phi values yields the same result every time. If so returns the
488 /// common result, otherwise returns null.
489 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
490 const Query &Q, unsigned MaxRecurse) {
491 // Recursion is always used, so bail out at once if we already hit the limit.
495 // Make sure the phi is on the LHS.
496 if (!isa<PHINode>(LHS)) {
498 Pred = CmpInst::getSwappedPredicate(Pred);
500 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
501 PHINode *PI = cast<PHINode>(LHS);
503 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
504 if (!ValueDominatesPHI(RHS, PI, Q.DT))
507 // Evaluate the BinOp on the incoming phi values.
508 Value *CommonValue = nullptr;
509 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
510 Value *Incoming = PI->getIncomingValue(i);
511 // If the incoming value is the phi node itself, it can safely be skipped.
512 if (Incoming == PI) continue;
513 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
514 // If the operation failed to simplify, or simplified to a different value
515 // to previously, then give up.
516 if (!V || (CommonValue && V != CommonValue))
524 /// SimplifyAddInst - Given operands for an Add, see if we can
525 /// fold the result. If not, this returns null.
526 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
527 const Query &Q, unsigned MaxRecurse) {
528 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
529 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
530 Constant *Ops[] = { CLHS, CRHS };
531 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
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, AssumptionTracker *AT,
585 const Instruction *CxtI) {
586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW,
587 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
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,
602 bool AllowNonInbounds = false) {
603 assert(V->getType()->getScalarType()->isPointerTy());
605 // Without DataLayout, just be conservative for now. Theoretically, more could
606 // be done in this case.
608 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
610 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
611 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
613 // Even though we don't look through PHI nodes, we could be called on an
614 // instruction in an unreachable block, which may be on a cycle.
615 SmallPtrSet<Value *, 4> Visited;
618 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
619 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
620 !GEP->accumulateConstantOffset(*DL, Offset))
622 V = GEP->getPointerOperand();
623 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
624 V = cast<Operator>(V)->getOperand(0);
625 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
626 if (GA->mayBeOverridden())
628 V = GA->getAliasee();
632 assert(V->getType()->getScalarType()->isPointerTy() &&
633 "Unexpected operand type!");
634 } while (Visited.insert(V));
636 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
637 if (V->getType()->isVectorTy())
638 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
643 /// \brief Compute the constant difference between two pointer values.
644 /// If the difference is not a constant, returns zero.
645 static Constant *computePointerDifference(const DataLayout *DL,
646 Value *LHS, Value *RHS) {
647 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
648 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
650 // If LHS and RHS are not related via constant offsets to the same base
651 // value, there is nothing we can do here.
655 // Otherwise, the difference of LHS - RHS can be computed as:
657 // = (LHSOffset + Base) - (RHSOffset + Base)
658 // = LHSOffset - RHSOffset
659 return ConstantExpr::getSub(LHSOffset, RHSOffset);
662 /// SimplifySubInst - Given operands for a Sub, see if we can
663 /// fold the result. If not, this returns null.
664 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
665 const Query &Q, unsigned MaxRecurse) {
666 if (Constant *CLHS = dyn_cast<Constant>(Op0))
667 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
668 Constant *Ops[] = { CLHS, CRHS };
669 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
673 // X - undef -> undef
674 // undef - X -> undef
675 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
676 return UndefValue::get(Op0->getType());
679 if (match(Op1, m_Zero()))
684 return Constant::getNullValue(Op0->getType());
686 // X - (0 - Y) -> X if the second sub is NUW.
687 // If Y != 0, 0 - Y is a poison value.
688 // If Y == 0, 0 - Y simplifies to 0.
689 if (BinaryOperator::isNeg(Op1)) {
690 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
691 assert(BO->getOpcode() == Instruction::Sub &&
692 "Expected a subtraction operator!");
693 if (BO->hasNoUnsignedWrap())
698 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
699 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
700 Value *X = nullptr, *Y = nullptr, *Z = Op1;
701 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
702 // See if "V === Y - Z" simplifies.
703 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
704 // It does! Now see if "X + V" simplifies.
705 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
706 // It does, we successfully reassociated!
710 // See if "V === X - Z" simplifies.
711 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
712 // It does! Now see if "Y + V" simplifies.
713 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
714 // It does, we successfully reassociated!
720 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
721 // For example, X - (X + 1) -> -1
723 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
724 // See if "V === X - Y" simplifies.
725 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
726 // It does! Now see if "V - Z" simplifies.
727 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
728 // It does, we successfully reassociated!
732 // See if "V === X - Z" simplifies.
733 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
734 // It does! Now see if "V - Y" simplifies.
735 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
736 // It does, we successfully reassociated!
742 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
743 // For example, X - (X - Y) -> Y.
745 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
746 // See if "V === Z - X" simplifies.
747 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
748 // It does! Now see if "V + Y" simplifies.
749 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
750 // It does, we successfully reassociated!
755 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
756 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
757 match(Op1, m_Trunc(m_Value(Y))))
758 if (X->getType() == Y->getType())
759 // See if "V === X - Y" simplifies.
760 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
761 // It does! Now see if "trunc V" simplifies.
762 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
763 // It does, return the simplified "trunc V".
766 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
767 if (match(Op0, m_PtrToInt(m_Value(X))) &&
768 match(Op1, m_PtrToInt(m_Value(Y))))
769 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
770 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
773 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
774 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
777 // Threading Sub over selects and phi nodes is pointless, so don't bother.
778 // Threading over the select in "A - select(cond, B, C)" means evaluating
779 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
780 // only if B and C are equal. If B and C are equal then (since we assume
781 // that operands have already been simplified) "select(cond, B, C)" should
782 // have been simplified to the common value of B and C already. Analysing
783 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
784 // for threading over phi nodes.
789 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
790 const DataLayout *DL, const TargetLibraryInfo *TLI,
791 const DominatorTree *DT, AssumptionTracker *AT,
792 const Instruction *CxtI) {
793 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW,
794 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
797 /// Given operands for an FAdd, see if we can fold the result. If not, this
799 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
800 const Query &Q, unsigned MaxRecurse) {
801 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
802 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
803 Constant *Ops[] = { CLHS, CRHS };
804 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
808 // Canonicalize the constant to the RHS.
813 if (match(Op1, m_NegZero()))
816 // fadd X, 0 ==> X, when we know X is not -0
817 if (match(Op1, m_Zero()) &&
818 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
821 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
822 // where nnan and ninf have to occur at least once somewhere in this
824 Value *SubOp = nullptr;
825 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
827 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
830 Instruction *FSub = cast<Instruction>(SubOp);
831 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
832 (FMF.noInfs() || FSub->hasNoInfs()))
833 return Constant::getNullValue(Op0->getType());
839 /// Given operands for an FSub, see if we can fold the result. If not, this
841 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
842 const Query &Q, unsigned MaxRecurse) {
843 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
844 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
845 Constant *Ops[] = { CLHS, CRHS };
846 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
852 if (match(Op1, m_Zero()))
855 // fsub X, -0 ==> X, when we know X is not -0
856 if (match(Op1, m_NegZero()) &&
857 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
860 // fsub 0, (fsub -0.0, X) ==> X
862 if (match(Op0, m_AnyZero())) {
863 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
865 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
869 // fsub nnan ninf x, x ==> 0.0
870 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
871 return Constant::getNullValue(Op0->getType());
876 /// Given the operands for an FMul, see if we can fold the result
877 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
880 unsigned MaxRecurse) {
881 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
882 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
883 Constant *Ops[] = { CLHS, CRHS };
884 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
888 // Canonicalize the constant to the RHS.
893 if (match(Op1, m_FPOne()))
896 // fmul nnan nsz X, 0 ==> 0
897 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
903 /// SimplifyMulInst - Given operands for a Mul, see if we can
904 /// fold the result. If not, this returns null.
905 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
906 unsigned MaxRecurse) {
907 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
908 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
909 Constant *Ops[] = { CLHS, CRHS };
910 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
914 // Canonicalize the constant to the RHS.
919 if (match(Op1, m_Undef()))
920 return Constant::getNullValue(Op0->getType());
923 if (match(Op1, m_Zero()))
927 if (match(Op1, m_One()))
930 // (X / Y) * Y -> X if the division is exact.
932 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
933 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
937 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
938 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
941 // Try some generic simplifications for associative operations.
942 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
946 // Mul distributes over Add. Try some generic simplifications based on this.
947 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
951 // If the operation is with the result of a select instruction, check whether
952 // operating on either branch of the select always yields the same value.
953 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
954 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
958 // If the operation is with the result of a phi instruction, check whether
959 // operating on all incoming values of the phi always yields the same value.
960 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
961 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
968 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
969 const DataLayout *DL, const TargetLibraryInfo *TLI,
970 const DominatorTree *DT, AssumptionTracker *AT,
971 const Instruction *CxtI) {
972 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
976 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
977 const DataLayout *DL, const TargetLibraryInfo *TLI,
978 const DominatorTree *DT, AssumptionTracker *AT,
979 const Instruction *CxtI) {
980 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
984 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
986 const DataLayout *DL,
987 const TargetLibraryInfo *TLI,
988 const DominatorTree *DT,
989 AssumptionTracker *AT,
990 const Instruction *CxtI) {
991 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
995 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
996 const TargetLibraryInfo *TLI,
997 const DominatorTree *DT, AssumptionTracker *AT,
998 const Instruction *CxtI) {
999 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1003 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1004 /// fold the result. If not, this returns null.
1005 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1006 const Query &Q, unsigned MaxRecurse) {
1007 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1008 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1009 Constant *Ops[] = { C0, C1 };
1010 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1014 bool isSigned = Opcode == Instruction::SDiv;
1016 // X / undef -> undef
1017 if (match(Op1, m_Undef()))
1021 if (match(Op0, m_Undef()))
1022 return Constant::getNullValue(Op0->getType());
1024 // 0 / X -> 0, we don't need to preserve faults!
1025 if (match(Op0, m_Zero()))
1029 if (match(Op1, m_One()))
1032 if (Op0->getType()->isIntegerTy(1))
1033 // It can't be division by zero, hence it must be division by one.
1038 return ConstantInt::get(Op0->getType(), 1);
1040 // (X * Y) / Y -> X if the multiplication does not overflow.
1041 Value *X = nullptr, *Y = nullptr;
1042 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1043 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1044 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1045 // If the Mul knows it does not overflow, then we are good to go.
1046 if ((isSigned && Mul->hasNoSignedWrap()) ||
1047 (!isSigned && Mul->hasNoUnsignedWrap()))
1049 // If X has the form X = A / Y then X * Y cannot overflow.
1050 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1051 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1055 // (X rem Y) / Y -> 0
1056 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1057 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1058 return Constant::getNullValue(Op0->getType());
1060 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1061 ConstantInt *C1, *C2;
1062 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1063 match(Op1, m_ConstantInt(C2))) {
1065 C1->getValue().umul_ov(C2->getValue(), Overflow);
1067 return Constant::getNullValue(Op0->getType());
1070 // If the operation is with the result of a select instruction, check whether
1071 // operating on either branch of the select always yields the same value.
1072 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1073 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1076 // If the operation is with the result of a phi instruction, check whether
1077 // operating on all incoming values of the phi always yields the same value.
1078 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1079 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1085 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1086 /// fold the result. If not, this returns null.
1087 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1088 unsigned MaxRecurse) {
1089 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1095 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1096 const TargetLibraryInfo *TLI,
1097 const DominatorTree *DT,
1098 AssumptionTracker *AT,
1099 const Instruction *CxtI) {
1100 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1104 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1105 /// fold the result. If not, this returns null.
1106 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1107 unsigned MaxRecurse) {
1108 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1114 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1115 const TargetLibraryInfo *TLI,
1116 const DominatorTree *DT,
1117 AssumptionTracker *AT,
1118 const Instruction *CxtI) {
1119 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1123 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1125 // undef / X -> undef (the undef could be a snan).
1126 if (match(Op0, m_Undef()))
1129 // X / undef -> undef
1130 if (match(Op1, m_Undef()))
1136 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1137 const TargetLibraryInfo *TLI,
1138 const DominatorTree *DT,
1139 AssumptionTracker *AT,
1140 const Instruction *CxtI) {
1141 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1145 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1146 /// fold the result. If not, this returns null.
1147 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1148 const Query &Q, unsigned MaxRecurse) {
1149 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1150 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1151 Constant *Ops[] = { C0, C1 };
1152 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1156 // X % undef -> undef
1157 if (match(Op1, m_Undef()))
1161 if (match(Op0, m_Undef()))
1162 return Constant::getNullValue(Op0->getType());
1164 // 0 % X -> 0, we don't need to preserve faults!
1165 if (match(Op0, m_Zero()))
1168 // X % 0 -> undef, we don't need to preserve faults!
1169 if (match(Op1, m_Zero()))
1170 return UndefValue::get(Op0->getType());
1173 if (match(Op1, m_One()))
1174 return Constant::getNullValue(Op0->getType());
1176 if (Op0->getType()->isIntegerTy(1))
1177 // It can't be remainder by zero, hence it must be remainder by one.
1178 return Constant::getNullValue(Op0->getType());
1182 return Constant::getNullValue(Op0->getType());
1184 // (X % Y) % Y -> X % Y
1185 if ((Opcode == Instruction::SRem &&
1186 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1187 (Opcode == Instruction::URem &&
1188 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1191 // If the operation is with the result of a select instruction, check whether
1192 // operating on either branch of the select always yields the same value.
1193 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1194 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1197 // If the operation is with the result of a phi instruction, check whether
1198 // operating on all incoming values of the phi always yields the same value.
1199 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1200 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1206 /// SimplifySRemInst - Given operands for an SRem, see if we can
1207 /// fold the result. If not, this returns null.
1208 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1209 unsigned MaxRecurse) {
1210 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1216 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1217 const TargetLibraryInfo *TLI,
1218 const DominatorTree *DT,
1219 AssumptionTracker *AT,
1220 const Instruction *CxtI) {
1221 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1225 /// SimplifyURemInst - Given operands for a URem, see if we can
1226 /// fold the result. If not, this returns null.
1227 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1228 unsigned MaxRecurse) {
1229 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1235 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1236 const TargetLibraryInfo *TLI,
1237 const DominatorTree *DT,
1238 AssumptionTracker *AT,
1239 const Instruction *CxtI) {
1240 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1244 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1246 // undef % X -> undef (the undef could be a snan).
1247 if (match(Op0, m_Undef()))
1250 // X % undef -> undef
1251 if (match(Op1, m_Undef()))
1257 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1258 const TargetLibraryInfo *TLI,
1259 const DominatorTree *DT,
1260 AssumptionTracker *AT,
1261 const Instruction *CxtI) {
1262 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1266 /// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1267 static bool isUndefShift(Value *Amount) {
1268 Constant *C = dyn_cast<Constant>(Amount);
1272 // X shift by undef -> undef because it may shift by the bitwidth.
1273 if (isa<UndefValue>(C))
1276 // Shifting by the bitwidth or more is undefined.
1277 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1278 if (CI->getValue().getLimitedValue() >=
1279 CI->getType()->getScalarSizeInBits())
1282 // If all lanes of a vector shift are undefined the whole shift is.
1283 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1284 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1285 if (!isUndefShift(C->getAggregateElement(I)))
1293 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1294 /// fold the result. If not, this returns null.
1295 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1296 const Query &Q, unsigned MaxRecurse) {
1297 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1298 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1299 Constant *Ops[] = { C0, C1 };
1300 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1304 // 0 shift by X -> 0
1305 if (match(Op0, m_Zero()))
1308 // X shift by 0 -> X
1309 if (match(Op1, m_Zero()))
1312 // Fold undefined shifts.
1313 if (isUndefShift(Op1))
1314 return UndefValue::get(Op0->getType());
1316 // If the operation is with the result of a select instruction, check whether
1317 // operating on either branch of the select always yields the same value.
1318 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1319 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1322 // If the operation is with the result of a phi instruction, check whether
1323 // operating on all incoming values of the phi always yields the same value.
1324 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1325 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1331 /// SimplifyShlInst - Given operands for an Shl, see if we can
1332 /// fold the result. If not, this returns null.
1333 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1334 const Query &Q, unsigned MaxRecurse) {
1335 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1339 if (match(Op0, m_Undef()))
1340 return Constant::getNullValue(Op0->getType());
1342 // (X >> A) << A -> X
1344 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1349 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1350 const DataLayout *DL, const TargetLibraryInfo *TLI,
1351 const DominatorTree *DT, AssumptionTracker *AT,
1352 const Instruction *CxtI) {
1353 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT, AT, CxtI),
1357 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1358 /// fold the result. If not, this returns null.
1359 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1360 const Query &Q, unsigned MaxRecurse) {
1361 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1366 return Constant::getNullValue(Op0->getType());
1369 if (match(Op0, m_Undef()))
1370 return Constant::getNullValue(Op0->getType());
1372 // (X << A) >> A -> X
1374 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1375 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1381 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1382 const DataLayout *DL,
1383 const TargetLibraryInfo *TLI,
1384 const DominatorTree *DT,
1385 AssumptionTracker *AT,
1386 const Instruction *CxtI) {
1387 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
1391 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1392 /// fold the result. If not, this returns null.
1393 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1394 const Query &Q, unsigned MaxRecurse) {
1395 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1400 return Constant::getNullValue(Op0->getType());
1402 // all ones >>a X -> all ones
1403 if (match(Op0, m_AllOnes()))
1406 // undef >>a X -> all ones
1407 if (match(Op0, m_Undef()))
1408 return Constant::getAllOnesValue(Op0->getType());
1410 // (X << A) >> A -> X
1412 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1413 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1416 // Arithmetic shifting an all-sign-bit value is a no-op.
1417 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AT, Q.CxtI, Q.DT);
1418 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1424 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1425 const DataLayout *DL,
1426 const TargetLibraryInfo *TLI,
1427 const DominatorTree *DT,
1428 AssumptionTracker *AT,
1429 const Instruction *CxtI) {
1430 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
1434 // Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
1435 // of possible values cannot be satisfied.
1436 static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1437 ICmpInst::Predicate Pred0, Pred1;
1438 ConstantInt *CI1, *CI2;
1440 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1441 m_ConstantInt(CI2))))
1444 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1447 Type *ITy = Op0->getType();
1449 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1450 bool isNSW = AddInst->hasNoSignedWrap();
1451 bool isNUW = AddInst->hasNoUnsignedWrap();
1453 const APInt &CI1V = CI1->getValue();
1454 const APInt &CI2V = CI2->getValue();
1455 const APInt Delta = CI2V - CI1V;
1456 if (CI1V.isStrictlyPositive()) {
1458 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1459 return getFalse(ITy);
1460 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1461 return getFalse(ITy);
1464 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1465 return getFalse(ITy);
1466 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1467 return getFalse(ITy);
1470 if (CI1V.getBoolValue() && isNUW) {
1472 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1473 return getFalse(ITy);
1475 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1476 return getFalse(ITy);
1482 /// SimplifyAndInst - Given operands for an And, see if we can
1483 /// fold the result. If not, this returns null.
1484 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1485 unsigned MaxRecurse) {
1486 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1487 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1488 Constant *Ops[] = { CLHS, CRHS };
1489 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1493 // Canonicalize the constant to the RHS.
1494 std::swap(Op0, Op1);
1498 if (match(Op1, m_Undef()))
1499 return Constant::getNullValue(Op0->getType());
1506 if (match(Op1, m_Zero()))
1510 if (match(Op1, m_AllOnes()))
1513 // A & ~A = ~A & A = 0
1514 if (match(Op0, m_Not(m_Specific(Op1))) ||
1515 match(Op1, m_Not(m_Specific(Op0))))
1516 return Constant::getNullValue(Op0->getType());
1519 Value *A = nullptr, *B = nullptr;
1520 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1521 (A == Op1 || B == Op1))
1525 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1526 (A == Op0 || B == Op0))
1529 // A & (-A) = A if A is a power of two or zero.
1530 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1531 match(Op1, m_Neg(m_Specific(Op0)))) {
1532 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
1534 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
1538 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1539 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1540 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1542 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1547 // Try some generic simplifications for associative operations.
1548 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1552 // And distributes over Or. Try some generic simplifications based on this.
1553 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1557 // And distributes over Xor. Try some generic simplifications based on this.
1558 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1562 // If the operation is with the result of a select instruction, check whether
1563 // operating on either branch of the select always yields the same value.
1564 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1565 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1569 // If the operation is with the result of a phi instruction, check whether
1570 // operating on all incoming values of the phi always yields the same value.
1571 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1572 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1579 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
1580 const TargetLibraryInfo *TLI,
1581 const DominatorTree *DT, AssumptionTracker *AT,
1582 const Instruction *CxtI) {
1583 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1587 // Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1588 // contains all possible values.
1589 static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1590 ICmpInst::Predicate Pred0, Pred1;
1591 ConstantInt *CI1, *CI2;
1593 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1594 m_ConstantInt(CI2))))
1597 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1600 Type *ITy = Op0->getType();
1602 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1603 bool isNSW = AddInst->hasNoSignedWrap();
1604 bool isNUW = AddInst->hasNoUnsignedWrap();
1606 const APInt &CI1V = CI1->getValue();
1607 const APInt &CI2V = CI2->getValue();
1608 const APInt Delta = CI2V - CI1V;
1609 if (CI1V.isStrictlyPositive()) {
1611 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1612 return getTrue(ITy);
1613 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1614 return getTrue(ITy);
1617 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1618 return getTrue(ITy);
1619 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1620 return getTrue(ITy);
1623 if (CI1V.getBoolValue() && isNUW) {
1625 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1626 return getTrue(ITy);
1628 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1629 return getTrue(ITy);
1635 /// SimplifyOrInst - Given operands for an Or, see if we can
1636 /// fold the result. If not, this returns null.
1637 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1638 unsigned MaxRecurse) {
1639 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1640 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1641 Constant *Ops[] = { CLHS, CRHS };
1642 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1646 // Canonicalize the constant to the RHS.
1647 std::swap(Op0, Op1);
1651 if (match(Op1, m_Undef()))
1652 return Constant::getAllOnesValue(Op0->getType());
1659 if (match(Op1, m_Zero()))
1663 if (match(Op1, m_AllOnes()))
1666 // A | ~A = ~A | A = -1
1667 if (match(Op0, m_Not(m_Specific(Op1))) ||
1668 match(Op1, m_Not(m_Specific(Op0))))
1669 return Constant::getAllOnesValue(Op0->getType());
1672 Value *A = nullptr, *B = nullptr;
1673 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1674 (A == Op1 || B == Op1))
1678 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1679 (A == Op0 || B == Op0))
1682 // ~(A & ?) | A = -1
1683 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1684 (A == Op1 || B == Op1))
1685 return Constant::getAllOnesValue(Op1->getType());
1687 // A | ~(A & ?) = -1
1688 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1689 (A == Op0 || B == Op0))
1690 return Constant::getAllOnesValue(Op0->getType());
1692 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1693 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1694 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1696 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1701 // Try some generic simplifications for associative operations.
1702 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1706 // Or distributes over And. Try some generic simplifications based on this.
1707 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1711 // If the operation is with the result of a select instruction, check whether
1712 // operating on either branch of the select always yields the same value.
1713 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1714 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1719 Value *C = nullptr, *D = nullptr;
1720 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1721 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1722 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1723 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1724 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1725 // (A & C1)|(B & C2)
1726 // If we have: ((V + N) & C1) | (V & C2)
1727 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1728 // replace with V+N.
1730 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1731 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1732 // Add commutes, try both ways.
1733 if (V1 == B && MaskedValueIsZero(V2, C2->getValue(), Q.DL,
1734 0, Q.AT, Q.CxtI, Q.DT))
1736 if (V2 == B && MaskedValueIsZero(V1, C2->getValue(), Q.DL,
1737 0, Q.AT, Q.CxtI, Q.DT))
1740 // Or commutes, try both ways.
1741 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1742 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1743 // Add commutes, try both ways.
1744 if (V1 == A && MaskedValueIsZero(V2, C1->getValue(), Q.DL,
1745 0, Q.AT, Q.CxtI, Q.DT))
1747 if (V2 == A && MaskedValueIsZero(V1, C1->getValue(), Q.DL,
1748 0, Q.AT, Q.CxtI, Q.DT))
1754 // If the operation is with the result of a phi instruction, check whether
1755 // operating on all incoming values of the phi always yields the same value.
1756 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1757 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1763 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
1764 const TargetLibraryInfo *TLI,
1765 const DominatorTree *DT, AssumptionTracker *AT,
1766 const Instruction *CxtI) {
1767 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1771 /// SimplifyXorInst - Given operands for a Xor, see if we can
1772 /// fold the result. If not, this returns null.
1773 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1774 unsigned MaxRecurse) {
1775 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1776 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1777 Constant *Ops[] = { CLHS, CRHS };
1778 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1782 // Canonicalize the constant to the RHS.
1783 std::swap(Op0, Op1);
1786 // A ^ undef -> undef
1787 if (match(Op1, m_Undef()))
1791 if (match(Op1, m_Zero()))
1796 return Constant::getNullValue(Op0->getType());
1798 // A ^ ~A = ~A ^ A = -1
1799 if (match(Op0, m_Not(m_Specific(Op1))) ||
1800 match(Op1, m_Not(m_Specific(Op0))))
1801 return Constant::getAllOnesValue(Op0->getType());
1803 // Try some generic simplifications for associative operations.
1804 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1808 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1809 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1810 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1811 // only if B and C are equal. If B and C are equal then (since we assume
1812 // that operands have already been simplified) "select(cond, B, C)" should
1813 // have been simplified to the common value of B and C already. Analysing
1814 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1815 // for threading over phi nodes.
1820 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
1821 const TargetLibraryInfo *TLI,
1822 const DominatorTree *DT, AssumptionTracker *AT,
1823 const Instruction *CxtI) {
1824 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1828 static Type *GetCompareTy(Value *Op) {
1829 return CmpInst::makeCmpResultType(Op->getType());
1832 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1833 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1834 /// otherwise return null. Helper function for analyzing max/min idioms.
1835 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1836 Value *LHS, Value *RHS) {
1837 SelectInst *SI = dyn_cast<SelectInst>(V);
1840 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1843 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1844 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1846 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1847 LHS == CmpRHS && RHS == CmpLHS)
1852 // A significant optimization not implemented here is assuming that alloca
1853 // addresses are not equal to incoming argument values. They don't *alias*,
1854 // as we say, but that doesn't mean they aren't equal, so we take a
1855 // conservative approach.
1857 // This is inspired in part by C++11 5.10p1:
1858 // "Two pointers of the same type compare equal if and only if they are both
1859 // null, both point to the same function, or both represent the same
1862 // This is pretty permissive.
1864 // It's also partly due to C11 6.5.9p6:
1865 // "Two pointers compare equal if and only if both are null pointers, both are
1866 // pointers to the same object (including a pointer to an object and a
1867 // subobject at its beginning) or function, both are pointers to one past the
1868 // last element of the same array object, or one is a pointer to one past the
1869 // end of one array object and the other is a pointer to the start of a
1870 // different array object that happens to immediately follow the first array
1871 // object in the address space.)
1873 // C11's version is more restrictive, however there's no reason why an argument
1874 // couldn't be a one-past-the-end value for a stack object in the caller and be
1875 // equal to the beginning of a stack object in the callee.
1877 // If the C and C++ standards are ever made sufficiently restrictive in this
1878 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1879 // this optimization.
1880 static Constant *computePointerICmp(const DataLayout *DL,
1881 const TargetLibraryInfo *TLI,
1882 CmpInst::Predicate Pred,
1883 Value *LHS, Value *RHS) {
1884 // First, skip past any trivial no-ops.
1885 LHS = LHS->stripPointerCasts();
1886 RHS = RHS->stripPointerCasts();
1888 // A non-null pointer is not equal to a null pointer.
1889 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1890 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1891 return ConstantInt::get(GetCompareTy(LHS),
1892 !CmpInst::isTrueWhenEqual(Pred));
1894 // We can only fold certain predicates on pointer comparisons.
1899 // Equality comaprisons are easy to fold.
1900 case CmpInst::ICMP_EQ:
1901 case CmpInst::ICMP_NE:
1904 // We can only handle unsigned relational comparisons because 'inbounds' on
1905 // a GEP only protects against unsigned wrapping.
1906 case CmpInst::ICMP_UGT:
1907 case CmpInst::ICMP_UGE:
1908 case CmpInst::ICMP_ULT:
1909 case CmpInst::ICMP_ULE:
1910 // However, we have to switch them to their signed variants to handle
1911 // negative indices from the base pointer.
1912 Pred = ICmpInst::getSignedPredicate(Pred);
1916 // Strip off any constant offsets so that we can reason about them.
1917 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1918 // here and compare base addresses like AliasAnalysis does, however there are
1919 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1920 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1921 // doesn't need to guarantee pointer inequality when it says NoAlias.
1922 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1923 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
1925 // If LHS and RHS are related via constant offsets to the same base
1926 // value, we can replace it with an icmp which just compares the offsets.
1928 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1930 // Various optimizations for (in)equality comparisons.
1931 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1932 // Different non-empty allocations that exist at the same time have
1933 // different addresses (if the program can tell). Global variables always
1934 // exist, so they always exist during the lifetime of each other and all
1935 // allocas. Two different allocas usually have different addresses...
1937 // However, if there's an @llvm.stackrestore dynamically in between two
1938 // allocas, they may have the same address. It's tempting to reduce the
1939 // scope of the problem by only looking at *static* allocas here. That would
1940 // cover the majority of allocas while significantly reducing the likelihood
1941 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1942 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1943 // an entry block. Also, if we have a block that's not attached to a
1944 // function, we can't tell if it's "static" under the current definition.
1945 // Theoretically, this problem could be fixed by creating a new kind of
1946 // instruction kind specifically for static allocas. Such a new instruction
1947 // could be required to be at the top of the entry block, thus preventing it
1948 // from being subject to a @llvm.stackrestore. Instcombine could even
1949 // convert regular allocas into these special allocas. It'd be nifty.
1950 // However, until then, this problem remains open.
1952 // So, we'll assume that two non-empty allocas have different addresses
1955 // With all that, if the offsets are within the bounds of their allocations
1956 // (and not one-past-the-end! so we can't use inbounds!), and their
1957 // allocations aren't the same, the pointers are not equal.
1959 // Note that it's not necessary to check for LHS being a global variable
1960 // address, due to canonicalization and constant folding.
1961 if (isa<AllocaInst>(LHS) &&
1962 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
1963 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1964 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
1965 uint64_t LHSSize, RHSSize;
1966 if (LHSOffsetCI && RHSOffsetCI &&
1967 getObjectSize(LHS, LHSSize, DL, TLI) &&
1968 getObjectSize(RHS, RHSSize, DL, TLI)) {
1969 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1970 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
1971 if (!LHSOffsetValue.isNegative() &&
1972 !RHSOffsetValue.isNegative() &&
1973 LHSOffsetValue.ult(LHSSize) &&
1974 RHSOffsetValue.ult(RHSSize)) {
1975 return ConstantInt::get(GetCompareTy(LHS),
1976 !CmpInst::isTrueWhenEqual(Pred));
1980 // Repeat the above check but this time without depending on DataLayout
1981 // or being able to compute a precise size.
1982 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1983 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1984 LHSOffset->isNullValue() &&
1985 RHSOffset->isNullValue())
1986 return ConstantInt::get(GetCompareTy(LHS),
1987 !CmpInst::isTrueWhenEqual(Pred));
1990 // Even if an non-inbounds GEP occurs along the path we can still optimize
1991 // equality comparisons concerning the result. We avoid walking the whole
1992 // chain again by starting where the last calls to
1993 // stripAndComputeConstantOffsets left off and accumulate the offsets.
1994 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1995 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
1997 return ConstantExpr::getICmp(Pred,
1998 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1999 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
2006 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
2007 /// fold the result. If not, this returns null.
2008 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2009 const Query &Q, unsigned MaxRecurse) {
2010 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2011 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
2013 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2014 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2015 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2017 // If we have a constant, make sure it is on the RHS.
2018 std::swap(LHS, RHS);
2019 Pred = CmpInst::getSwappedPredicate(Pred);
2022 Type *ITy = GetCompareTy(LHS); // The return type.
2023 Type *OpTy = LHS->getType(); // The operand type.
2025 // icmp X, X -> true/false
2026 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2027 // because X could be 0.
2028 if (LHS == RHS || isa<UndefValue>(RHS))
2029 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
2031 // Special case logic when the operands have i1 type.
2032 if (OpTy->getScalarType()->isIntegerTy(1)) {
2035 case ICmpInst::ICMP_EQ:
2037 if (match(RHS, m_One()))
2040 case ICmpInst::ICMP_NE:
2042 if (match(RHS, m_Zero()))
2045 case ICmpInst::ICMP_UGT:
2047 if (match(RHS, m_Zero()))
2050 case ICmpInst::ICMP_UGE:
2052 if (match(RHS, m_One()))
2055 case ICmpInst::ICMP_SLT:
2057 if (match(RHS, m_Zero()))
2060 case ICmpInst::ICMP_SLE:
2062 if (match(RHS, m_One()))
2068 // If we are comparing with zero then try hard since this is a common case.
2069 if (match(RHS, m_Zero())) {
2070 bool LHSKnownNonNegative, LHSKnownNegative;
2072 default: llvm_unreachable("Unknown ICmp predicate!");
2073 case ICmpInst::ICMP_ULT:
2074 return getFalse(ITy);
2075 case ICmpInst::ICMP_UGE:
2076 return getTrue(ITy);
2077 case ICmpInst::ICMP_EQ:
2078 case ICmpInst::ICMP_ULE:
2079 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
2080 return getFalse(ITy);
2082 case ICmpInst::ICMP_NE:
2083 case ICmpInst::ICMP_UGT:
2084 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
2085 return getTrue(ITy);
2087 case ICmpInst::ICMP_SLT:
2088 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2089 0, Q.AT, Q.CxtI, Q.DT);
2090 if (LHSKnownNegative)
2091 return getTrue(ITy);
2092 if (LHSKnownNonNegative)
2093 return getFalse(ITy);
2095 case ICmpInst::ICMP_SLE:
2096 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2097 0, Q.AT, Q.CxtI, Q.DT);
2098 if (LHSKnownNegative)
2099 return getTrue(ITy);
2100 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
2101 0, Q.AT, Q.CxtI, Q.DT))
2102 return getFalse(ITy);
2104 case ICmpInst::ICMP_SGE:
2105 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2106 0, Q.AT, Q.CxtI, Q.DT);
2107 if (LHSKnownNegative)
2108 return getFalse(ITy);
2109 if (LHSKnownNonNegative)
2110 return getTrue(ITy);
2112 case ICmpInst::ICMP_SGT:
2113 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
2114 0, Q.AT, Q.CxtI, Q.DT);
2115 if (LHSKnownNegative)
2116 return getFalse(ITy);
2117 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
2118 0, Q.AT, Q.CxtI, Q.DT))
2119 return getTrue(ITy);
2124 // See if we are doing a comparison with a constant integer.
2125 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2126 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2127 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2128 if (RHS_CR.isEmptySet())
2129 return ConstantInt::getFalse(CI->getContext());
2130 if (RHS_CR.isFullSet())
2131 return ConstantInt::getTrue(CI->getContext());
2133 // Many binary operators with constant RHS have easy to compute constant
2134 // range. Use them to check whether the comparison is a tautology.
2135 unsigned Width = CI->getBitWidth();
2136 APInt Lower = APInt(Width, 0);
2137 APInt Upper = APInt(Width, 0);
2139 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2140 // 'urem x, CI2' produces [0, CI2).
2141 Upper = CI2->getValue();
2142 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2143 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2144 Upper = CI2->getValue().abs();
2145 Lower = (-Upper) + 1;
2146 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2147 // 'udiv CI2, x' produces [0, CI2].
2148 Upper = CI2->getValue() + 1;
2149 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2150 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2151 APInt NegOne = APInt::getAllOnesValue(Width);
2153 Upper = NegOne.udiv(CI2->getValue()) + 1;
2154 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2155 if (CI2->isMinSignedValue()) {
2156 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2157 Lower = CI2->getValue();
2158 Upper = Lower.lshr(1) + 1;
2160 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2161 Upper = CI2->getValue().abs() + 1;
2162 Lower = (-Upper) + 1;
2164 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2165 APInt IntMin = APInt::getSignedMinValue(Width);
2166 APInt IntMax = APInt::getSignedMaxValue(Width);
2167 APInt Val = CI2->getValue();
2168 if (Val.isAllOnesValue()) {
2169 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2170 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2173 } else if (Val.countLeadingZeros() < Width - 1) {
2174 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2175 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2176 Lower = IntMin.sdiv(Val);
2177 Upper = IntMax.sdiv(Val);
2178 if (Lower.sgt(Upper))
2179 std::swap(Lower, Upper);
2181 assert(Upper != Lower && "Upper part of range has wrapped!");
2183 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2184 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2185 Lower = CI2->getValue();
2186 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2187 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2188 if (CI2->isNegative()) {
2189 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2190 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2191 Lower = CI2->getValue().shl(ShiftAmount);
2192 Upper = CI2->getValue() + 1;
2194 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2195 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2196 Lower = CI2->getValue();
2197 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2199 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2200 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2201 APInt NegOne = APInt::getAllOnesValue(Width);
2202 if (CI2->getValue().ult(Width))
2203 Upper = NegOne.lshr(CI2->getValue()) + 1;
2204 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2205 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2206 unsigned ShiftAmount = Width - 1;
2207 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2208 ShiftAmount = CI2->getValue().countTrailingZeros();
2209 Lower = CI2->getValue().lshr(ShiftAmount);
2210 Upper = CI2->getValue() + 1;
2211 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2212 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2213 APInt IntMin = APInt::getSignedMinValue(Width);
2214 APInt IntMax = APInt::getSignedMaxValue(Width);
2215 if (CI2->getValue().ult(Width)) {
2216 Lower = IntMin.ashr(CI2->getValue());
2217 Upper = IntMax.ashr(CI2->getValue()) + 1;
2219 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2220 unsigned ShiftAmount = Width - 1;
2221 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2222 ShiftAmount = CI2->getValue().countTrailingZeros();
2223 if (CI2->isNegative()) {
2224 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2225 Lower = CI2->getValue();
2226 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2228 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2229 Lower = CI2->getValue().ashr(ShiftAmount);
2230 Upper = CI2->getValue() + 1;
2232 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2233 // 'or x, CI2' produces [CI2, UINT_MAX].
2234 Lower = CI2->getValue();
2235 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2236 // 'and x, CI2' produces [0, CI2].
2237 Upper = CI2->getValue() + 1;
2239 if (Lower != Upper) {
2240 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2241 if (RHS_CR.contains(LHS_CR))
2242 return ConstantInt::getTrue(RHS->getContext());
2243 if (RHS_CR.inverse().contains(LHS_CR))
2244 return ConstantInt::getFalse(RHS->getContext());
2248 // Compare of cast, for example (zext X) != 0 -> X != 0
2249 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2250 Instruction *LI = cast<CastInst>(LHS);
2251 Value *SrcOp = LI->getOperand(0);
2252 Type *SrcTy = SrcOp->getType();
2253 Type *DstTy = LI->getType();
2255 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2256 // if the integer type is the same size as the pointer type.
2257 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2258 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2259 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2260 // Transfer the cast to the constant.
2261 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2262 ConstantExpr::getIntToPtr(RHSC, SrcTy),
2265 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2266 if (RI->getOperand(0)->getType() == SrcTy)
2267 // Compare without the cast.
2268 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2274 if (isa<ZExtInst>(LHS)) {
2275 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2277 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2278 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2279 // Compare X and Y. Note that signed predicates become unsigned.
2280 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2281 SrcOp, RI->getOperand(0), Q,
2285 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2286 // too. If not, then try to deduce the result of the comparison.
2287 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2288 // Compute the constant that would happen if we truncated to SrcTy then
2289 // reextended to DstTy.
2290 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2291 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2293 // If the re-extended constant didn't change then this is effectively
2294 // also a case of comparing two zero-extended values.
2295 if (RExt == CI && MaxRecurse)
2296 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2297 SrcOp, Trunc, Q, MaxRecurse-1))
2300 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2301 // there. Use this to work out the result of the comparison.
2304 default: llvm_unreachable("Unknown ICmp predicate!");
2306 case ICmpInst::ICMP_EQ:
2307 case ICmpInst::ICMP_UGT:
2308 case ICmpInst::ICMP_UGE:
2309 return ConstantInt::getFalse(CI->getContext());
2311 case ICmpInst::ICMP_NE:
2312 case ICmpInst::ICMP_ULT:
2313 case ICmpInst::ICMP_ULE:
2314 return ConstantInt::getTrue(CI->getContext());
2316 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2317 // is non-negative then LHS <s RHS.
2318 case ICmpInst::ICMP_SGT:
2319 case ICmpInst::ICMP_SGE:
2320 return CI->getValue().isNegative() ?
2321 ConstantInt::getTrue(CI->getContext()) :
2322 ConstantInt::getFalse(CI->getContext());
2324 case ICmpInst::ICMP_SLT:
2325 case ICmpInst::ICMP_SLE:
2326 return CI->getValue().isNegative() ?
2327 ConstantInt::getFalse(CI->getContext()) :
2328 ConstantInt::getTrue(CI->getContext());
2334 if (isa<SExtInst>(LHS)) {
2335 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2337 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2338 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2339 // Compare X and Y. Note that the predicate does not change.
2340 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2344 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2345 // too. If not, then try to deduce the result of the comparison.
2346 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2347 // Compute the constant that would happen if we truncated to SrcTy then
2348 // reextended to DstTy.
2349 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2350 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2352 // If the re-extended constant didn't change then this is effectively
2353 // also a case of comparing two sign-extended values.
2354 if (RExt == CI && MaxRecurse)
2355 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2358 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2359 // bits there. Use this to work out the result of the comparison.
2362 default: llvm_unreachable("Unknown ICmp predicate!");
2363 case ICmpInst::ICMP_EQ:
2364 return ConstantInt::getFalse(CI->getContext());
2365 case ICmpInst::ICMP_NE:
2366 return ConstantInt::getTrue(CI->getContext());
2368 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2370 case ICmpInst::ICMP_SGT:
2371 case ICmpInst::ICMP_SGE:
2372 return CI->getValue().isNegative() ?
2373 ConstantInt::getTrue(CI->getContext()) :
2374 ConstantInt::getFalse(CI->getContext());
2375 case ICmpInst::ICMP_SLT:
2376 case ICmpInst::ICMP_SLE:
2377 return CI->getValue().isNegative() ?
2378 ConstantInt::getFalse(CI->getContext()) :
2379 ConstantInt::getTrue(CI->getContext());
2381 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2383 case ICmpInst::ICMP_UGT:
2384 case ICmpInst::ICMP_UGE:
2385 // Comparison is true iff the LHS <s 0.
2387 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2388 Constant::getNullValue(SrcTy),
2392 case ICmpInst::ICMP_ULT:
2393 case ICmpInst::ICMP_ULE:
2394 // Comparison is true iff the LHS >=s 0.
2396 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2397 Constant::getNullValue(SrcTy),
2407 // If a bit is known to be zero for A and known to be one for B,
2408 // then A and B cannot be equal.
2409 if (ICmpInst::isEquality(Pred)) {
2410 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2411 uint32_t BitWidth = CI->getBitWidth();
2412 APInt LHSKnownZero(BitWidth, 0);
2413 APInt LHSKnownOne(BitWidth, 0);
2414 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL,
2415 0, Q.AT, Q.CxtI, Q.DT);
2416 APInt RHSKnownZero(BitWidth, 0);
2417 APInt RHSKnownOne(BitWidth, 0);
2418 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, Q.DL,
2419 0, Q.AT, Q.CxtI, Q.DT);
2420 if (((LHSKnownOne & RHSKnownZero) != 0) ||
2421 ((LHSKnownZero & RHSKnownOne) != 0))
2422 return (Pred == ICmpInst::ICMP_EQ)
2423 ? ConstantInt::getFalse(CI->getContext())
2424 : ConstantInt::getTrue(CI->getContext());
2428 // Special logic for binary operators.
2429 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2430 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2431 if (MaxRecurse && (LBO || RBO)) {
2432 // Analyze the case when either LHS or RHS is an add instruction.
2433 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2434 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2435 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2436 if (LBO && LBO->getOpcode() == Instruction::Add) {
2437 A = LBO->getOperand(0); B = LBO->getOperand(1);
2438 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2439 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2440 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2442 if (RBO && RBO->getOpcode() == Instruction::Add) {
2443 C = RBO->getOperand(0); D = RBO->getOperand(1);
2444 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2445 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2446 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2449 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2450 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2451 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2452 Constant::getNullValue(RHS->getType()),
2456 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2457 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2458 if (Value *V = SimplifyICmpInst(Pred,
2459 Constant::getNullValue(LHS->getType()),
2460 C == LHS ? D : C, Q, MaxRecurse-1))
2463 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2464 if (A && C && (A == C || A == D || B == C || B == D) &&
2465 NoLHSWrapProblem && NoRHSWrapProblem) {
2466 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2469 // C + B == C + D -> B == D
2472 } else if (A == D) {
2473 // D + B == C + D -> B == C
2476 } else if (B == C) {
2477 // A + C == C + D -> A == D
2482 // A + D == C + D -> A == C
2486 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2491 // 0 - (zext X) pred C
2492 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2493 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2494 if (RHSC->getValue().isStrictlyPositive()) {
2495 if (Pred == ICmpInst::ICMP_SLT)
2496 return ConstantInt::getTrue(RHSC->getContext());
2497 if (Pred == ICmpInst::ICMP_SGE)
2498 return ConstantInt::getFalse(RHSC->getContext());
2499 if (Pred == ICmpInst::ICMP_EQ)
2500 return ConstantInt::getFalse(RHSC->getContext());
2501 if (Pred == ICmpInst::ICMP_NE)
2502 return ConstantInt::getTrue(RHSC->getContext());
2504 if (RHSC->getValue().isNonNegative()) {
2505 if (Pred == ICmpInst::ICMP_SLE)
2506 return ConstantInt::getTrue(RHSC->getContext());
2507 if (Pred == ICmpInst::ICMP_SGT)
2508 return ConstantInt::getFalse(RHSC->getContext());
2513 // icmp pred (urem X, Y), Y
2514 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2515 bool KnownNonNegative, KnownNegative;
2519 case ICmpInst::ICMP_SGT:
2520 case ICmpInst::ICMP_SGE:
2521 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2522 0, Q.AT, Q.CxtI, Q.DT);
2523 if (!KnownNonNegative)
2526 case ICmpInst::ICMP_EQ:
2527 case ICmpInst::ICMP_UGT:
2528 case ICmpInst::ICMP_UGE:
2529 return getFalse(ITy);
2530 case ICmpInst::ICMP_SLT:
2531 case ICmpInst::ICMP_SLE:
2532 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2533 0, Q.AT, Q.CxtI, Q.DT);
2534 if (!KnownNonNegative)
2537 case ICmpInst::ICMP_NE:
2538 case ICmpInst::ICMP_ULT:
2539 case ICmpInst::ICMP_ULE:
2540 return getTrue(ITy);
2544 // icmp pred X, (urem Y, X)
2545 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2546 bool KnownNonNegative, KnownNegative;
2550 case ICmpInst::ICMP_SGT:
2551 case ICmpInst::ICMP_SGE:
2552 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2553 0, Q.AT, Q.CxtI, Q.DT);
2554 if (!KnownNonNegative)
2557 case ICmpInst::ICMP_NE:
2558 case ICmpInst::ICMP_UGT:
2559 case ICmpInst::ICMP_UGE:
2560 return getTrue(ITy);
2561 case ICmpInst::ICMP_SLT:
2562 case ICmpInst::ICMP_SLE:
2563 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2564 0, Q.AT, Q.CxtI, Q.DT);
2565 if (!KnownNonNegative)
2568 case ICmpInst::ICMP_EQ:
2569 case ICmpInst::ICMP_ULT:
2570 case ICmpInst::ICMP_ULE:
2571 return getFalse(ITy);
2576 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2577 // icmp pred (X /u Y), X
2578 if (Pred == ICmpInst::ICMP_UGT)
2579 return getFalse(ITy);
2580 if (Pred == ICmpInst::ICMP_ULE)
2581 return getTrue(ITy);
2588 // where CI2 is a power of 2 and CI isn't
2589 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2590 const APInt *CI2Val, *CIVal = &CI->getValue();
2591 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2592 CI2Val->isPowerOf2()) {
2593 if (!CIVal->isPowerOf2()) {
2594 // CI2 << X can equal zero in some circumstances,
2595 // this simplification is unsafe if CI is zero.
2597 // We know it is safe if:
2598 // - The shift is nsw, we can't shift out the one bit.
2599 // - The shift is nuw, we can't shift out the one bit.
2602 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2603 *CI2Val == 1 || !CI->isZero()) {
2604 if (Pred == ICmpInst::ICMP_EQ)
2605 return ConstantInt::getFalse(RHS->getContext());
2606 if (Pred == ICmpInst::ICMP_NE)
2607 return ConstantInt::getTrue(RHS->getContext());
2610 if (CIVal->isSignBit() && *CI2Val == 1) {
2611 if (Pred == ICmpInst::ICMP_UGT)
2612 return ConstantInt::getFalse(RHS->getContext());
2613 if (Pred == ICmpInst::ICMP_ULE)
2614 return ConstantInt::getTrue(RHS->getContext());
2619 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2620 LBO->getOperand(1) == RBO->getOperand(1)) {
2621 switch (LBO->getOpcode()) {
2623 case Instruction::UDiv:
2624 case Instruction::LShr:
2625 if (ICmpInst::isSigned(Pred))
2628 case Instruction::SDiv:
2629 case Instruction::AShr:
2630 if (!LBO->isExact() || !RBO->isExact())
2632 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2633 RBO->getOperand(0), Q, MaxRecurse-1))
2636 case Instruction::Shl: {
2637 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2638 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2641 if (!NSW && ICmpInst::isSigned(Pred))
2643 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2644 RBO->getOperand(0), Q, MaxRecurse-1))
2651 // Simplify comparisons involving max/min.
2653 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2654 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2656 // Signed variants on "max(a,b)>=a -> true".
2657 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2658 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2659 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2660 // We analyze this as smax(A, B) pred A.
2662 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2663 (A == LHS || B == LHS)) {
2664 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2665 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2666 // We analyze this as smax(A, B) swapped-pred A.
2667 P = CmpInst::getSwappedPredicate(Pred);
2668 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2669 (A == RHS || B == RHS)) {
2670 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2671 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2672 // We analyze this as smax(-A, -B) swapped-pred -A.
2673 // Note that we do not need to actually form -A or -B thanks to EqP.
2674 P = CmpInst::getSwappedPredicate(Pred);
2675 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2676 (A == LHS || B == LHS)) {
2677 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2678 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2679 // We analyze this as smax(-A, -B) pred -A.
2680 // Note that we do not need to actually form -A or -B thanks to EqP.
2683 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2684 // Cases correspond to "max(A, B) p A".
2688 case CmpInst::ICMP_EQ:
2689 case CmpInst::ICMP_SLE:
2690 // Equivalent to "A EqP B". This may be the same as the condition tested
2691 // in the max/min; if so, we can just return that.
2692 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2694 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2696 // Otherwise, see if "A EqP B" simplifies.
2698 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2701 case CmpInst::ICMP_NE:
2702 case CmpInst::ICMP_SGT: {
2703 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2704 // Equivalent to "A InvEqP B". This may be the same as the condition
2705 // tested in the max/min; if so, we can just return that.
2706 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2708 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2710 // Otherwise, see if "A InvEqP B" simplifies.
2712 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2716 case CmpInst::ICMP_SGE:
2718 return getTrue(ITy);
2719 case CmpInst::ICMP_SLT:
2721 return getFalse(ITy);
2725 // Unsigned variants on "max(a,b)>=a -> true".
2726 P = CmpInst::BAD_ICMP_PREDICATE;
2727 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2728 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2729 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2730 // We analyze this as umax(A, B) pred A.
2732 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2733 (A == LHS || B == LHS)) {
2734 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2735 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2736 // We analyze this as umax(A, B) swapped-pred A.
2737 P = CmpInst::getSwappedPredicate(Pred);
2738 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2739 (A == RHS || B == RHS)) {
2740 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2741 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2742 // We analyze this as umax(-A, -B) swapped-pred -A.
2743 // Note that we do not need to actually form -A or -B thanks to EqP.
2744 P = CmpInst::getSwappedPredicate(Pred);
2745 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2746 (A == LHS || B == LHS)) {
2747 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2748 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2749 // We analyze this as umax(-A, -B) pred -A.
2750 // Note that we do not need to actually form -A or -B thanks to EqP.
2753 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2754 // Cases correspond to "max(A, B) p A".
2758 case CmpInst::ICMP_EQ:
2759 case CmpInst::ICMP_ULE:
2760 // Equivalent to "A EqP B". This may be the same as the condition tested
2761 // in the max/min; if so, we can just return that.
2762 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2764 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2766 // Otherwise, see if "A EqP B" simplifies.
2768 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2771 case CmpInst::ICMP_NE:
2772 case CmpInst::ICMP_UGT: {
2773 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2774 // Equivalent to "A InvEqP B". This may be the same as the condition
2775 // tested in the max/min; if so, we can just return that.
2776 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2778 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2780 // Otherwise, see if "A InvEqP B" simplifies.
2782 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2786 case CmpInst::ICMP_UGE:
2788 return getTrue(ITy);
2789 case CmpInst::ICMP_ULT:
2791 return getFalse(ITy);
2795 // Variants on "max(x,y) >= min(x,z)".
2797 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2798 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2799 (A == C || A == D || B == C || B == D)) {
2800 // max(x, ?) pred min(x, ?).
2801 if (Pred == CmpInst::ICMP_SGE)
2803 return getTrue(ITy);
2804 if (Pred == CmpInst::ICMP_SLT)
2806 return getFalse(ITy);
2807 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2808 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2809 (A == C || A == D || B == C || B == D)) {
2810 // min(x, ?) pred max(x, ?).
2811 if (Pred == CmpInst::ICMP_SLE)
2813 return getTrue(ITy);
2814 if (Pred == CmpInst::ICMP_SGT)
2816 return getFalse(ITy);
2817 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2818 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2819 (A == C || A == D || B == C || B == D)) {
2820 // max(x, ?) pred min(x, ?).
2821 if (Pred == CmpInst::ICMP_UGE)
2823 return getTrue(ITy);
2824 if (Pred == CmpInst::ICMP_ULT)
2826 return getFalse(ITy);
2827 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2828 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2829 (A == C || A == D || B == C || B == D)) {
2830 // min(x, ?) pred max(x, ?).
2831 if (Pred == CmpInst::ICMP_ULE)
2833 return getTrue(ITy);
2834 if (Pred == CmpInst::ICMP_UGT)
2836 return getFalse(ITy);
2839 // Simplify comparisons of related pointers using a powerful, recursive
2840 // GEP-walk when we have target data available..
2841 if (LHS->getType()->isPointerTy())
2842 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
2845 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2846 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2847 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2848 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2849 (ICmpInst::isEquality(Pred) ||
2850 (GLHS->isInBounds() && GRHS->isInBounds() &&
2851 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2852 // The bases are equal and the indices are constant. Build a constant
2853 // expression GEP with the same indices and a null base pointer to see
2854 // what constant folding can make out of it.
2855 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2856 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2857 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2859 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2860 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2861 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2866 // If the comparison is with the result of a select instruction, check whether
2867 // comparing with either branch of the select always yields the same value.
2868 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2869 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2872 // If the comparison is with the result of a phi instruction, check whether
2873 // doing the compare with each incoming phi value yields a common result.
2874 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2875 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2881 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2882 const DataLayout *DL,
2883 const TargetLibraryInfo *TLI,
2884 const DominatorTree *DT,
2885 AssumptionTracker *AT,
2886 Instruction *CxtI) {
2887 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
2891 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2892 /// fold the result. If not, this returns null.
2893 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2894 const Query &Q, unsigned MaxRecurse) {
2895 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2896 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2898 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2899 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2900 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2902 // If we have a constant, make sure it is on the RHS.
2903 std::swap(LHS, RHS);
2904 Pred = CmpInst::getSwappedPredicate(Pred);
2907 // Fold trivial predicates.
2908 if (Pred == FCmpInst::FCMP_FALSE)
2909 return ConstantInt::get(GetCompareTy(LHS), 0);
2910 if (Pred == FCmpInst::FCMP_TRUE)
2911 return ConstantInt::get(GetCompareTy(LHS), 1);
2913 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2914 return UndefValue::get(GetCompareTy(LHS));
2916 // fcmp x,x -> true/false. Not all compares are foldable.
2918 if (CmpInst::isTrueWhenEqual(Pred))
2919 return ConstantInt::get(GetCompareTy(LHS), 1);
2920 if (CmpInst::isFalseWhenEqual(Pred))
2921 return ConstantInt::get(GetCompareTy(LHS), 0);
2924 // Handle fcmp with constant RHS
2925 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2926 // If the constant is a nan, see if we can fold the comparison based on it.
2927 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2928 if (CFP->getValueAPF().isNaN()) {
2929 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2930 return ConstantInt::getFalse(CFP->getContext());
2931 assert(FCmpInst::isUnordered(Pred) &&
2932 "Comparison must be either ordered or unordered!");
2933 // True if unordered.
2934 return ConstantInt::getTrue(CFP->getContext());
2936 // Check whether the constant is an infinity.
2937 if (CFP->getValueAPF().isInfinity()) {
2938 if (CFP->getValueAPF().isNegative()) {
2940 case FCmpInst::FCMP_OLT:
2941 // No value is ordered and less than negative infinity.
2942 return ConstantInt::getFalse(CFP->getContext());
2943 case FCmpInst::FCMP_UGE:
2944 // All values are unordered with or at least negative infinity.
2945 return ConstantInt::getTrue(CFP->getContext());
2951 case FCmpInst::FCMP_OGT:
2952 // No value is ordered and greater than infinity.
2953 return ConstantInt::getFalse(CFP->getContext());
2954 case FCmpInst::FCMP_ULE:
2955 // All values are unordered with and at most infinity.
2956 return ConstantInt::getTrue(CFP->getContext());
2965 // If the comparison is with the result of a select instruction, check whether
2966 // comparing with either branch of the select always yields the same value.
2967 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2968 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2971 // If the comparison is with the result of a phi instruction, check whether
2972 // doing the compare with each incoming phi value yields a common result.
2973 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2974 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2980 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2981 const DataLayout *DL,
2982 const TargetLibraryInfo *TLI,
2983 const DominatorTree *DT,
2984 AssumptionTracker *AT,
2985 const Instruction *CxtI) {
2986 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
2990 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2991 /// the result. If not, this returns null.
2992 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2993 Value *FalseVal, const Query &Q,
2994 unsigned MaxRecurse) {
2995 // select true, X, Y -> X
2996 // select false, X, Y -> Y
2997 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2998 if (CB->isAllOnesValue())
3000 if (CB->isNullValue())
3004 // select C, X, X -> X
3005 if (TrueVal == FalseVal)
3008 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3009 if (isa<Constant>(TrueVal))
3013 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3015 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3021 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
3022 const DataLayout *DL,
3023 const TargetLibraryInfo *TLI,
3024 const DominatorTree *DT,
3025 AssumptionTracker *AT,
3026 const Instruction *CxtI) {
3027 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
3028 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
3031 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
3032 /// fold the result. If not, this returns null.
3033 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
3034 // The type of the GEP pointer operand.
3035 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
3036 unsigned AS = PtrTy->getAddressSpace();
3038 // getelementptr P -> P.
3039 if (Ops.size() == 1)
3042 // Compute the (pointer) type returned by the GEP instruction.
3043 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
3044 Type *GEPTy = PointerType::get(LastType, AS);
3045 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3046 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3048 if (isa<UndefValue>(Ops[0]))
3049 return UndefValue::get(GEPTy);
3051 if (Ops.size() == 2) {
3052 // getelementptr P, 0 -> P.
3053 if (match(Ops[1], m_Zero()))
3056 Type *Ty = PtrTy->getElementType();
3057 if (Q.DL && Ty->isSized()) {
3060 uint64_t TyAllocSize = Q.DL->getTypeAllocSize(Ty);
3061 // getelementptr P, N -> P if P points to a type of zero size.
3062 if (TyAllocSize == 0)
3065 // The following transforms are only safe if the ptrtoint cast
3066 // doesn't truncate the pointers.
3067 if (Ops[1]->getType()->getScalarSizeInBits() ==
3068 Q.DL->getPointerSizeInBits(AS)) {
3069 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3070 if (match(P, m_Zero()))
3071 return Constant::getNullValue(GEPTy);
3073 if (match(P, m_PtrToInt(m_Value(Temp))))
3074 if (Temp->getType() == GEPTy)
3079 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3080 if (TyAllocSize == 1 &&
3081 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3082 if (Value *R = PtrToIntOrZero(P))
3085 // getelementptr V, (ashr (sub P, V), C) -> Q
3086 // if P points to a type of size 1 << C.
3088 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3089 m_ConstantInt(C))) &&
3090 TyAllocSize == 1ULL << C)
3091 if (Value *R = PtrToIntOrZero(P))
3094 // getelementptr V, (sdiv (sub P, V), C) -> Q
3095 // if P points to a type of size C.
3097 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3098 m_SpecificInt(TyAllocSize))))
3099 if (Value *R = PtrToIntOrZero(P))
3105 // Check to see if this is constant foldable.
3106 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3107 if (!isa<Constant>(Ops[i]))
3110 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
3113 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
3114 const TargetLibraryInfo *TLI,
3115 const DominatorTree *DT, AssumptionTracker *AT,
3116 const Instruction *CxtI) {
3117 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
3120 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
3121 /// can fold the result. If not, this returns null.
3122 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3123 ArrayRef<unsigned> Idxs, const Query &Q,
3125 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3126 if (Constant *CVal = dyn_cast<Constant>(Val))
3127 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3129 // insertvalue x, undef, n -> x
3130 if (match(Val, m_Undef()))
3133 // insertvalue x, (extractvalue y, n), n
3134 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3135 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3136 EV->getIndices() == Idxs) {
3137 // insertvalue undef, (extractvalue y, n), n -> y
3138 if (match(Agg, m_Undef()))
3139 return EV->getAggregateOperand();
3141 // insertvalue y, (extractvalue y, n), n -> y
3142 if (Agg == EV->getAggregateOperand())
3149 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3150 ArrayRef<unsigned> Idxs,
3151 const DataLayout *DL,
3152 const TargetLibraryInfo *TLI,
3153 const DominatorTree *DT,
3154 AssumptionTracker *AT,
3155 const Instruction *CxtI) {
3156 return ::SimplifyInsertValueInst(Agg, Val, Idxs,
3157 Query (DL, TLI, DT, AT, CxtI),
3161 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
3162 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3163 // If all of the PHI's incoming values are the same then replace the PHI node
3164 // with the common value.
3165 Value *CommonValue = nullptr;
3166 bool HasUndefInput = false;
3167 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3168 Value *Incoming = PN->getIncomingValue(i);
3169 // If the incoming value is the phi node itself, it can safely be skipped.
3170 if (Incoming == PN) continue;
3171 if (isa<UndefValue>(Incoming)) {
3172 // Remember that we saw an undef value, but otherwise ignore them.
3173 HasUndefInput = true;
3176 if (CommonValue && Incoming != CommonValue)
3177 return nullptr; // Not the same, bail out.
3178 CommonValue = Incoming;
3181 // If CommonValue is null then all of the incoming values were either undef or
3182 // equal to the phi node itself.
3184 return UndefValue::get(PN->getType());
3186 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3187 // instruction, we cannot return X as the result of the PHI node unless it
3188 // dominates the PHI block.
3190 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3195 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3196 if (Constant *C = dyn_cast<Constant>(Op))
3197 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
3202 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
3203 const TargetLibraryInfo *TLI,
3204 const DominatorTree *DT,
3205 AssumptionTracker *AT,
3206 const Instruction *CxtI) {
3207 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT, AT, CxtI),
3211 //=== Helper functions for higher up the class hierarchy.
3213 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
3214 /// fold the result. If not, this returns null.
3215 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3216 const Query &Q, unsigned MaxRecurse) {
3218 case Instruction::Add:
3219 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3221 case Instruction::FAdd:
3222 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3224 case Instruction::Sub:
3225 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3227 case Instruction::FSub:
3228 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3230 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3231 case Instruction::FMul:
3232 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3233 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3234 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3235 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
3236 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3237 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3238 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
3239 case Instruction::Shl:
3240 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3242 case Instruction::LShr:
3243 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3244 case Instruction::AShr:
3245 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3246 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3247 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3248 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3250 if (Constant *CLHS = dyn_cast<Constant>(LHS))
3251 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
3252 Constant *COps[] = {CLHS, CRHS};
3253 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
3257 // If the operation is associative, try some generic simplifications.
3258 if (Instruction::isAssociative(Opcode))
3259 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3262 // If the operation is with the result of a select instruction check whether
3263 // operating on either branch of the select always yields the same value.
3264 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3265 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3268 // If the operation is with the result of a phi instruction, check whether
3269 // operating on all incoming values of the phi always yields the same value.
3270 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3271 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3278 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3279 const DataLayout *DL, const TargetLibraryInfo *TLI,
3280 const DominatorTree *DT, AssumptionTracker *AT,
3281 const Instruction *CxtI) {
3282 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3286 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
3287 /// fold the result.
3288 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3289 const Query &Q, unsigned MaxRecurse) {
3290 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3291 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3292 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3295 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3296 const DataLayout *DL, const TargetLibraryInfo *TLI,
3297 const DominatorTree *DT, AssumptionTracker *AT,
3298 const Instruction *CxtI) {
3299 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3303 static bool IsIdempotent(Intrinsic::ID ID) {
3305 default: return false;
3307 // Unary idempotent: f(f(x)) = f(x)
3308 case Intrinsic::fabs:
3309 case Intrinsic::floor:
3310 case Intrinsic::ceil:
3311 case Intrinsic::trunc:
3312 case Intrinsic::rint:
3313 case Intrinsic::nearbyint:
3314 case Intrinsic::round:
3319 template <typename IterTy>
3320 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
3321 const Query &Q, unsigned MaxRecurse) {
3322 // Perform idempotent optimizations
3323 if (!IsIdempotent(IID))
3327 if (std::distance(ArgBegin, ArgEnd) == 1)
3328 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3329 if (II->getIntrinsicID() == IID)
3335 template <typename IterTy>
3336 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
3337 const Query &Q, unsigned MaxRecurse) {
3338 Type *Ty = V->getType();
3339 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3340 Ty = PTy->getElementType();
3341 FunctionType *FTy = cast<FunctionType>(Ty);
3343 // call undef -> undef
3344 if (isa<UndefValue>(V))
3345 return UndefValue::get(FTy->getReturnType());
3347 Function *F = dyn_cast<Function>(V);
3351 if (unsigned IID = F->getIntrinsicID())
3353 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3356 if (!canConstantFoldCallTo(F))
3359 SmallVector<Constant *, 4> ConstantArgs;
3360 ConstantArgs.reserve(ArgEnd - ArgBegin);
3361 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3362 Constant *C = dyn_cast<Constant>(*I);
3365 ConstantArgs.push_back(C);
3368 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
3371 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
3372 User::op_iterator ArgEnd, const DataLayout *DL,
3373 const TargetLibraryInfo *TLI,
3374 const DominatorTree *DT, AssumptionTracker *AT,
3375 const Instruction *CxtI) {
3376 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AT, CxtI),
3380 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
3381 const DataLayout *DL, const TargetLibraryInfo *TLI,
3382 const DominatorTree *DT, AssumptionTracker *AT,
3383 const Instruction *CxtI) {
3384 return ::SimplifyCall(V, Args.begin(), Args.end(),
3385 Query(DL, TLI, DT, AT, CxtI), RecursionLimit);
3388 /// SimplifyInstruction - See if we can compute a simplified version of this
3389 /// instruction. If not, this returns null.
3390 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
3391 const TargetLibraryInfo *TLI,
3392 const DominatorTree *DT,
3393 AssumptionTracker *AT) {
3396 switch (I->getOpcode()) {
3398 Result = ConstantFoldInstruction(I, DL, TLI);
3400 case Instruction::FAdd:
3401 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3402 I->getFastMathFlags(), DL, TLI, DT, AT, I);
3404 case Instruction::Add:
3405 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3406 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3407 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3408 DL, TLI, DT, AT, I);
3410 case Instruction::FSub:
3411 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3412 I->getFastMathFlags(), DL, TLI, DT, AT, I);
3414 case Instruction::Sub:
3415 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3416 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3417 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3418 DL, TLI, DT, AT, I);
3420 case Instruction::FMul:
3421 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3422 I->getFastMathFlags(), DL, TLI, DT, AT, I);
3424 case Instruction::Mul:
3425 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1),
3426 DL, TLI, DT, AT, I);
3428 case Instruction::SDiv:
3429 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1),
3430 DL, TLI, DT, AT, I);
3432 case Instruction::UDiv:
3433 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1),
3434 DL, TLI, DT, AT, I);
3436 case Instruction::FDiv:
3437 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
3438 DL, TLI, DT, AT, I);
3440 case Instruction::SRem:
3441 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1),
3442 DL, TLI, DT, AT, I);
3444 case Instruction::URem:
3445 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1),
3446 DL, TLI, DT, AT, I);
3448 case Instruction::FRem:
3449 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
3450 DL, TLI, DT, AT, I);
3452 case Instruction::Shl:
3453 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3454 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3455 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3456 DL, TLI, DT, AT, I);
3458 case Instruction::LShr:
3459 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3460 cast<BinaryOperator>(I)->isExact(),
3461 DL, TLI, DT, AT, I);
3463 case Instruction::AShr:
3464 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3465 cast<BinaryOperator>(I)->isExact(),
3466 DL, TLI, DT, AT, I);
3468 case Instruction::And:
3469 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1),
3470 DL, TLI, DT, AT, I);
3472 case Instruction::Or:
3473 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3476 case Instruction::Xor:
3477 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1),
3478 DL, TLI, DT, AT, I);
3480 case Instruction::ICmp:
3481 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
3482 I->getOperand(0), I->getOperand(1),
3483 DL, TLI, DT, AT, I);
3485 case Instruction::FCmp:
3486 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
3487 I->getOperand(0), I->getOperand(1),
3488 DL, TLI, DT, AT, I);
3490 case Instruction::Select:
3491 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
3492 I->getOperand(2), DL, TLI, DT, AT, I);
3494 case Instruction::GetElementPtr: {
3495 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
3496 Result = SimplifyGEPInst(Ops, DL, TLI, DT, AT, I);
3499 case Instruction::InsertValue: {
3500 InsertValueInst *IV = cast<InsertValueInst>(I);
3501 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3502 IV->getInsertedValueOperand(),
3503 IV->getIndices(), DL, TLI, DT, AT, I);
3506 case Instruction::PHI:
3507 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT, AT, I));
3509 case Instruction::Call: {
3510 CallSite CS(cast<CallInst>(I));
3511 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3512 DL, TLI, DT, AT, I);
3515 case Instruction::Trunc:
3516 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT,
3521 /// If called on unreachable code, the above logic may report that the
3522 /// instruction simplified to itself. Make life easier for users by
3523 /// detecting that case here, returning a safe value instead.
3524 return Result == I ? UndefValue::get(I->getType()) : Result;
3527 /// \brief Implementation of recursive simplification through an instructions
3530 /// This is the common implementation of the recursive simplification routines.
3531 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3532 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3533 /// instructions to process and attempt to simplify it using
3534 /// InstructionSimplify.
3536 /// This routine returns 'true' only when *it* simplifies something. The passed
3537 /// in simplified value does not count toward this.
3538 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
3539 const DataLayout *DL,
3540 const TargetLibraryInfo *TLI,
3541 const DominatorTree *DT,
3542 AssumptionTracker *AT) {
3543 bool Simplified = false;
3544 SmallSetVector<Instruction *, 8> Worklist;
3546 // If we have an explicit value to collapse to, do that round of the
3547 // simplification loop by hand initially.
3549 for (User *U : I->users())
3551 Worklist.insert(cast<Instruction>(U));
3553 // Replace the instruction with its simplified value.
3554 I->replaceAllUsesWith(SimpleV);
3556 // Gracefully handle edge cases where the instruction is not wired into any
3559 I->eraseFromParent();
3564 // Note that we must test the size on each iteration, the worklist can grow.
3565 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3568 // See if this instruction simplifies.
3569 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AT);
3575 // Stash away all the uses of the old instruction so we can check them for
3576 // recursive simplifications after a RAUW. This is cheaper than checking all
3577 // uses of To on the recursive step in most cases.
3578 for (User *U : I->users())
3579 Worklist.insert(cast<Instruction>(U));
3581 // Replace the instruction with its simplified value.
3582 I->replaceAllUsesWith(SimpleV);
3584 // Gracefully handle edge cases where the instruction is not wired into any
3587 I->eraseFromParent();
3592 bool llvm::recursivelySimplifyInstruction(Instruction *I,
3593 const DataLayout *DL,
3594 const TargetLibraryInfo *TLI,
3595 const DominatorTree *DT,
3596 AssumptionTracker *AT) {
3597 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT, AT);
3600 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
3601 const DataLayout *DL,
3602 const TargetLibraryInfo *TLI,
3603 const DominatorTree *DT,
3604 AssumptionTracker *AT) {
3605 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3606 assert(SimpleV && "Must provide a simplified value.");
3607 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT, AT);