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/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Support/PatternMatch.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "llvm/Target/TargetData.h"
27 using namespace llvm::PatternMatch;
29 #define RecursionLimit 3
31 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
32 const DominatorTree *, unsigned);
33 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
34 const DominatorTree *, unsigned);
36 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
37 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
38 Instruction *I = dyn_cast<Instruction>(V);
40 // Arguments and constants dominate all instructions.
43 // If we have a DominatorTree then do a precise test.
45 return DT->dominates(I, P);
47 // Otherwise, if the instruction is in the entry block, and is not an invoke,
48 // then it obviously dominates all phi nodes.
49 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
56 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
57 /// instruction as an operand, try to simplify the binop by seeing whether
58 /// evaluating it on both branches of the select results in the same value.
59 /// Returns the common value if so, otherwise returns null.
60 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
62 const DominatorTree *DT,
63 unsigned MaxRecurse) {
65 if (isa<SelectInst>(LHS)) {
66 SI = cast<SelectInst>(LHS);
68 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
69 SI = cast<SelectInst>(RHS);
72 // Evaluate the BinOp on the true and false branches of the select.
76 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
77 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
79 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
80 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
83 // If they simplified to the same value, then return the common value.
84 // If they both failed to simplify then return null.
88 // If one branch simplified to undef, return the other one.
89 if (TV && isa<UndefValue>(TV))
91 if (FV && isa<UndefValue>(FV))
94 // If applying the operation did not change the true and false select values,
95 // then the result of the binop is the select itself.
96 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
99 // If one branch simplified and the other did not, and the simplified
100 // value is equal to the unsimplified one, return the simplified value.
101 // For example, select (cond, X, X & Z) & Z -> X & Z.
102 if ((FV && !TV) || (TV && !FV)) {
103 // Check that the simplified value has the form "X op Y" where "op" is the
104 // same as the original operation.
105 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
106 if (Simplified && Simplified->getOpcode() == Opcode) {
107 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
108 // We already know that "op" is the same as for the simplified value. See
109 // if the operands match too. If so, return the simplified value.
110 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
111 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
112 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
113 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
114 Simplified->getOperand(1) == UnsimplifiedRHS)
116 if (Simplified->isCommutative() &&
117 Simplified->getOperand(1) == UnsimplifiedLHS &&
118 Simplified->getOperand(0) == UnsimplifiedRHS)
126 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
127 /// try to simplify the comparison by seeing whether both branches of the select
128 /// result in the same value. Returns the common value if so, otherwise returns
130 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
131 Value *RHS, const TargetData *TD,
132 const DominatorTree *DT,
133 unsigned MaxRecurse) {
134 // Make sure the select is on the LHS.
135 if (!isa<SelectInst>(LHS)) {
137 Pred = CmpInst::getSwappedPredicate(Pred);
139 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
140 SelectInst *SI = cast<SelectInst>(LHS);
142 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
143 // Does "cmp TV, RHS" simplify?
144 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
146 // It does! Does "cmp FV, RHS" simplify?
147 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
149 // It does! If they simplified to the same value, then use it as the
150 // result of the original comparison.
156 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
157 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
158 /// it on the incoming phi values yields the same result for every value. If so
159 /// returns the common value, otherwise returns null.
160 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
161 const TargetData *TD, const DominatorTree *DT,
162 unsigned MaxRecurse) {
164 if (isa<PHINode>(LHS)) {
165 PI = cast<PHINode>(LHS);
166 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
167 if (!ValueDominatesPHI(RHS, PI, DT))
170 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
171 PI = cast<PHINode>(RHS);
172 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
173 if (!ValueDominatesPHI(LHS, PI, DT))
177 // Evaluate the BinOp on the incoming phi values.
178 Value *CommonValue = 0;
179 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
180 Value *Incoming = PI->getIncomingValue(i);
181 // If the incoming value is the phi node itself, it can safely be skipped.
182 if (Incoming == PI) continue;
183 Value *V = PI == LHS ?
184 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
185 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
186 // If the operation failed to simplify, or simplified to a different value
187 // to previously, then give up.
188 if (!V || (CommonValue && V != CommonValue))
196 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
197 /// try to simplify the comparison by seeing whether comparing with all of the
198 /// incoming phi values yields the same result every time. If so returns the
199 /// common result, otherwise returns null.
200 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
201 const TargetData *TD, const DominatorTree *DT,
202 unsigned MaxRecurse) {
203 // Make sure the phi is on the LHS.
204 if (!isa<PHINode>(LHS)) {
206 Pred = CmpInst::getSwappedPredicate(Pred);
208 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
209 PHINode *PI = cast<PHINode>(LHS);
211 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
212 if (!ValueDominatesPHI(RHS, PI, DT))
215 // Evaluate the BinOp on the incoming phi values.
216 Value *CommonValue = 0;
217 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
218 Value *Incoming = PI->getIncomingValue(i);
219 // If the incoming value is the phi node itself, it can safely be skipped.
220 if (Incoming == PI) continue;
221 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
222 // If the operation failed to simplify, or simplified to a different value
223 // to previously, then give up.
224 if (!V || (CommonValue && V != CommonValue))
232 /// SimplifyAddInst - Given operands for an Add, see if we can
233 /// fold the result. If not, this returns null.
234 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
235 const TargetData *TD, const DominatorTree *DT,
236 unsigned MaxRecurse) {
237 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
238 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
239 Constant *Ops[] = { CLHS, CRHS };
240 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
244 // Canonicalize the constant to the RHS.
248 // X + undef -> undef
249 if (isa<UndefValue>(Op1))
253 if (match(Op1, m_Zero()))
260 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
261 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
264 // X + ~X -> -1 since ~X = -X-1
265 if (match(Op0, m_Not(m_Specific(Op1))) ||
266 match(Op1, m_Not(m_Specific(Op0))))
267 return Constant::getAllOnesValue(Op0->getType());
269 // Threading Add over selects and phi nodes is pointless, so don't bother.
270 // Threading over the select in "A + select(cond, B, C)" means evaluating
271 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
272 // only if B and C are equal. If B and C are equal then (since we assume
273 // that operands have already been simplified) "select(cond, B, C)" should
274 // have been simplified to the common value of B and C already. Analysing
275 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
276 // for threading over phi nodes.
281 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
282 const TargetData *TD, const DominatorTree *DT) {
283 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
286 /// SimplifySubInst - Given operands for a Sub, see if we can
287 /// fold the result. If not, this returns null.
288 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
289 const TargetData *TD, const DominatorTree *,
290 unsigned MaxRecurse) {
291 if (Constant *CLHS = dyn_cast<Constant>(Op0))
292 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
293 Constant *Ops[] = { CLHS, CRHS };
294 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
298 // X - undef -> undef
299 // undef - X -> undef
300 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
301 return UndefValue::get(Op0->getType());
304 if (match(Op1, m_Zero()))
309 return Constant::getNullValue(Op0->getType());
314 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
315 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
318 // Threading Sub over selects and phi nodes is pointless, so don't bother.
319 // Threading over the select in "A - select(cond, B, C)" means evaluating
320 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
321 // only if B and C are equal. If B and C are equal then (since we assume
322 // that operands have already been simplified) "select(cond, B, C)" should
323 // have been simplified to the common value of B and C already. Analysing
324 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
325 // for threading over phi nodes.
330 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
331 const TargetData *TD, const DominatorTree *DT) {
332 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
335 /// SimplifyAndInst - Given operands for an And, see if we can
336 /// fold the result. If not, this returns null.
337 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
338 const DominatorTree *DT, unsigned MaxRecurse) {
339 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
340 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
341 Constant *Ops[] = { CLHS, CRHS };
342 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
346 // Canonicalize the constant to the RHS.
351 if (isa<UndefValue>(Op1))
352 return Constant::getNullValue(Op0->getType());
359 if (match(Op1, m_Zero()))
363 if (match(Op1, m_AllOnes()))
366 // A & ~A = ~A & A = 0
367 Value *A = 0, *B = 0;
368 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
369 (match(Op1, m_Not(m_Value(A))) && A == Op0))
370 return Constant::getNullValue(Op0->getType());
373 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
374 (A == Op1 || B == Op1))
378 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
379 (A == Op0 || B == Op0))
382 // (A & B) & A -> A & B
383 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
384 (A == Op1 || B == Op1))
387 // A & (A & B) -> A & B
388 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
389 (A == Op0 || B == Op0))
392 // If the operation is with the result of a select instruction, check whether
393 // operating on either branch of the select always yields the same value.
394 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
395 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
399 // If the operation is with the result of a phi instruction, check whether
400 // operating on all incoming values of the phi always yields the same value.
401 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
402 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
409 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
410 const DominatorTree *DT) {
411 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
414 /// SimplifyOrInst - Given operands for an Or, see if we can
415 /// fold the result. If not, this returns null.
416 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
417 const DominatorTree *DT, unsigned MaxRecurse) {
418 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
419 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
420 Constant *Ops[] = { CLHS, CRHS };
421 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
425 // Canonicalize the constant to the RHS.
430 if (isa<UndefValue>(Op1))
431 return Constant::getAllOnesValue(Op0->getType());
438 if (match(Op1, m_Zero()))
442 if (match(Op1, m_AllOnes()))
445 // A | ~A = ~A | A = -1
446 Value *A = 0, *B = 0;
447 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
448 (match(Op1, m_Not(m_Value(A))) && A == Op0))
449 return Constant::getAllOnesValue(Op0->getType());
452 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
453 (A == Op1 || B == Op1))
457 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
458 (A == Op0 || B == Op0))
461 // (A | B) | A -> A | B
462 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
463 (A == Op1 || B == Op1))
466 // A | (A | B) -> A | B
467 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
468 (A == Op0 || B == Op0))
471 // If the operation is with the result of a select instruction, check whether
472 // operating on either branch of the select always yields the same value.
473 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
474 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
478 // If the operation is with the result of a phi instruction, check whether
479 // operating on all incoming values of the phi always yields the same value.
480 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
481 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
488 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
489 const DominatorTree *DT) {
490 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
493 /// SimplifyXorInst - Given operands for a Xor, see if we can
494 /// fold the result. If not, this returns null.
495 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
496 const DominatorTree *DT, unsigned MaxRecurse) {
497 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
498 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
499 Constant *Ops[] = { CLHS, CRHS };
500 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
504 // Canonicalize the constant to the RHS.
508 // A ^ undef -> undef
509 if (isa<UndefValue>(Op1))
513 if (match(Op1, m_Zero()))
518 return Constant::getNullValue(Op0->getType());
520 // A ^ ~A = ~A ^ A = -1
521 Value *A = 0, *B = 0;
522 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
523 (match(Op1, m_Not(m_Value(A))) && A == Op0))
524 return Constant::getAllOnesValue(Op0->getType());
527 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
528 (A == Op1 || B == Op1))
529 return A == Op1 ? B : A;
532 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
533 (A == Op0 || B == Op0))
534 return A == Op0 ? B : A;
536 // Threading Xor over selects and phi nodes is pointless, so don't bother.
537 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
538 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
539 // only if B and C are equal. If B and C are equal then (since we assume
540 // that operands have already been simplified) "select(cond, B, C)" should
541 // have been simplified to the common value of B and C already. Analysing
542 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
543 // for threading over phi nodes.
548 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
549 const DominatorTree *DT) {
550 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
553 static const Type *GetCompareTy(Value *Op) {
554 return CmpInst::makeCmpResultType(Op->getType());
557 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
558 /// fold the result. If not, this returns null.
559 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
560 const TargetData *TD, const DominatorTree *DT,
561 unsigned MaxRecurse) {
562 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
563 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
565 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
566 if (Constant *CRHS = dyn_cast<Constant>(RHS))
567 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
569 // If we have a constant, make sure it is on the RHS.
571 Pred = CmpInst::getSwappedPredicate(Pred);
574 // ITy - This is the return type of the compare we're considering.
575 const Type *ITy = GetCompareTy(LHS);
577 // icmp X, X -> true/false
578 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
579 // because X could be 0.
580 if (LHS == RHS || isa<UndefValue>(RHS))
581 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
583 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
584 // addresses never equal each other! We already know that Op0 != Op1.
585 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
586 isa<ConstantPointerNull>(LHS)) &&
587 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
588 isa<ConstantPointerNull>(RHS)))
589 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
591 // See if we are doing a comparison with a constant.
592 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
593 // If we have an icmp le or icmp ge instruction, turn it into the
594 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
595 // them being folded in the code below.
598 case ICmpInst::ICMP_ULE:
599 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
600 return ConstantInt::getTrue(CI->getContext());
602 case ICmpInst::ICMP_SLE:
603 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
604 return ConstantInt::getTrue(CI->getContext());
606 case ICmpInst::ICMP_UGE:
607 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
608 return ConstantInt::getTrue(CI->getContext());
610 case ICmpInst::ICMP_SGE:
611 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
612 return ConstantInt::getTrue(CI->getContext());
617 // If the comparison is with the result of a select instruction, check whether
618 // comparing with either branch of the select always yields the same value.
619 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
620 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
623 // If the comparison is with the result of a phi instruction, check whether
624 // doing the compare with each incoming phi value yields a common result.
625 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
626 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
632 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
633 const TargetData *TD, const DominatorTree *DT) {
634 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
637 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
638 /// fold the result. If not, this returns null.
639 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
640 const TargetData *TD, const DominatorTree *DT,
641 unsigned MaxRecurse) {
642 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
643 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
645 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
646 if (Constant *CRHS = dyn_cast<Constant>(RHS))
647 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
649 // If we have a constant, make sure it is on the RHS.
651 Pred = CmpInst::getSwappedPredicate(Pred);
654 // Fold trivial predicates.
655 if (Pred == FCmpInst::FCMP_FALSE)
656 return ConstantInt::get(GetCompareTy(LHS), 0);
657 if (Pred == FCmpInst::FCMP_TRUE)
658 return ConstantInt::get(GetCompareTy(LHS), 1);
660 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
661 return UndefValue::get(GetCompareTy(LHS));
663 // fcmp x,x -> true/false. Not all compares are foldable.
665 if (CmpInst::isTrueWhenEqual(Pred))
666 return ConstantInt::get(GetCompareTy(LHS), 1);
667 if (CmpInst::isFalseWhenEqual(Pred))
668 return ConstantInt::get(GetCompareTy(LHS), 0);
671 // Handle fcmp with constant RHS
672 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
673 // If the constant is a nan, see if we can fold the comparison based on it.
674 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
675 if (CFP->getValueAPF().isNaN()) {
676 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
677 return ConstantInt::getFalse(CFP->getContext());
678 assert(FCmpInst::isUnordered(Pred) &&
679 "Comparison must be either ordered or unordered!");
680 // True if unordered.
681 return ConstantInt::getTrue(CFP->getContext());
683 // Check whether the constant is an infinity.
684 if (CFP->getValueAPF().isInfinity()) {
685 if (CFP->getValueAPF().isNegative()) {
687 case FCmpInst::FCMP_OLT:
688 // No value is ordered and less than negative infinity.
689 return ConstantInt::getFalse(CFP->getContext());
690 case FCmpInst::FCMP_UGE:
691 // All values are unordered with or at least negative infinity.
692 return ConstantInt::getTrue(CFP->getContext());
698 case FCmpInst::FCMP_OGT:
699 // No value is ordered and greater than infinity.
700 return ConstantInt::getFalse(CFP->getContext());
701 case FCmpInst::FCMP_ULE:
702 // All values are unordered with and at most infinity.
703 return ConstantInt::getTrue(CFP->getContext());
712 // If the comparison is with the result of a select instruction, check whether
713 // comparing with either branch of the select always yields the same value.
714 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
715 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
718 // If the comparison is with the result of a phi instruction, check whether
719 // doing the compare with each incoming phi value yields a common result.
720 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
721 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
727 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
728 const TargetData *TD, const DominatorTree *DT) {
729 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
732 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
733 /// the result. If not, this returns null.
734 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
735 const TargetData *TD, const DominatorTree *) {
736 // select true, X, Y -> X
737 // select false, X, Y -> Y
738 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
739 return CB->getZExtValue() ? TrueVal : FalseVal;
741 // select C, X, X -> X
742 if (TrueVal == FalseVal)
745 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
747 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
749 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
750 if (isa<Constant>(TrueVal))
758 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
759 /// fold the result. If not, this returns null.
760 Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
761 const TargetData *TD, const DominatorTree *) {
762 // The type of the GEP pointer operand.
763 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
765 // getelementptr P -> P.
769 if (isa<UndefValue>(Ops[0])) {
770 // Compute the (pointer) type returned by the GEP instruction.
771 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
773 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
774 return UndefValue::get(GEPTy);
778 // getelementptr P, 0 -> P.
779 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
782 // getelementptr P, N -> P if P points to a type of zero size.
784 const Type *Ty = PtrTy->getElementType();
785 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
790 // Check to see if this is constant foldable.
791 for (unsigned i = 0; i != NumOps; ++i)
792 if (!isa<Constant>(Ops[i]))
795 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
796 (Constant *const*)Ops+1, NumOps-1);
799 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
800 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
801 // If all of the PHI's incoming values are the same then replace the PHI node
802 // with the common value.
803 Value *CommonValue = 0;
804 bool HasUndefInput = false;
805 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
806 Value *Incoming = PN->getIncomingValue(i);
807 // If the incoming value is the phi node itself, it can safely be skipped.
808 if (Incoming == PN) continue;
809 if (isa<UndefValue>(Incoming)) {
810 // Remember that we saw an undef value, but otherwise ignore them.
811 HasUndefInput = true;
814 if (CommonValue && Incoming != CommonValue)
815 return 0; // Not the same, bail out.
816 CommonValue = Incoming;
819 // If CommonValue is null then all of the incoming values were either undef or
820 // equal to the phi node itself.
822 return UndefValue::get(PN->getType());
824 // If we have a PHI node like phi(X, undef, X), where X is defined by some
825 // instruction, we cannot return X as the result of the PHI node unless it
826 // dominates the PHI block.
828 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
834 //=== Helper functions for higher up the class hierarchy.
836 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
837 /// fold the result. If not, this returns null.
838 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
839 const TargetData *TD, const DominatorTree *DT,
840 unsigned MaxRecurse) {
842 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
843 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
844 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
845 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
846 /* isNUW */ false, TD, DT,
848 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
849 /* isNUW */ false, TD, DT,
852 if (Constant *CLHS = dyn_cast<Constant>(LHS))
853 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
854 Constant *COps[] = {CLHS, CRHS};
855 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
858 // If the operation is with the result of a select instruction, check whether
859 // operating on either branch of the select always yields the same value.
860 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
861 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
865 // If the operation is with the result of a phi instruction, check whether
866 // operating on all incoming values of the phi always yields the same value.
867 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
868 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
875 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
876 const TargetData *TD, const DominatorTree *DT) {
877 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
880 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
882 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
883 const TargetData *TD, const DominatorTree *DT,
884 unsigned MaxRecurse) {
885 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
886 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
887 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
890 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
891 const TargetData *TD, const DominatorTree *DT) {
892 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
895 /// SimplifyInstruction - See if we can compute a simplified version of this
896 /// instruction. If not, this returns null.
897 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
898 const DominatorTree *DT) {
901 switch (I->getOpcode()) {
903 Result = ConstantFoldInstruction(I, TD);
905 case Instruction::Add:
906 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
907 cast<BinaryOperator>(I)->hasNoSignedWrap(),
908 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
911 case Instruction::Sub:
912 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
913 cast<BinaryOperator>(I)->hasNoSignedWrap(),
914 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
917 case Instruction::And:
918 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
920 case Instruction::Or:
921 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
923 case Instruction::Xor:
924 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
926 case Instruction::ICmp:
927 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
928 I->getOperand(0), I->getOperand(1), TD, DT);
930 case Instruction::FCmp:
931 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
932 I->getOperand(0), I->getOperand(1), TD, DT);
934 case Instruction::Select:
935 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
936 I->getOperand(2), TD, DT);
938 case Instruction::GetElementPtr: {
939 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
940 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
943 case Instruction::PHI:
944 Result = SimplifyPHINode(cast<PHINode>(I), DT);
948 /// If called on unreachable code, the above logic may report that the
949 /// instruction simplified to itself. Make life easier for users by
950 /// detecting that case here, returning a safe value instead.
951 return Result == I ? UndefValue::get(I->getType()) : Result;
954 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
955 /// delete the From instruction. In addition to a basic RAUW, this does a
956 /// recursive simplification of the newly formed instructions. This catches
957 /// things where one simplification exposes other opportunities. This only
958 /// simplifies and deletes scalar operations, it does not change the CFG.
960 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
961 const TargetData *TD,
962 const DominatorTree *DT) {
963 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
965 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
966 // we can know if it gets deleted out from under us or replaced in a
967 // recursive simplification.
968 WeakVH FromHandle(From);
971 while (!From->use_empty()) {
972 // Update the instruction to use the new value.
973 Use &TheUse = From->use_begin().getUse();
974 Instruction *User = cast<Instruction>(TheUse.getUser());
977 // Check to see if the instruction can be folded due to the operand
978 // replacement. For example changing (or X, Y) into (or X, -1) can replace
980 Value *SimplifiedVal;
982 // Sanity check to make sure 'User' doesn't dangle across
983 // SimplifyInstruction.
984 AssertingVH<> UserHandle(User);
986 SimplifiedVal = SimplifyInstruction(User, TD, DT);
987 if (SimplifiedVal == 0) continue;
990 // Recursively simplify this user to the new value.
991 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
992 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
995 assert(ToHandle && "To value deleted by recursive simplification?");
997 // If the recursive simplification ended up revisiting and deleting
998 // 'From' then we're done.
1003 // If 'From' has value handles referring to it, do a real RAUW to update them.
1004 From->replaceAllUsesWith(To);
1006 From->eraseFromParent();