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 #define DEBUG_TYPE "instsimplify"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Support/ConstantRange.h"
28 #include "llvm/Support/PatternMatch.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Target/TargetData.h"
32 using namespace llvm::PatternMatch;
34 enum { RecursionLimit = 3 };
36 STATISTIC(NumExpand, "Number of expansions");
37 STATISTIC(NumFactor , "Number of factorizations");
38 STATISTIC(NumReassoc, "Number of reassociations");
40 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41 const DominatorTree *, unsigned);
42 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
43 const DominatorTree *, unsigned);
44 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
45 const DominatorTree *, unsigned);
46 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
47 const DominatorTree *, unsigned);
48 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
49 const DominatorTree *, unsigned);
51 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
52 /// a vector with every element false, as appropriate for the type.
53 static Constant *getFalse(Type *Ty) {
54 assert((Ty->isIntegerTy(1) ||
56 cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
57 "Expected i1 type or a vector of i1!");
58 return Constant::getNullValue(Ty);
61 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
62 /// a vector with every element true, as appropriate for the type.
63 static Constant *getTrue(Type *Ty) {
64 assert((Ty->isIntegerTy(1) ||
66 cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
67 "Expected i1 type or a vector of i1!");
68 return Constant::getAllOnesValue(Ty);
71 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
72 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
73 Instruction *I = dyn_cast<Instruction>(V);
75 // Arguments and constants dominate all instructions.
78 // If we have a DominatorTree then do a precise test.
80 return DT->dominates(I, P);
82 // Otherwise, if the instruction is in the entry block, and is not an invoke,
83 // then it obviously dominates all phi nodes.
84 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
91 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
92 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
93 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
94 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
95 /// Returns the simplified value, or null if no simplification was performed.
96 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
97 unsigned OpcToExpand, const TargetData *TD,
98 const DominatorTree *DT, unsigned MaxRecurse) {
99 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
100 // Recursion is always used, so bail out at once if we already hit the limit.
104 // Check whether the expression has the form "(A op' B) op C".
105 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
106 if (Op0->getOpcode() == OpcodeToExpand) {
107 // It does! Try turning it into "(A op C) op' (B op C)".
108 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
109 // Do "A op C" and "B op C" both simplify?
110 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
111 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
112 // They do! Return "L op' R" if it simplifies or is already available.
113 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
114 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
115 && L == B && R == A)) {
119 // Otherwise return "L op' R" if it simplifies.
120 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
128 // Check whether the expression has the form "A op (B op' C)".
129 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
130 if (Op1->getOpcode() == OpcodeToExpand) {
131 // It does! Try turning it into "(A op B) op' (A op C)".
132 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
133 // Do "A op B" and "A op C" both simplify?
134 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
135 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
136 // They do! Return "L op' R" if it simplifies or is already available.
137 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
138 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
139 && L == C && R == B)) {
143 // Otherwise return "L op' R" if it simplifies.
144 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
155 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
156 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
157 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
158 /// Returns the simplified value, or null if no simplification was performed.
159 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
160 unsigned OpcToExtract, const TargetData *TD,
161 const DominatorTree *DT, unsigned MaxRecurse) {
162 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
163 // Recursion is always used, so bail out at once if we already hit the limit.
167 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
168 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
170 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
171 !Op1 || Op1->getOpcode() != OpcodeToExtract)
174 // The expression has the form "(A op' B) op (C op' D)".
175 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
176 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
178 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
179 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
180 // commutative case, "(A op' B) op (C op' A)"?
181 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
182 Value *DD = A == C ? D : C;
183 // Form "A op' (B op DD)" if it simplifies completely.
184 // Does "B op DD" simplify?
185 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
186 // It does! Return "A op' V" if it simplifies or is already available.
187 // If V equals B then "A op' V" is just the LHS. If V equals DD then
188 // "A op' V" is just the RHS.
189 if (V == B || V == DD) {
191 return V == B ? LHS : RHS;
193 // Otherwise return "A op' V" if it simplifies.
194 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
201 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
202 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
203 // commutative case, "(A op' B) op (B op' D)"?
204 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
205 Value *CC = B == D ? C : D;
206 // Form "(A op CC) op' B" if it simplifies completely..
207 // Does "A op CC" simplify?
208 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
209 // It does! Return "V op' B" if it simplifies or is already available.
210 // If V equals A then "V op' B" is just the LHS. If V equals CC then
211 // "V op' B" is just the RHS.
212 if (V == A || V == CC) {
214 return V == A ? LHS : RHS;
216 // Otherwise return "V op' B" if it simplifies.
217 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
227 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
228 /// operations. Returns the simpler value, or null if none was found.
229 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
230 const TargetData *TD,
231 const DominatorTree *DT,
232 unsigned MaxRecurse) {
233 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
234 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
236 // Recursion is always used, so bail out at once if we already hit the limit.
240 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
241 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
243 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
244 if (Op0 && Op0->getOpcode() == Opcode) {
245 Value *A = Op0->getOperand(0);
246 Value *B = Op0->getOperand(1);
249 // Does "B op C" simplify?
250 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
251 // It does! Return "A op V" if it simplifies or is already available.
252 // If V equals B then "A op V" is just the LHS.
253 if (V == B) return LHS;
254 // Otherwise return "A op V" if it simplifies.
255 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
262 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
263 if (Op1 && Op1->getOpcode() == Opcode) {
265 Value *B = Op1->getOperand(0);
266 Value *C = Op1->getOperand(1);
268 // Does "A op B" simplify?
269 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
270 // It does! Return "V op C" if it simplifies or is already available.
271 // If V equals B then "V op C" is just the RHS.
272 if (V == B) return RHS;
273 // Otherwise return "V op C" if it simplifies.
274 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
281 // The remaining transforms require commutativity as well as associativity.
282 if (!Instruction::isCommutative(Opcode))
285 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
286 if (Op0 && Op0->getOpcode() == Opcode) {
287 Value *A = Op0->getOperand(0);
288 Value *B = Op0->getOperand(1);
291 // Does "C op A" simplify?
292 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
293 // It does! Return "V op B" if it simplifies or is already available.
294 // If V equals A then "V op B" is just the LHS.
295 if (V == A) return LHS;
296 // Otherwise return "V op B" if it simplifies.
297 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
304 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
305 if (Op1 && Op1->getOpcode() == Opcode) {
307 Value *B = Op1->getOperand(0);
308 Value *C = Op1->getOperand(1);
310 // Does "C op A" simplify?
311 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
312 // It does! Return "B op V" if it simplifies or is already available.
313 // If V equals C then "B op V" is just the RHS.
314 if (V == C) return RHS;
315 // Otherwise return "B op V" if it simplifies.
316 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
326 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
327 /// instruction as an operand, try to simplify the binop by seeing whether
328 /// evaluating it on both branches of the select results in the same value.
329 /// Returns the common value if so, otherwise returns null.
330 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
331 const TargetData *TD,
332 const DominatorTree *DT,
333 unsigned MaxRecurse) {
334 // Recursion is always used, so bail out at once if we already hit the limit.
339 if (isa<SelectInst>(LHS)) {
340 SI = cast<SelectInst>(LHS);
342 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
343 SI = cast<SelectInst>(RHS);
346 // Evaluate the BinOp on the true and false branches of the select.
350 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
351 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
353 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
354 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
357 // If they simplified to the same value, then return the common value.
358 // If they both failed to simplify then return null.
362 // If one branch simplified to undef, return the other one.
363 if (TV && isa<UndefValue>(TV))
365 if (FV && isa<UndefValue>(FV))
368 // If applying the operation did not change the true and false select values,
369 // then the result of the binop is the select itself.
370 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
373 // If one branch simplified and the other did not, and the simplified
374 // value is equal to the unsimplified one, return the simplified value.
375 // For example, select (cond, X, X & Z) & Z -> X & Z.
376 if ((FV && !TV) || (TV && !FV)) {
377 // Check that the simplified value has the form "X op Y" where "op" is the
378 // same as the original operation.
379 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
380 if (Simplified && Simplified->getOpcode() == Opcode) {
381 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
382 // We already know that "op" is the same as for the simplified value. See
383 // if the operands match too. If so, return the simplified value.
384 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
385 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
386 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
387 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
388 Simplified->getOperand(1) == UnsimplifiedRHS)
390 if (Simplified->isCommutative() &&
391 Simplified->getOperand(1) == UnsimplifiedLHS &&
392 Simplified->getOperand(0) == UnsimplifiedRHS)
400 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
401 /// try to simplify the comparison by seeing whether both branches of the select
402 /// result in the same value. Returns the common value if so, otherwise returns
404 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
405 Value *RHS, const TargetData *TD,
406 const DominatorTree *DT,
407 unsigned MaxRecurse) {
408 // Recursion is always used, so bail out at once if we already hit the limit.
412 // Make sure the select is on the LHS.
413 if (!isa<SelectInst>(LHS)) {
415 Pred = CmpInst::getSwappedPredicate(Pred);
417 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
418 SelectInst *SI = cast<SelectInst>(LHS);
419 Value *Cond = SI->getCondition();
420 Value *TV = SI->getTrueValue();
421 Value *FV = SI->getFalseValue();
423 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
424 // Does "cmp TV, RHS" simplify?
425 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, DT, MaxRecurse);
427 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
428 // condition itself then we can replace it with 'true'.
429 if (match(Cond, m_ICmp(Pred, m_Specific(TV), m_Specific(RHS))))
430 TCmp = getTrue(Cond->getType());
435 // Does "cmp FV, RHS" simplify?
436 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, DT, MaxRecurse);
438 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
439 // condition itself then we can replace it with 'false'.
440 if (match(Cond, m_ICmp(Pred, m_Specific(FV), m_Specific(RHS))))
441 FCmp = getFalse(Cond->getType());
446 // If both sides simplified to the same value, then use it as the result of
447 // the original comparison.
450 // If the false value simplified to false, then the result of the compare
451 // is equal to "Cond && TCmp". This also catches the case when the false
452 // value simplified to false and the true value to true, returning "Cond".
453 if (match(FCmp, m_Zero()))
454 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
456 // If the true value simplified to true, then the result of the compare
457 // is equal to "Cond || FCmp".
458 if (match(TCmp, m_One()))
459 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
461 // Finally, if the false value simplified to true and the true value to
462 // false, then the result of the compare is equal to "!Cond".
463 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
465 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
472 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
473 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
474 /// it on the incoming phi values yields the same result for every value. If so
475 /// returns the common value, otherwise returns null.
476 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
477 const TargetData *TD, const DominatorTree *DT,
478 unsigned MaxRecurse) {
479 // Recursion is always used, so bail out at once if we already hit the limit.
484 if (isa<PHINode>(LHS)) {
485 PI = cast<PHINode>(LHS);
486 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
487 if (!ValueDominatesPHI(RHS, PI, DT))
490 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
491 PI = cast<PHINode>(RHS);
492 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
493 if (!ValueDominatesPHI(LHS, PI, DT))
497 // Evaluate the BinOp on the incoming phi values.
498 Value *CommonValue = 0;
499 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
500 Value *Incoming = PI->getIncomingValue(i);
501 // If the incoming value is the phi node itself, it can safely be skipped.
502 if (Incoming == PI) continue;
503 Value *V = PI == LHS ?
504 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
505 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
506 // If the operation failed to simplify, or simplified to a different value
507 // to previously, then give up.
508 if (!V || (CommonValue && V != CommonValue))
516 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
517 /// try to simplify the comparison by seeing whether comparing with all of the
518 /// incoming phi values yields the same result every time. If so returns the
519 /// common result, otherwise returns null.
520 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
521 const TargetData *TD, const DominatorTree *DT,
522 unsigned MaxRecurse) {
523 // Recursion is always used, so bail out at once if we already hit the limit.
527 // Make sure the phi is on the LHS.
528 if (!isa<PHINode>(LHS)) {
530 Pred = CmpInst::getSwappedPredicate(Pred);
532 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
533 PHINode *PI = cast<PHINode>(LHS);
535 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
536 if (!ValueDominatesPHI(RHS, PI, DT))
539 // Evaluate the BinOp on the incoming phi values.
540 Value *CommonValue = 0;
541 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
542 Value *Incoming = PI->getIncomingValue(i);
543 // If the incoming value is the phi node itself, it can safely be skipped.
544 if (Incoming == PI) continue;
545 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
546 // If the operation failed to simplify, or simplified to a different value
547 // to previously, then give up.
548 if (!V || (CommonValue && V != CommonValue))
556 /// SimplifyAddInst - Given operands for an Add, see if we can
557 /// fold the result. If not, this returns null.
558 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
559 const TargetData *TD, const DominatorTree *DT,
560 unsigned MaxRecurse) {
561 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
562 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
563 Constant *Ops[] = { CLHS, CRHS };
564 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
568 // Canonicalize the constant to the RHS.
572 // X + undef -> undef
573 if (match(Op1, m_Undef()))
577 if (match(Op1, m_Zero()))
584 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
585 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
588 // X + ~X -> -1 since ~X = -X-1
589 if (match(Op0, m_Not(m_Specific(Op1))) ||
590 match(Op1, m_Not(m_Specific(Op0))))
591 return Constant::getAllOnesValue(Op0->getType());
594 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
595 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
598 // Try some generic simplifications for associative operations.
599 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
603 // Mul distributes over Add. Try some generic simplifications based on this.
604 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
608 // Threading Add over selects and phi nodes is pointless, so don't bother.
609 // Threading over the select in "A + select(cond, B, C)" means evaluating
610 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
611 // only if B and C are equal. If B and C are equal then (since we assume
612 // that operands have already been simplified) "select(cond, B, C)" should
613 // have been simplified to the common value of B and C already. Analysing
614 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
615 // for threading over phi nodes.
620 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
621 const TargetData *TD, const DominatorTree *DT) {
622 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
625 /// SimplifySubInst - Given operands for a Sub, see if we can
626 /// fold the result. If not, this returns null.
627 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
628 const TargetData *TD, const DominatorTree *DT,
629 unsigned MaxRecurse) {
630 if (Constant *CLHS = dyn_cast<Constant>(Op0))
631 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
632 Constant *Ops[] = { CLHS, CRHS };
633 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
637 // X - undef -> undef
638 // undef - X -> undef
639 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
640 return UndefValue::get(Op0->getType());
643 if (match(Op1, m_Zero()))
648 return Constant::getNullValue(Op0->getType());
653 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
654 match(Op0, m_Shl(m_Specific(Op1), m_One())))
657 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
658 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
659 Value *Y = 0, *Z = Op1;
660 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
661 // See if "V === Y - Z" simplifies.
662 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
663 // It does! Now see if "X + V" simplifies.
664 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
666 // It does, we successfully reassociated!
670 // See if "V === X - Z" simplifies.
671 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
672 // It does! Now see if "Y + V" simplifies.
673 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
675 // It does, we successfully reassociated!
681 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
682 // For example, X - (X + 1) -> -1
684 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
685 // See if "V === X - Y" simplifies.
686 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
687 // It does! Now see if "V - Z" simplifies.
688 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
690 // It does, we successfully reassociated!
694 // See if "V === X - Z" simplifies.
695 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
696 // It does! Now see if "V - Y" simplifies.
697 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
699 // It does, we successfully reassociated!
705 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
706 // For example, X - (X - Y) -> Y.
708 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
709 // See if "V === Z - X" simplifies.
710 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
711 // It does! Now see if "V + Y" simplifies.
712 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
714 // It does, we successfully reassociated!
719 // Mul distributes over Sub. Try some generic simplifications based on this.
720 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
725 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
726 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
729 // Threading Sub over selects and phi nodes is pointless, so don't bother.
730 // Threading over the select in "A - select(cond, B, C)" means evaluating
731 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
732 // only if B and C are equal. If B and C are equal then (since we assume
733 // that operands have already been simplified) "select(cond, B, C)" should
734 // have been simplified to the common value of B and C already. Analysing
735 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
736 // for threading over phi nodes.
741 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
742 const TargetData *TD, const DominatorTree *DT) {
743 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
746 /// SimplifyMulInst - Given operands for a Mul, see if we can
747 /// fold the result. If not, this returns null.
748 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
749 const DominatorTree *DT, unsigned MaxRecurse) {
750 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
751 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
752 Constant *Ops[] = { CLHS, CRHS };
753 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
757 // Canonicalize the constant to the RHS.
762 if (match(Op1, m_Undef()))
763 return Constant::getNullValue(Op0->getType());
766 if (match(Op1, m_Zero()))
770 if (match(Op1, m_One()))
773 // (X / Y) * Y -> X if the division is exact.
774 Value *X = 0, *Y = 0;
775 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
776 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
777 PossiblyExactOperator *Div =
778 cast<PossiblyExactOperator>(Y == Op1 ? Op0 : Op1);
784 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
785 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
788 // Try some generic simplifications for associative operations.
789 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
793 // Mul distributes over Add. Try some generic simplifications based on this.
794 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
798 // If the operation is with the result of a select instruction, check whether
799 // operating on either branch of the select always yields the same value.
800 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
801 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
805 // If the operation is with the result of a phi instruction, check whether
806 // operating on all incoming values of the phi always yields the same value.
807 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
808 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
815 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
816 const DominatorTree *DT) {
817 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
820 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
821 /// fold the result. If not, this returns null.
822 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
823 const TargetData *TD, const DominatorTree *DT,
824 unsigned MaxRecurse) {
825 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
826 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
827 Constant *Ops[] = { C0, C1 };
828 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
832 bool isSigned = Opcode == Instruction::SDiv;
834 // X / undef -> undef
835 if (match(Op1, m_Undef()))
839 if (match(Op0, m_Undef()))
840 return Constant::getNullValue(Op0->getType());
842 // 0 / X -> 0, we don't need to preserve faults!
843 if (match(Op0, m_Zero()))
847 if (match(Op1, m_One()))
850 if (Op0->getType()->isIntegerTy(1))
851 // It can't be division by zero, hence it must be division by one.
856 return ConstantInt::get(Op0->getType(), 1);
858 // (X * Y) / Y -> X if the multiplication does not overflow.
859 Value *X = 0, *Y = 0;
860 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
861 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
862 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
863 // If the Mul knows it does not overflow, then we are good to go.
864 if ((isSigned && Mul->hasNoSignedWrap()) ||
865 (!isSigned && Mul->hasNoUnsignedWrap()))
867 // If X has the form X = A / Y then X * Y cannot overflow.
868 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
869 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
873 // (X rem Y) / Y -> 0
874 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
875 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
876 return Constant::getNullValue(Op0->getType());
878 // If the operation is with the result of a select instruction, check whether
879 // operating on either branch of the select always yields the same value.
880 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
881 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
884 // If the operation is with the result of a phi instruction, check whether
885 // operating on all incoming values of the phi always yields the same value.
886 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
887 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
893 /// SimplifySDivInst - Given operands for an SDiv, see if we can
894 /// fold the result. If not, this returns null.
895 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
896 const DominatorTree *DT, unsigned MaxRecurse) {
897 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
903 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
904 const DominatorTree *DT) {
905 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
908 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
909 /// fold the result. If not, this returns null.
910 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
911 const DominatorTree *DT, unsigned MaxRecurse) {
912 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
918 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
919 const DominatorTree *DT) {
920 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
923 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
924 const DominatorTree *, unsigned) {
925 // undef / X -> undef (the undef could be a snan).
926 if (match(Op0, m_Undef()))
929 // X / undef -> undef
930 if (match(Op1, m_Undef()))
936 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
937 const DominatorTree *DT) {
938 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
941 /// SimplifyRem - Given operands for an SRem or URem, see if we can
942 /// fold the result. If not, this returns null.
943 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
944 const TargetData *TD, const DominatorTree *DT,
945 unsigned MaxRecurse) {
946 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
947 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
948 Constant *Ops[] = { C0, C1 };
949 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
953 // X % undef -> undef
954 if (match(Op1, m_Undef()))
958 if (match(Op0, m_Undef()))
959 return Constant::getNullValue(Op0->getType());
961 // 0 % X -> 0, we don't need to preserve faults!
962 if (match(Op0, m_Zero()))
965 // X % 0 -> undef, we don't need to preserve faults!
966 if (match(Op1, m_Zero()))
967 return UndefValue::get(Op0->getType());
970 if (match(Op1, m_One()))
971 return Constant::getNullValue(Op0->getType());
973 if (Op0->getType()->isIntegerTy(1))
974 // It can't be remainder by zero, hence it must be remainder by one.
975 return Constant::getNullValue(Op0->getType());
979 return Constant::getNullValue(Op0->getType());
981 // If the operation is with the result of a select instruction, check whether
982 // operating on either branch of the select always yields the same value.
983 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
984 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
987 // If the operation is with the result of a phi instruction, check whether
988 // operating on all incoming values of the phi always yields the same value.
989 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
990 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
996 /// SimplifySRemInst - Given operands for an SRem, see if we can
997 /// fold the result. If not, this returns null.
998 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
999 const DominatorTree *DT, unsigned MaxRecurse) {
1000 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
1006 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1007 const DominatorTree *DT) {
1008 return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
1011 /// SimplifyURemInst - Given operands for a URem, see if we can
1012 /// fold the result. If not, this returns null.
1013 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1014 const DominatorTree *DT, unsigned MaxRecurse) {
1015 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
1021 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1022 const DominatorTree *DT) {
1023 return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
1026 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1027 const DominatorTree *, unsigned) {
1028 // undef % X -> undef (the undef could be a snan).
1029 if (match(Op0, m_Undef()))
1032 // X % undef -> undef
1033 if (match(Op1, m_Undef()))
1039 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1040 const DominatorTree *DT) {
1041 return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1044 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1045 /// fold the result. If not, this returns null.
1046 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1047 const TargetData *TD, const DominatorTree *DT,
1048 unsigned MaxRecurse) {
1049 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1050 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1051 Constant *Ops[] = { C0, C1 };
1052 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
1056 // 0 shift by X -> 0
1057 if (match(Op0, m_Zero()))
1060 // X shift by 0 -> X
1061 if (match(Op1, m_Zero()))
1064 // X shift by undef -> undef because it may shift by the bitwidth.
1065 if (match(Op1, m_Undef()))
1068 // Shifting by the bitwidth or more is undefined.
1069 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1070 if (CI->getValue().getLimitedValue() >=
1071 Op0->getType()->getScalarSizeInBits())
1072 return UndefValue::get(Op0->getType());
1074 // If the operation is with the result of a select instruction, check whether
1075 // operating on either branch of the select always yields the same value.
1076 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1077 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1080 // If the operation is with the result of a phi instruction, check whether
1081 // operating on all incoming values of the phi always yields the same value.
1082 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1083 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1089 /// SimplifyShlInst - Given operands for an Shl, see if we can
1090 /// fold the result. If not, this returns null.
1091 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1092 const TargetData *TD, const DominatorTree *DT,
1093 unsigned MaxRecurse) {
1094 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1098 if (match(Op0, m_Undef()))
1099 return Constant::getNullValue(Op0->getType());
1101 // (X >> A) << A -> X
1103 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1104 cast<PossiblyExactOperator>(Op0)->isExact())
1109 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1110 const TargetData *TD, const DominatorTree *DT) {
1111 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
1114 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1115 /// fold the result. If not, this returns null.
1116 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1117 const TargetData *TD, const DominatorTree *DT,
1118 unsigned MaxRecurse) {
1119 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1123 if (match(Op0, m_Undef()))
1124 return Constant::getNullValue(Op0->getType());
1126 // (X << A) >> A -> X
1128 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1129 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1135 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1136 const TargetData *TD, const DominatorTree *DT) {
1137 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1140 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1141 /// fold the result. If not, this returns null.
1142 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1143 const TargetData *TD, const DominatorTree *DT,
1144 unsigned MaxRecurse) {
1145 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1148 // all ones >>a X -> all ones
1149 if (match(Op0, m_AllOnes()))
1152 // undef >>a X -> all ones
1153 if (match(Op0, m_Undef()))
1154 return Constant::getAllOnesValue(Op0->getType());
1156 // (X << A) >> A -> X
1158 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1159 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1165 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1166 const TargetData *TD, const DominatorTree *DT) {
1167 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1170 /// SimplifyAndInst - Given operands for an And, see if we can
1171 /// fold the result. If not, this returns null.
1172 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1173 const DominatorTree *DT, unsigned MaxRecurse) {
1174 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1175 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1176 Constant *Ops[] = { CLHS, CRHS };
1177 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1181 // Canonicalize the constant to the RHS.
1182 std::swap(Op0, Op1);
1186 if (match(Op1, m_Undef()))
1187 return Constant::getNullValue(Op0->getType());
1194 if (match(Op1, m_Zero()))
1198 if (match(Op1, m_AllOnes()))
1201 // A & ~A = ~A & A = 0
1202 if (match(Op0, m_Not(m_Specific(Op1))) ||
1203 match(Op1, m_Not(m_Specific(Op0))))
1204 return Constant::getNullValue(Op0->getType());
1207 Value *A = 0, *B = 0;
1208 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1209 (A == Op1 || B == Op1))
1213 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1214 (A == Op0 || B == Op0))
1217 // A & (-A) = A if A is a power of two or zero.
1218 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1219 match(Op1, m_Neg(m_Specific(Op0)))) {
1220 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1222 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1226 // Try some generic simplifications for associative operations.
1227 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1231 // And distributes over Or. Try some generic simplifications based on this.
1232 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1233 TD, DT, MaxRecurse))
1236 // And distributes over Xor. Try some generic simplifications based on this.
1237 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1238 TD, DT, MaxRecurse))
1241 // Or distributes over And. Try some generic simplifications based on this.
1242 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1243 TD, DT, MaxRecurse))
1246 // If the operation is with the result of a select instruction, check whether
1247 // operating on either branch of the select always yields the same value.
1248 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1249 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
1253 // If the operation is with the result of a phi instruction, check whether
1254 // operating on all incoming values of the phi always yields the same value.
1255 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1256 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
1263 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1264 const DominatorTree *DT) {
1265 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
1268 /// SimplifyOrInst - Given operands for an Or, see if we can
1269 /// fold the result. If not, this returns null.
1270 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1271 const DominatorTree *DT, unsigned MaxRecurse) {
1272 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1273 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1274 Constant *Ops[] = { CLHS, CRHS };
1275 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1279 // Canonicalize the constant to the RHS.
1280 std::swap(Op0, Op1);
1284 if (match(Op1, m_Undef()))
1285 return Constant::getAllOnesValue(Op0->getType());
1292 if (match(Op1, m_Zero()))
1296 if (match(Op1, m_AllOnes()))
1299 // A | ~A = ~A | A = -1
1300 if (match(Op0, m_Not(m_Specific(Op1))) ||
1301 match(Op1, m_Not(m_Specific(Op0))))
1302 return Constant::getAllOnesValue(Op0->getType());
1305 Value *A = 0, *B = 0;
1306 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1307 (A == Op1 || B == Op1))
1311 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1312 (A == Op0 || B == Op0))
1315 // ~(A & ?) | A = -1
1316 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1317 (A == Op1 || B == Op1))
1318 return Constant::getAllOnesValue(Op1->getType());
1320 // A | ~(A & ?) = -1
1321 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1322 (A == Op0 || B == Op0))
1323 return Constant::getAllOnesValue(Op0->getType());
1325 // Try some generic simplifications for associative operations.
1326 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1330 // Or distributes over And. Try some generic simplifications based on this.
1331 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1332 TD, DT, MaxRecurse))
1335 // And distributes over Or. Try some generic simplifications based on this.
1336 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1337 TD, DT, MaxRecurse))
1340 // If the operation is with the result of a select instruction, check whether
1341 // operating on either branch of the select always yields the same value.
1342 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1343 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
1347 // If the operation is with the result of a phi instruction, check whether
1348 // operating on all incoming values of the phi always yields the same value.
1349 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1350 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
1357 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1358 const DominatorTree *DT) {
1359 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
1362 /// SimplifyXorInst - Given operands for a Xor, see if we can
1363 /// fold the result. If not, this returns null.
1364 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1365 const DominatorTree *DT, unsigned MaxRecurse) {
1366 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1367 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1368 Constant *Ops[] = { CLHS, CRHS };
1369 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1373 // Canonicalize the constant to the RHS.
1374 std::swap(Op0, Op1);
1377 // A ^ undef -> undef
1378 if (match(Op1, m_Undef()))
1382 if (match(Op1, m_Zero()))
1387 return Constant::getNullValue(Op0->getType());
1389 // A ^ ~A = ~A ^ A = -1
1390 if (match(Op0, m_Not(m_Specific(Op1))) ||
1391 match(Op1, m_Not(m_Specific(Op0))))
1392 return Constant::getAllOnesValue(Op0->getType());
1394 // Try some generic simplifications for associative operations.
1395 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1399 // And distributes over Xor. Try some generic simplifications based on this.
1400 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1401 TD, DT, MaxRecurse))
1404 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1405 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1406 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1407 // only if B and C are equal. If B and C are equal then (since we assume
1408 // that operands have already been simplified) "select(cond, B, C)" should
1409 // have been simplified to the common value of B and C already. Analysing
1410 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1411 // for threading over phi nodes.
1416 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1417 const DominatorTree *DT) {
1418 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1421 static Type *GetCompareTy(Value *Op) {
1422 return CmpInst::makeCmpResultType(Op->getType());
1425 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1426 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1427 /// otherwise return null. Helper function for analyzing max/min idioms.
1428 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1429 Value *LHS, Value *RHS) {
1430 SelectInst *SI = dyn_cast<SelectInst>(V);
1433 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1436 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1437 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1439 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1440 LHS == CmpRHS && RHS == CmpLHS)
1445 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1446 /// fold the result. If not, this returns null.
1447 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1448 const TargetData *TD, const DominatorTree *DT,
1449 unsigned MaxRecurse) {
1450 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1451 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1453 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1454 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1455 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1457 // If we have a constant, make sure it is on the RHS.
1458 std::swap(LHS, RHS);
1459 Pred = CmpInst::getSwappedPredicate(Pred);
1462 Type *ITy = GetCompareTy(LHS); // The return type.
1463 Type *OpTy = LHS->getType(); // The operand type.
1465 // icmp X, X -> true/false
1466 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1467 // because X could be 0.
1468 if (LHS == RHS || isa<UndefValue>(RHS))
1469 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1471 // Special case logic when the operands have i1 type.
1472 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1473 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1476 case ICmpInst::ICMP_EQ:
1478 if (match(RHS, m_One()))
1481 case ICmpInst::ICMP_NE:
1483 if (match(RHS, m_Zero()))
1486 case ICmpInst::ICMP_UGT:
1488 if (match(RHS, m_Zero()))
1491 case ICmpInst::ICMP_UGE:
1493 if (match(RHS, m_One()))
1496 case ICmpInst::ICMP_SLT:
1498 if (match(RHS, m_Zero()))
1501 case ICmpInst::ICMP_SLE:
1503 if (match(RHS, m_One()))
1509 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1510 // different addresses, and what's more the address of a stack variable is
1511 // never null or equal to the address of a global. Note that generalizing
1512 // to the case where LHS is a global variable address or null is pointless,
1513 // since if both LHS and RHS are constants then we already constant folded
1514 // the compare, and if only one of them is then we moved it to RHS already.
1515 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1516 isa<ConstantPointerNull>(RHS)))
1517 // We already know that LHS != RHS.
1518 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1520 // If we are comparing with zero then try hard since this is a common case.
1521 if (match(RHS, m_Zero())) {
1522 bool LHSKnownNonNegative, LHSKnownNegative;
1525 assert(false && "Unknown ICmp predicate!");
1526 case ICmpInst::ICMP_ULT:
1527 return getFalse(ITy);
1528 case ICmpInst::ICMP_UGE:
1529 return getTrue(ITy);
1530 case ICmpInst::ICMP_EQ:
1531 case ICmpInst::ICMP_ULE:
1532 if (isKnownNonZero(LHS, TD))
1533 return getFalse(ITy);
1535 case ICmpInst::ICMP_NE:
1536 case ICmpInst::ICMP_UGT:
1537 if (isKnownNonZero(LHS, TD))
1538 return getTrue(ITy);
1540 case ICmpInst::ICMP_SLT:
1541 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1542 if (LHSKnownNegative)
1543 return getTrue(ITy);
1544 if (LHSKnownNonNegative)
1545 return getFalse(ITy);
1547 case ICmpInst::ICMP_SLE:
1548 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1549 if (LHSKnownNegative)
1550 return getTrue(ITy);
1551 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1552 return getFalse(ITy);
1554 case ICmpInst::ICMP_SGE:
1555 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1556 if (LHSKnownNegative)
1557 return getFalse(ITy);
1558 if (LHSKnownNonNegative)
1559 return getTrue(ITy);
1561 case ICmpInst::ICMP_SGT:
1562 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1563 if (LHSKnownNegative)
1564 return getFalse(ITy);
1565 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1566 return getTrue(ITy);
1571 // See if we are doing a comparison with a constant integer.
1572 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1573 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1574 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1575 if (RHS_CR.isEmptySet())
1576 return ConstantInt::getFalse(CI->getContext());
1577 if (RHS_CR.isFullSet())
1578 return ConstantInt::getTrue(CI->getContext());
1580 // Many binary operators with constant RHS have easy to compute constant
1581 // range. Use them to check whether the comparison is a tautology.
1582 uint32_t Width = CI->getBitWidth();
1583 APInt Lower = APInt(Width, 0);
1584 APInt Upper = APInt(Width, 0);
1586 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1587 // 'urem x, CI2' produces [0, CI2).
1588 Upper = CI2->getValue();
1589 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1590 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1591 Upper = CI2->getValue().abs();
1592 Lower = (-Upper) + 1;
1593 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1594 // 'udiv CI2, x' produces [0, CI2].
1595 Upper = CI2->getValue();
1596 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1597 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1598 APInt NegOne = APInt::getAllOnesValue(Width);
1600 Upper = NegOne.udiv(CI2->getValue()) + 1;
1601 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1602 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1603 APInt IntMin = APInt::getSignedMinValue(Width);
1604 APInt IntMax = APInt::getSignedMaxValue(Width);
1605 APInt Val = CI2->getValue().abs();
1606 if (!Val.isMinValue()) {
1607 Lower = IntMin.sdiv(Val);
1608 Upper = IntMax.sdiv(Val) + 1;
1610 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1611 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1612 APInt NegOne = APInt::getAllOnesValue(Width);
1613 if (CI2->getValue().ult(Width))
1614 Upper = NegOne.lshr(CI2->getValue()) + 1;
1615 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1616 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1617 APInt IntMin = APInt::getSignedMinValue(Width);
1618 APInt IntMax = APInt::getSignedMaxValue(Width);
1619 if (CI2->getValue().ult(Width)) {
1620 Lower = IntMin.ashr(CI2->getValue());
1621 Upper = IntMax.ashr(CI2->getValue()) + 1;
1623 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1624 // 'or x, CI2' produces [CI2, UINT_MAX].
1625 Lower = CI2->getValue();
1626 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1627 // 'and x, CI2' produces [0, CI2].
1628 Upper = CI2->getValue() + 1;
1630 if (Lower != Upper) {
1631 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1632 if (RHS_CR.contains(LHS_CR))
1633 return ConstantInt::getTrue(RHS->getContext());
1634 if (RHS_CR.inverse().contains(LHS_CR))
1635 return ConstantInt::getFalse(RHS->getContext());
1639 // Compare of cast, for example (zext X) != 0 -> X != 0
1640 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1641 Instruction *LI = cast<CastInst>(LHS);
1642 Value *SrcOp = LI->getOperand(0);
1643 Type *SrcTy = SrcOp->getType();
1644 Type *DstTy = LI->getType();
1646 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1647 // if the integer type is the same size as the pointer type.
1648 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1649 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1650 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1651 // Transfer the cast to the constant.
1652 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1653 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1654 TD, DT, MaxRecurse-1))
1656 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1657 if (RI->getOperand(0)->getType() == SrcTy)
1658 // Compare without the cast.
1659 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1660 TD, DT, MaxRecurse-1))
1665 if (isa<ZExtInst>(LHS)) {
1666 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1668 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1669 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1670 // Compare X and Y. Note that signed predicates become unsigned.
1671 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1672 SrcOp, RI->getOperand(0), TD, DT,
1676 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1677 // too. If not, then try to deduce the result of the comparison.
1678 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1679 // Compute the constant that would happen if we truncated to SrcTy then
1680 // reextended to DstTy.
1681 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1682 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1684 // If the re-extended constant didn't change then this is effectively
1685 // also a case of comparing two zero-extended values.
1686 if (RExt == CI && MaxRecurse)
1687 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1688 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1691 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1692 // there. Use this to work out the result of the comparison.
1696 assert(false && "Unknown ICmp predicate!");
1698 case ICmpInst::ICMP_EQ:
1699 case ICmpInst::ICMP_UGT:
1700 case ICmpInst::ICMP_UGE:
1701 return ConstantInt::getFalse(CI->getContext());
1703 case ICmpInst::ICMP_NE:
1704 case ICmpInst::ICMP_ULT:
1705 case ICmpInst::ICMP_ULE:
1706 return ConstantInt::getTrue(CI->getContext());
1708 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1709 // is non-negative then LHS <s RHS.
1710 case ICmpInst::ICMP_SGT:
1711 case ICmpInst::ICMP_SGE:
1712 return CI->getValue().isNegative() ?
1713 ConstantInt::getTrue(CI->getContext()) :
1714 ConstantInt::getFalse(CI->getContext());
1716 case ICmpInst::ICMP_SLT:
1717 case ICmpInst::ICMP_SLE:
1718 return CI->getValue().isNegative() ?
1719 ConstantInt::getFalse(CI->getContext()) :
1720 ConstantInt::getTrue(CI->getContext());
1726 if (isa<SExtInst>(LHS)) {
1727 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1729 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1730 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1731 // Compare X and Y. Note that the predicate does not change.
1732 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1733 TD, DT, MaxRecurse-1))
1736 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1737 // too. If not, then try to deduce the result of the comparison.
1738 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1739 // Compute the constant that would happen if we truncated to SrcTy then
1740 // reextended to DstTy.
1741 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1742 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1744 // If the re-extended constant didn't change then this is effectively
1745 // also a case of comparing two sign-extended values.
1746 if (RExt == CI && MaxRecurse)
1747 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1751 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1752 // bits there. Use this to work out the result of the comparison.
1756 assert(false && "Unknown ICmp predicate!");
1757 case ICmpInst::ICMP_EQ:
1758 return ConstantInt::getFalse(CI->getContext());
1759 case ICmpInst::ICMP_NE:
1760 return ConstantInt::getTrue(CI->getContext());
1762 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1764 case ICmpInst::ICMP_SGT:
1765 case ICmpInst::ICMP_SGE:
1766 return CI->getValue().isNegative() ?
1767 ConstantInt::getTrue(CI->getContext()) :
1768 ConstantInt::getFalse(CI->getContext());
1769 case ICmpInst::ICMP_SLT:
1770 case ICmpInst::ICMP_SLE:
1771 return CI->getValue().isNegative() ?
1772 ConstantInt::getFalse(CI->getContext()) :
1773 ConstantInt::getTrue(CI->getContext());
1775 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1777 case ICmpInst::ICMP_UGT:
1778 case ICmpInst::ICMP_UGE:
1779 // Comparison is true iff the LHS <s 0.
1781 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1782 Constant::getNullValue(SrcTy),
1783 TD, DT, MaxRecurse-1))
1786 case ICmpInst::ICMP_ULT:
1787 case ICmpInst::ICMP_ULE:
1788 // Comparison is true iff the LHS >=s 0.
1790 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1791 Constant::getNullValue(SrcTy),
1792 TD, DT, MaxRecurse-1))
1801 // Special logic for binary operators.
1802 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1803 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1804 if (MaxRecurse && (LBO || RBO)) {
1805 // Analyze the case when either LHS or RHS is an add instruction.
1806 Value *A = 0, *B = 0, *C = 0, *D = 0;
1807 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1808 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1809 if (LBO && LBO->getOpcode() == Instruction::Add) {
1810 A = LBO->getOperand(0); B = LBO->getOperand(1);
1811 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1812 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1813 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1815 if (RBO && RBO->getOpcode() == Instruction::Add) {
1816 C = RBO->getOperand(0); D = RBO->getOperand(1);
1817 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1818 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1819 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1822 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1823 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1824 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1825 Constant::getNullValue(RHS->getType()),
1826 TD, DT, MaxRecurse-1))
1829 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1830 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1831 if (Value *V = SimplifyICmpInst(Pred,
1832 Constant::getNullValue(LHS->getType()),
1833 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1836 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1837 if (A && C && (A == C || A == D || B == C || B == D) &&
1838 NoLHSWrapProblem && NoRHSWrapProblem) {
1839 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1840 Value *Y = (A == C || A == D) ? B : A;
1841 Value *Z = (C == A || C == B) ? D : C;
1842 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1847 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1848 bool KnownNonNegative, KnownNegative;
1852 case ICmpInst::ICMP_SGT:
1853 case ICmpInst::ICMP_SGE:
1854 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1855 if (!KnownNonNegative)
1858 case ICmpInst::ICMP_EQ:
1859 case ICmpInst::ICMP_UGT:
1860 case ICmpInst::ICMP_UGE:
1861 return getFalse(ITy);
1862 case ICmpInst::ICMP_SLT:
1863 case ICmpInst::ICMP_SLE:
1864 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1865 if (!KnownNonNegative)
1868 case ICmpInst::ICMP_NE:
1869 case ICmpInst::ICMP_ULT:
1870 case ICmpInst::ICMP_ULE:
1871 return getTrue(ITy);
1874 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1875 bool KnownNonNegative, KnownNegative;
1879 case ICmpInst::ICMP_SGT:
1880 case ICmpInst::ICMP_SGE:
1881 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1882 if (!KnownNonNegative)
1885 case ICmpInst::ICMP_NE:
1886 case ICmpInst::ICMP_UGT:
1887 case ICmpInst::ICMP_UGE:
1888 return getTrue(ITy);
1889 case ICmpInst::ICMP_SLT:
1890 case ICmpInst::ICMP_SLE:
1891 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1892 if (!KnownNonNegative)
1895 case ICmpInst::ICMP_EQ:
1896 case ICmpInst::ICMP_ULT:
1897 case ICmpInst::ICMP_ULE:
1898 return getFalse(ITy);
1903 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
1904 // icmp pred (X /u Y), X
1905 if (Pred == ICmpInst::ICMP_UGT)
1906 return getFalse(ITy);
1907 if (Pred == ICmpInst::ICMP_ULE)
1908 return getTrue(ITy);
1911 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1912 LBO->getOperand(1) == RBO->getOperand(1)) {
1913 switch (LBO->getOpcode()) {
1915 case Instruction::UDiv:
1916 case Instruction::LShr:
1917 if (ICmpInst::isSigned(Pred))
1920 case Instruction::SDiv:
1921 case Instruction::AShr:
1922 if (!LBO->isExact() || !RBO->isExact())
1924 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1925 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1928 case Instruction::Shl: {
1929 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
1930 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1933 if (!NSW && ICmpInst::isSigned(Pred))
1935 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1936 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1943 // Simplify comparisons involving max/min.
1945 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1946 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1948 // Signed variants on "max(a,b)>=a -> true".
1949 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1950 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1951 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1952 // We analyze this as smax(A, B) pred A.
1954 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1955 (A == LHS || B == LHS)) {
1956 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1957 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1958 // We analyze this as smax(A, B) swapped-pred A.
1959 P = CmpInst::getSwappedPredicate(Pred);
1960 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1961 (A == RHS || B == RHS)) {
1962 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1963 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1964 // We analyze this as smax(-A, -B) swapped-pred -A.
1965 // Note that we do not need to actually form -A or -B thanks to EqP.
1966 P = CmpInst::getSwappedPredicate(Pred);
1967 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1968 (A == LHS || B == LHS)) {
1969 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1970 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1971 // We analyze this as smax(-A, -B) pred -A.
1972 // Note that we do not need to actually form -A or -B thanks to EqP.
1975 if (P != CmpInst::BAD_ICMP_PREDICATE) {
1976 // Cases correspond to "max(A, B) p A".
1980 case CmpInst::ICMP_EQ:
1981 case CmpInst::ICMP_SLE:
1982 // Equivalent to "A EqP B". This may be the same as the condition tested
1983 // in the max/min; if so, we can just return that.
1984 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
1986 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
1988 // Otherwise, see if "A EqP B" simplifies.
1990 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
1993 case CmpInst::ICMP_NE:
1994 case CmpInst::ICMP_SGT: {
1995 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
1996 // Equivalent to "A InvEqP B". This may be the same as the condition
1997 // tested in the max/min; if so, we can just return that.
1998 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2000 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2002 // Otherwise, see if "A InvEqP B" simplifies.
2004 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2008 case CmpInst::ICMP_SGE:
2010 return getTrue(ITy);
2011 case CmpInst::ICMP_SLT:
2013 return getFalse(ITy);
2017 // Unsigned variants on "max(a,b)>=a -> true".
2018 P = CmpInst::BAD_ICMP_PREDICATE;
2019 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2020 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2021 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2022 // We analyze this as umax(A, B) pred A.
2024 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2025 (A == LHS || B == LHS)) {
2026 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2027 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2028 // We analyze this as umax(A, B) swapped-pred A.
2029 P = CmpInst::getSwappedPredicate(Pred);
2030 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2031 (A == RHS || B == RHS)) {
2032 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2033 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2034 // We analyze this as umax(-A, -B) swapped-pred -A.
2035 // Note that we do not need to actually form -A or -B thanks to EqP.
2036 P = CmpInst::getSwappedPredicate(Pred);
2037 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2038 (A == LHS || B == LHS)) {
2039 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2040 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2041 // We analyze this as umax(-A, -B) pred -A.
2042 // Note that we do not need to actually form -A or -B thanks to EqP.
2045 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2046 // Cases correspond to "max(A, B) p A".
2050 case CmpInst::ICMP_EQ:
2051 case CmpInst::ICMP_ULE:
2052 // Equivalent to "A EqP B". This may be the same as the condition tested
2053 // in the max/min; if so, we can just return that.
2054 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2056 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2058 // Otherwise, see if "A EqP B" simplifies.
2060 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2063 case CmpInst::ICMP_NE:
2064 case CmpInst::ICMP_UGT: {
2065 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2066 // Equivalent to "A InvEqP B". This may be the same as the condition
2067 // tested in the max/min; if so, we can just return that.
2068 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2070 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2072 // Otherwise, see if "A InvEqP B" simplifies.
2074 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2078 case CmpInst::ICMP_UGE:
2080 return getTrue(ITy);
2081 case CmpInst::ICMP_ULT:
2083 return getFalse(ITy);
2087 // Variants on "max(x,y) >= min(x,z)".
2089 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2090 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2091 (A == C || A == D || B == C || B == D)) {
2092 // max(x, ?) pred min(x, ?).
2093 if (Pred == CmpInst::ICMP_SGE)
2095 return getTrue(ITy);
2096 if (Pred == CmpInst::ICMP_SLT)
2098 return getFalse(ITy);
2099 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2100 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2101 (A == C || A == D || B == C || B == D)) {
2102 // min(x, ?) pred max(x, ?).
2103 if (Pred == CmpInst::ICMP_SLE)
2105 return getTrue(ITy);
2106 if (Pred == CmpInst::ICMP_SGT)
2108 return getFalse(ITy);
2109 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2110 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2111 (A == C || A == D || B == C || B == D)) {
2112 // max(x, ?) pred min(x, ?).
2113 if (Pred == CmpInst::ICMP_UGE)
2115 return getTrue(ITy);
2116 if (Pred == CmpInst::ICMP_ULT)
2118 return getFalse(ITy);
2119 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2120 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2121 (A == C || A == D || B == C || B == D)) {
2122 // min(x, ?) pred max(x, ?).
2123 if (Pred == CmpInst::ICMP_ULE)
2125 return getTrue(ITy);
2126 if (Pred == CmpInst::ICMP_UGT)
2128 return getFalse(ITy);
2131 // If the comparison is with the result of a select instruction, check whether
2132 // comparing with either branch of the select always yields the same value.
2133 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2134 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2137 // If the comparison is with the result of a phi instruction, check whether
2138 // doing the compare with each incoming phi value yields a common result.
2139 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2140 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2146 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2147 const TargetData *TD, const DominatorTree *DT) {
2148 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2151 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2152 /// fold the result. If not, this returns null.
2153 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2154 const TargetData *TD, const DominatorTree *DT,
2155 unsigned MaxRecurse) {
2156 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2157 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2159 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2160 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2161 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
2163 // If we have a constant, make sure it is on the RHS.
2164 std::swap(LHS, RHS);
2165 Pred = CmpInst::getSwappedPredicate(Pred);
2168 // Fold trivial predicates.
2169 if (Pred == FCmpInst::FCMP_FALSE)
2170 return ConstantInt::get(GetCompareTy(LHS), 0);
2171 if (Pred == FCmpInst::FCMP_TRUE)
2172 return ConstantInt::get(GetCompareTy(LHS), 1);
2174 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2175 return UndefValue::get(GetCompareTy(LHS));
2177 // fcmp x,x -> true/false. Not all compares are foldable.
2179 if (CmpInst::isTrueWhenEqual(Pred))
2180 return ConstantInt::get(GetCompareTy(LHS), 1);
2181 if (CmpInst::isFalseWhenEqual(Pred))
2182 return ConstantInt::get(GetCompareTy(LHS), 0);
2185 // Handle fcmp with constant RHS
2186 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2187 // If the constant is a nan, see if we can fold the comparison based on it.
2188 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2189 if (CFP->getValueAPF().isNaN()) {
2190 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2191 return ConstantInt::getFalse(CFP->getContext());
2192 assert(FCmpInst::isUnordered(Pred) &&
2193 "Comparison must be either ordered or unordered!");
2194 // True if unordered.
2195 return ConstantInt::getTrue(CFP->getContext());
2197 // Check whether the constant is an infinity.
2198 if (CFP->getValueAPF().isInfinity()) {
2199 if (CFP->getValueAPF().isNegative()) {
2201 case FCmpInst::FCMP_OLT:
2202 // No value is ordered and less than negative infinity.
2203 return ConstantInt::getFalse(CFP->getContext());
2204 case FCmpInst::FCMP_UGE:
2205 // All values are unordered with or at least negative infinity.
2206 return ConstantInt::getTrue(CFP->getContext());
2212 case FCmpInst::FCMP_OGT:
2213 // No value is ordered and greater than infinity.
2214 return ConstantInt::getFalse(CFP->getContext());
2215 case FCmpInst::FCMP_ULE:
2216 // All values are unordered with and at most infinity.
2217 return ConstantInt::getTrue(CFP->getContext());
2226 // If the comparison is with the result of a select instruction, check whether
2227 // comparing with either branch of the select always yields the same value.
2228 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2229 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2232 // If the comparison is with the result of a phi instruction, check whether
2233 // doing the compare with each incoming phi value yields a common result.
2234 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2235 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2241 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2242 const TargetData *TD, const DominatorTree *DT) {
2243 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2246 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2247 /// the result. If not, this returns null.
2248 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2249 const TargetData *TD, const DominatorTree *) {
2250 // select true, X, Y -> X
2251 // select false, X, Y -> Y
2252 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2253 return CB->getZExtValue() ? TrueVal : FalseVal;
2255 // select C, X, X -> X
2256 if (TrueVal == FalseVal)
2259 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2260 if (isa<Constant>(TrueVal))
2264 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2266 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2272 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2273 /// fold the result. If not, this returns null.
2274 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops,
2275 const TargetData *TD, const DominatorTree *) {
2276 // The type of the GEP pointer operand.
2277 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
2279 // getelementptr P -> P.
2280 if (Ops.size() == 1)
2283 if (isa<UndefValue>(Ops[0])) {
2284 // Compute the (pointer) type returned by the GEP instruction.
2285 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2286 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2287 return UndefValue::get(GEPTy);
2290 if (Ops.size() == 2) {
2291 // getelementptr P, 0 -> P.
2292 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2295 // getelementptr P, N -> P if P points to a type of zero size.
2297 Type *Ty = PtrTy->getElementType();
2298 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2303 // Check to see if this is constant foldable.
2304 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2305 if (!isa<Constant>(Ops[i]))
2308 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2311 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2312 /// can fold the result. If not, this returns null.
2313 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2314 ArrayRef<unsigned> Idxs,
2316 const DominatorTree *) {
2317 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2318 if (Constant *CVal = dyn_cast<Constant>(Val))
2319 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2321 // insertvalue x, undef, n -> x
2322 if (match(Val, m_Undef()))
2325 // insertvalue x, (extractvalue y, n), n
2326 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2327 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2328 EV->getIndices() == Idxs) {
2329 // insertvalue undef, (extractvalue y, n), n -> y
2330 if (match(Agg, m_Undef()))
2331 return EV->getAggregateOperand();
2333 // insertvalue y, (extractvalue y, n), n -> y
2334 if (Agg == EV->getAggregateOperand())
2341 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2342 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2343 // If all of the PHI's incoming values are the same then replace the PHI node
2344 // with the common value.
2345 Value *CommonValue = 0;
2346 bool HasUndefInput = false;
2347 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2348 Value *Incoming = PN->getIncomingValue(i);
2349 // If the incoming value is the phi node itself, it can safely be skipped.
2350 if (Incoming == PN) continue;
2351 if (isa<UndefValue>(Incoming)) {
2352 // Remember that we saw an undef value, but otherwise ignore them.
2353 HasUndefInput = true;
2356 if (CommonValue && Incoming != CommonValue)
2357 return 0; // Not the same, bail out.
2358 CommonValue = Incoming;
2361 // If CommonValue is null then all of the incoming values were either undef or
2362 // equal to the phi node itself.
2364 return UndefValue::get(PN->getType());
2366 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2367 // instruction, we cannot return X as the result of the PHI node unless it
2368 // dominates the PHI block.
2370 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2376 //=== Helper functions for higher up the class hierarchy.
2378 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2379 /// fold the result. If not, this returns null.
2380 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2381 const TargetData *TD, const DominatorTree *DT,
2382 unsigned MaxRecurse) {
2384 case Instruction::Add:
2385 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2386 TD, DT, MaxRecurse);
2387 case Instruction::Sub:
2388 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2389 TD, DT, MaxRecurse);
2390 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
2391 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2392 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
2393 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
2394 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2395 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2396 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
2397 case Instruction::Shl:
2398 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2399 TD, DT, MaxRecurse);
2400 case Instruction::LShr:
2401 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2402 case Instruction::AShr:
2403 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2404 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
2405 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
2406 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
2408 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2409 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2410 Constant *COps[] = {CLHS, CRHS};
2411 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD);
2414 // If the operation is associative, try some generic simplifications.
2415 if (Instruction::isAssociative(Opcode))
2416 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2420 // If the operation is with the result of a select instruction, check whether
2421 // operating on either branch of the select always yields the same value.
2422 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2423 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
2427 // If the operation is with the result of a phi instruction, check whether
2428 // operating on all incoming values of the phi always yields the same value.
2429 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2430 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
2437 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2438 const TargetData *TD, const DominatorTree *DT) {
2439 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
2442 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2443 /// fold the result.
2444 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2445 const TargetData *TD, const DominatorTree *DT,
2446 unsigned MaxRecurse) {
2447 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2448 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2449 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2452 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2453 const TargetData *TD, const DominatorTree *DT) {
2454 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2457 /// SimplifyInstruction - See if we can compute a simplified version of this
2458 /// instruction. If not, this returns null.
2459 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2460 const DominatorTree *DT) {
2463 switch (I->getOpcode()) {
2465 Result = ConstantFoldInstruction(I, TD);
2467 case Instruction::Add:
2468 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2469 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2470 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2473 case Instruction::Sub:
2474 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2475 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2476 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2479 case Instruction::Mul:
2480 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2482 case Instruction::SDiv:
2483 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2485 case Instruction::UDiv:
2486 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2488 case Instruction::FDiv:
2489 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2491 case Instruction::SRem:
2492 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2494 case Instruction::URem:
2495 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2497 case Instruction::FRem:
2498 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2500 case Instruction::Shl:
2501 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2502 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2503 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2506 case Instruction::LShr:
2507 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2508 cast<BinaryOperator>(I)->isExact(),
2511 case Instruction::AShr:
2512 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2513 cast<BinaryOperator>(I)->isExact(),
2516 case Instruction::And:
2517 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2519 case Instruction::Or:
2520 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2522 case Instruction::Xor:
2523 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2525 case Instruction::ICmp:
2526 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2527 I->getOperand(0), I->getOperand(1), TD, DT);
2529 case Instruction::FCmp:
2530 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2531 I->getOperand(0), I->getOperand(1), TD, DT);
2533 case Instruction::Select:
2534 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2535 I->getOperand(2), TD, DT);
2537 case Instruction::GetElementPtr: {
2538 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2539 Result = SimplifyGEPInst(Ops, TD, DT);
2542 case Instruction::InsertValue: {
2543 InsertValueInst *IV = cast<InsertValueInst>(I);
2544 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2545 IV->getInsertedValueOperand(),
2546 IV->getIndices(), TD, DT);
2549 case Instruction::PHI:
2550 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2554 /// If called on unreachable code, the above logic may report that the
2555 /// instruction simplified to itself. Make life easier for users by
2556 /// detecting that case here, returning a safe value instead.
2557 return Result == I ? UndefValue::get(I->getType()) : Result;
2560 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2561 /// delete the From instruction. In addition to a basic RAUW, this does a
2562 /// recursive simplification of the newly formed instructions. This catches
2563 /// things where one simplification exposes other opportunities. This only
2564 /// simplifies and deletes scalar operations, it does not change the CFG.
2566 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2567 const TargetData *TD,
2568 const DominatorTree *DT) {
2569 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2571 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2572 // we can know if it gets deleted out from under us or replaced in a
2573 // recursive simplification.
2574 WeakVH FromHandle(From);
2575 WeakVH ToHandle(To);
2577 while (!From->use_empty()) {
2578 // Update the instruction to use the new value.
2579 Use &TheUse = From->use_begin().getUse();
2580 Instruction *User = cast<Instruction>(TheUse.getUser());
2583 // Check to see if the instruction can be folded due to the operand
2584 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2585 // the 'or' with -1.
2586 Value *SimplifiedVal;
2588 // Sanity check to make sure 'User' doesn't dangle across
2589 // SimplifyInstruction.
2590 AssertingVH<> UserHandle(User);
2592 SimplifiedVal = SimplifyInstruction(User, TD, DT);
2593 if (SimplifiedVal == 0) continue;
2596 // Recursively simplify this user to the new value.
2597 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
2598 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2601 assert(ToHandle && "To value deleted by recursive simplification?");
2603 // If the recursive simplification ended up revisiting and deleting
2604 // 'From' then we're done.
2609 // If 'From' has value handles referring to it, do a real RAUW to update them.
2610 From->replaceAllUsesWith(To);
2612 From->eraseFromParent();