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);
420 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
421 // Does "cmp TV, RHS" simplify?
422 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
424 // It does! Does "cmp FV, RHS" simplify?
425 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
427 // It does! If they simplified to the same value, then use it as the
428 // result of the original comparison.
431 Value *Cond = SI->getCondition();
432 // If the false value simplified to false, then the result of the compare
433 // is equal to "Cond && TCmp". This also catches the case when the false
434 // value simplified to false and the true value to true, returning "Cond".
435 if (match(FCmp, m_Zero()))
436 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
438 // If the true value simplified to true, then the result of the compare
439 // is equal to "Cond || FCmp".
440 if (match(TCmp, m_One()))
441 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
443 // Finally, if the false value simplified to true and the true value to
444 // false, then the result of the compare is equal to "!Cond".
445 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
447 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
456 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
457 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
458 /// it on the incoming phi values yields the same result for every value. If so
459 /// returns the common value, otherwise returns null.
460 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
461 const TargetData *TD, const DominatorTree *DT,
462 unsigned MaxRecurse) {
463 // Recursion is always used, so bail out at once if we already hit the limit.
468 if (isa<PHINode>(LHS)) {
469 PI = cast<PHINode>(LHS);
470 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
471 if (!ValueDominatesPHI(RHS, PI, DT))
474 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
475 PI = cast<PHINode>(RHS);
476 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
477 if (!ValueDominatesPHI(LHS, PI, DT))
481 // Evaluate the BinOp on the incoming phi values.
482 Value *CommonValue = 0;
483 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
484 Value *Incoming = PI->getIncomingValue(i);
485 // If the incoming value is the phi node itself, it can safely be skipped.
486 if (Incoming == PI) continue;
487 Value *V = PI == LHS ?
488 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
489 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
490 // If the operation failed to simplify, or simplified to a different value
491 // to previously, then give up.
492 if (!V || (CommonValue && V != CommonValue))
500 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
501 /// try to simplify the comparison by seeing whether comparing with all of the
502 /// incoming phi values yields the same result every time. If so returns the
503 /// common result, otherwise returns null.
504 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
505 const TargetData *TD, const DominatorTree *DT,
506 unsigned MaxRecurse) {
507 // Recursion is always used, so bail out at once if we already hit the limit.
511 // Make sure the phi is on the LHS.
512 if (!isa<PHINode>(LHS)) {
514 Pred = CmpInst::getSwappedPredicate(Pred);
516 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
517 PHINode *PI = cast<PHINode>(LHS);
519 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
520 if (!ValueDominatesPHI(RHS, PI, DT))
523 // Evaluate the BinOp on the incoming phi values.
524 Value *CommonValue = 0;
525 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
526 Value *Incoming = PI->getIncomingValue(i);
527 // If the incoming value is the phi node itself, it can safely be skipped.
528 if (Incoming == PI) continue;
529 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
530 // If the operation failed to simplify, or simplified to a different value
531 // to previously, then give up.
532 if (!V || (CommonValue && V != CommonValue))
540 /// SimplifyAddInst - Given operands for an Add, see if we can
541 /// fold the result. If not, this returns null.
542 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
543 const TargetData *TD, const DominatorTree *DT,
544 unsigned MaxRecurse) {
545 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
546 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
547 Constant *Ops[] = { CLHS, CRHS };
548 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
552 // Canonicalize the constant to the RHS.
556 // X + undef -> undef
557 if (match(Op1, m_Undef()))
561 if (match(Op1, m_Zero()))
568 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
569 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
572 // X + ~X -> -1 since ~X = -X-1
573 if (match(Op0, m_Not(m_Specific(Op1))) ||
574 match(Op1, m_Not(m_Specific(Op0))))
575 return Constant::getAllOnesValue(Op0->getType());
578 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
579 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
582 // Try some generic simplifications for associative operations.
583 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
587 // Mul distributes over Add. Try some generic simplifications based on this.
588 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
592 // Threading Add over selects and phi nodes is pointless, so don't bother.
593 // Threading over the select in "A + select(cond, B, C)" means evaluating
594 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
595 // only if B and C are equal. If B and C are equal then (since we assume
596 // that operands have already been simplified) "select(cond, B, C)" should
597 // have been simplified to the common value of B and C already. Analysing
598 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
599 // for threading over phi nodes.
604 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
605 const TargetData *TD, const DominatorTree *DT) {
606 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
609 /// SimplifySubInst - Given operands for a Sub, see if we can
610 /// fold the result. If not, this returns null.
611 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
612 const TargetData *TD, const DominatorTree *DT,
613 unsigned MaxRecurse) {
614 if (Constant *CLHS = dyn_cast<Constant>(Op0))
615 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
616 Constant *Ops[] = { CLHS, CRHS };
617 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
621 // X - undef -> undef
622 // undef - X -> undef
623 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
624 return UndefValue::get(Op0->getType());
627 if (match(Op1, m_Zero()))
632 return Constant::getNullValue(Op0->getType());
637 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
638 match(Op0, m_Shl(m_Specific(Op1), m_One())))
641 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
642 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
643 Value *Y = 0, *Z = Op1;
644 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
645 // See if "V === Y - Z" simplifies.
646 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
647 // It does! Now see if "X + V" simplifies.
648 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
650 // It does, we successfully reassociated!
654 // See if "V === X - Z" simplifies.
655 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
656 // It does! Now see if "Y + V" simplifies.
657 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
659 // It does, we successfully reassociated!
665 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
666 // For example, X - (X + 1) -> -1
668 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
669 // See if "V === X - Y" simplifies.
670 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
671 // It does! Now see if "V - Z" simplifies.
672 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
674 // It does, we successfully reassociated!
678 // See if "V === X - Z" simplifies.
679 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
680 // It does! Now see if "V - Y" simplifies.
681 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
683 // It does, we successfully reassociated!
689 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
690 // For example, X - (X - Y) -> Y.
692 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
693 // See if "V === Z - X" simplifies.
694 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
695 // It does! Now see if "V + Y" simplifies.
696 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
698 // It does, we successfully reassociated!
703 // Mul distributes over Sub. Try some generic simplifications based on this.
704 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
709 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
710 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
713 // Threading Sub over selects and phi nodes is pointless, so don't bother.
714 // Threading over the select in "A - select(cond, B, C)" means evaluating
715 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
716 // only if B and C are equal. If B and C are equal then (since we assume
717 // that operands have already been simplified) "select(cond, B, C)" should
718 // have been simplified to the common value of B and C already. Analysing
719 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
720 // for threading over phi nodes.
725 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
726 const TargetData *TD, const DominatorTree *DT) {
727 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
730 /// SimplifyMulInst - Given operands for a Mul, see if we can
731 /// fold the result. If not, this returns null.
732 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
733 const DominatorTree *DT, unsigned MaxRecurse) {
734 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
735 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
736 Constant *Ops[] = { CLHS, CRHS };
737 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
741 // Canonicalize the constant to the RHS.
746 if (match(Op1, m_Undef()))
747 return Constant::getNullValue(Op0->getType());
750 if (match(Op1, m_Zero()))
754 if (match(Op1, m_One()))
757 // (X / Y) * Y -> X if the division is exact.
758 Value *X = 0, *Y = 0;
759 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
760 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
761 BinaryOperator *Div = cast<BinaryOperator>(Y == Op1 ? Op0 : Op1);
767 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
768 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
771 // Try some generic simplifications for associative operations.
772 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
776 // Mul distributes over Add. Try some generic simplifications based on this.
777 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
781 // If the operation is with the result of a select instruction, check whether
782 // operating on either branch of the select always yields the same value.
783 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
784 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
788 // If the operation is with the result of a phi instruction, check whether
789 // operating on all incoming values of the phi always yields the same value.
790 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
791 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
798 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
799 const DominatorTree *DT) {
800 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
803 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
804 /// fold the result. If not, this returns null.
805 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
806 const TargetData *TD, const DominatorTree *DT,
807 unsigned MaxRecurse) {
808 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
809 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
810 Constant *Ops[] = { C0, C1 };
811 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
815 bool isSigned = Opcode == Instruction::SDiv;
817 // X / undef -> undef
818 if (match(Op1, m_Undef()))
822 if (match(Op0, m_Undef()))
823 return Constant::getNullValue(Op0->getType());
825 // 0 / X -> 0, we don't need to preserve faults!
826 if (match(Op0, m_Zero()))
830 if (match(Op1, m_One()))
833 if (Op0->getType()->isIntegerTy(1))
834 // It can't be division by zero, hence it must be division by one.
839 return ConstantInt::get(Op0->getType(), 1);
841 // (X * Y) / Y -> X if the multiplication does not overflow.
842 Value *X = 0, *Y = 0;
843 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
844 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
845 BinaryOperator *Mul = cast<BinaryOperator>(Op0);
846 // If the Mul knows it does not overflow, then we are good to go.
847 if ((isSigned && Mul->hasNoSignedWrap()) ||
848 (!isSigned && Mul->hasNoUnsignedWrap()))
850 // If X has the form X = A / Y then X * Y cannot overflow.
851 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
852 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
856 // (X rem Y) / Y -> 0
857 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
858 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
859 return Constant::getNullValue(Op0->getType());
861 // If the operation is with the result of a select instruction, check whether
862 // operating on either branch of the select always yields the same value.
863 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
864 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
867 // If the operation is with the result of a phi instruction, check whether
868 // operating on all incoming values of the phi always yields the same value.
869 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
870 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
876 /// SimplifySDivInst - Given operands for an SDiv, see if we can
877 /// fold the result. If not, this returns null.
878 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
879 const DominatorTree *DT, unsigned MaxRecurse) {
880 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
886 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
887 const DominatorTree *DT) {
888 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
891 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
892 /// fold the result. If not, this returns null.
893 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
894 const DominatorTree *DT, unsigned MaxRecurse) {
895 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
901 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
902 const DominatorTree *DT) {
903 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
906 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
907 const DominatorTree *, unsigned) {
908 // undef / X -> undef (the undef could be a snan).
909 if (match(Op0, m_Undef()))
912 // X / undef -> undef
913 if (match(Op1, m_Undef()))
919 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
920 const DominatorTree *DT) {
921 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
924 /// SimplifyRem - Given operands for an SRem or URem, see if we can
925 /// fold the result. If not, this returns null.
926 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
927 const TargetData *TD, const DominatorTree *DT,
928 unsigned MaxRecurse) {
929 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
930 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
931 Constant *Ops[] = { C0, C1 };
932 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
936 // X % undef -> undef
937 if (match(Op1, m_Undef()))
941 if (match(Op0, m_Undef()))
942 return Constant::getNullValue(Op0->getType());
944 // 0 % X -> 0, we don't need to preserve faults!
945 if (match(Op0, m_Zero()))
948 // X % 0 -> undef, we don't need to preserve faults!
949 if (match(Op1, m_Zero()))
950 return UndefValue::get(Op0->getType());
953 if (match(Op1, m_One()))
954 return Constant::getNullValue(Op0->getType());
956 if (Op0->getType()->isIntegerTy(1))
957 // It can't be remainder by zero, hence it must be remainder by one.
958 return Constant::getNullValue(Op0->getType());
962 return Constant::getNullValue(Op0->getType());
964 // If the operation is with the result of a select instruction, check whether
965 // operating on either branch of the select always yields the same value.
966 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
967 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
970 // If the operation is with the result of a phi instruction, check whether
971 // operating on all incoming values of the phi always yields the same value.
972 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
973 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
979 /// SimplifySRemInst - Given operands for an SRem, see if we can
980 /// fold the result. If not, this returns null.
981 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
982 const DominatorTree *DT, unsigned MaxRecurse) {
983 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
989 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
990 const DominatorTree *DT) {
991 return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
994 /// SimplifyURemInst - Given operands for a URem, see if we can
995 /// fold the result. If not, this returns null.
996 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
997 const DominatorTree *DT, unsigned MaxRecurse) {
998 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
1004 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1005 const DominatorTree *DT) {
1006 return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
1009 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1010 const DominatorTree *, unsigned) {
1011 // undef % X -> undef (the undef could be a snan).
1012 if (match(Op0, m_Undef()))
1015 // X % undef -> undef
1016 if (match(Op1, m_Undef()))
1022 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1023 const DominatorTree *DT) {
1024 return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1027 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1028 /// fold the result. If not, this returns null.
1029 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1030 const TargetData *TD, const DominatorTree *DT,
1031 unsigned MaxRecurse) {
1032 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1033 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1034 Constant *Ops[] = { C0, C1 };
1035 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
1039 // 0 shift by X -> 0
1040 if (match(Op0, m_Zero()))
1043 // X shift by 0 -> X
1044 if (match(Op1, m_Zero()))
1047 // X shift by undef -> undef because it may shift by the bitwidth.
1048 if (match(Op1, m_Undef()))
1051 // Shifting by the bitwidth or more is undefined.
1052 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1053 if (CI->getValue().getLimitedValue() >=
1054 Op0->getType()->getScalarSizeInBits())
1055 return UndefValue::get(Op0->getType());
1057 // If the operation is with the result of a select instruction, check whether
1058 // operating on either branch of the select always yields the same value.
1059 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1060 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1063 // If the operation is with the result of a phi instruction, check whether
1064 // operating on all incoming values of the phi always yields the same value.
1065 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1066 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1072 /// SimplifyShlInst - Given operands for an Shl, see if we can
1073 /// fold the result. If not, this returns null.
1074 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1075 const TargetData *TD, const DominatorTree *DT,
1076 unsigned MaxRecurse) {
1077 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1081 if (match(Op0, m_Undef()))
1082 return Constant::getNullValue(Op0->getType());
1084 // (X >> A) << A -> X
1086 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1087 cast<PossiblyExactOperator>(Op0)->isExact())
1092 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1093 const TargetData *TD, const DominatorTree *DT) {
1094 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
1097 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1098 /// fold the result. If not, this returns null.
1099 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1100 const TargetData *TD, const DominatorTree *DT,
1101 unsigned MaxRecurse) {
1102 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1106 if (match(Op0, m_Undef()))
1107 return Constant::getNullValue(Op0->getType());
1109 // (X << A) >> A -> X
1111 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1112 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1118 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1119 const TargetData *TD, const DominatorTree *DT) {
1120 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1123 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1124 /// fold the result. If not, this returns null.
1125 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1126 const TargetData *TD, const DominatorTree *DT,
1127 unsigned MaxRecurse) {
1128 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1131 // all ones >>a X -> all ones
1132 if (match(Op0, m_AllOnes()))
1135 // undef >>a X -> all ones
1136 if (match(Op0, m_Undef()))
1137 return Constant::getAllOnesValue(Op0->getType());
1139 // (X << A) >> A -> X
1141 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1142 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1148 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1149 const TargetData *TD, const DominatorTree *DT) {
1150 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1153 /// SimplifyAndInst - Given operands for an And, see if we can
1154 /// fold the result. If not, this returns null.
1155 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1156 const DominatorTree *DT, unsigned MaxRecurse) {
1157 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1158 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1159 Constant *Ops[] = { CLHS, CRHS };
1160 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1164 // Canonicalize the constant to the RHS.
1165 std::swap(Op0, Op1);
1169 if (match(Op1, m_Undef()))
1170 return Constant::getNullValue(Op0->getType());
1177 if (match(Op1, m_Zero()))
1181 if (match(Op1, m_AllOnes()))
1184 // A & ~A = ~A & A = 0
1185 if (match(Op0, m_Not(m_Specific(Op1))) ||
1186 match(Op1, m_Not(m_Specific(Op0))))
1187 return Constant::getNullValue(Op0->getType());
1190 Value *A = 0, *B = 0;
1191 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1192 (A == Op1 || B == Op1))
1196 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1197 (A == Op0 || B == Op0))
1200 // Try some generic simplifications for associative operations.
1201 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1205 // And distributes over Or. Try some generic simplifications based on this.
1206 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1207 TD, DT, MaxRecurse))
1210 // And distributes over Xor. Try some generic simplifications based on this.
1211 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1212 TD, DT, MaxRecurse))
1215 // Or distributes over And. Try some generic simplifications based on this.
1216 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1217 TD, DT, MaxRecurse))
1220 // If the operation is with the result of a select instruction, check whether
1221 // operating on either branch of the select always yields the same value.
1222 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1223 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
1227 // If the operation is with the result of a phi instruction, check whether
1228 // operating on all incoming values of the phi always yields the same value.
1229 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1230 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
1237 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1238 const DominatorTree *DT) {
1239 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
1242 /// SimplifyOrInst - Given operands for an Or, see if we can
1243 /// fold the result. If not, this returns null.
1244 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1245 const DominatorTree *DT, unsigned MaxRecurse) {
1246 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1247 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1248 Constant *Ops[] = { CLHS, CRHS };
1249 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1253 // Canonicalize the constant to the RHS.
1254 std::swap(Op0, Op1);
1258 if (match(Op1, m_Undef()))
1259 return Constant::getAllOnesValue(Op0->getType());
1266 if (match(Op1, m_Zero()))
1270 if (match(Op1, m_AllOnes()))
1273 // A | ~A = ~A | A = -1
1274 if (match(Op0, m_Not(m_Specific(Op1))) ||
1275 match(Op1, m_Not(m_Specific(Op0))))
1276 return Constant::getAllOnesValue(Op0->getType());
1279 Value *A = 0, *B = 0;
1280 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1281 (A == Op1 || B == Op1))
1285 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1286 (A == Op0 || B == Op0))
1289 // ~(A & ?) | A = -1
1290 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1291 (A == Op1 || B == Op1))
1292 return Constant::getAllOnesValue(Op1->getType());
1294 // A | ~(A & ?) = -1
1295 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1296 (A == Op0 || B == Op0))
1297 return Constant::getAllOnesValue(Op0->getType());
1299 // Try some generic simplifications for associative operations.
1300 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1304 // Or distributes over And. Try some generic simplifications based on this.
1305 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1306 TD, DT, MaxRecurse))
1309 // And distributes over Or. Try some generic simplifications based on this.
1310 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1311 TD, DT, MaxRecurse))
1314 // If the operation is with the result of a select instruction, check whether
1315 // operating on either branch of the select always yields the same value.
1316 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1317 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
1321 // If the operation is with the result of a phi instruction, check whether
1322 // operating on all incoming values of the phi always yields the same value.
1323 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1324 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
1331 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1332 const DominatorTree *DT) {
1333 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
1336 /// SimplifyXorInst - Given operands for a Xor, see if we can
1337 /// fold the result. If not, this returns null.
1338 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1339 const DominatorTree *DT, unsigned MaxRecurse) {
1340 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1341 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1342 Constant *Ops[] = { CLHS, CRHS };
1343 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1347 // Canonicalize the constant to the RHS.
1348 std::swap(Op0, Op1);
1351 // A ^ undef -> undef
1352 if (match(Op1, m_Undef()))
1356 if (match(Op1, m_Zero()))
1361 return Constant::getNullValue(Op0->getType());
1363 // A ^ ~A = ~A ^ A = -1
1364 if (match(Op0, m_Not(m_Specific(Op1))) ||
1365 match(Op1, m_Not(m_Specific(Op0))))
1366 return Constant::getAllOnesValue(Op0->getType());
1368 // Try some generic simplifications for associative operations.
1369 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1373 // And distributes over Xor. Try some generic simplifications based on this.
1374 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1375 TD, DT, MaxRecurse))
1378 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1379 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1380 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1381 // only if B and C are equal. If B and C are equal then (since we assume
1382 // that operands have already been simplified) "select(cond, B, C)" should
1383 // have been simplified to the common value of B and C already. Analysing
1384 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1385 // for threading over phi nodes.
1390 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1391 const DominatorTree *DT) {
1392 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1395 static Type *GetCompareTy(Value *Op) {
1396 return CmpInst::makeCmpResultType(Op->getType());
1399 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1400 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1401 /// otherwise return null. Helper function for analyzing max/min idioms.
1402 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1403 Value *LHS, Value *RHS) {
1404 SelectInst *SI = dyn_cast<SelectInst>(V);
1407 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1410 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1411 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1413 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1414 LHS == CmpRHS && RHS == CmpLHS)
1419 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1420 /// fold the result. If not, this returns null.
1421 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1422 const TargetData *TD, const DominatorTree *DT,
1423 unsigned MaxRecurse) {
1424 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1425 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1427 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1428 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1429 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1431 // If we have a constant, make sure it is on the RHS.
1432 std::swap(LHS, RHS);
1433 Pred = CmpInst::getSwappedPredicate(Pred);
1436 Type *ITy = GetCompareTy(LHS); // The return type.
1437 Type *OpTy = LHS->getType(); // The operand type.
1439 // icmp X, X -> true/false
1440 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1441 // because X could be 0.
1442 if (LHS == RHS || isa<UndefValue>(RHS))
1443 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1445 // Special case logic when the operands have i1 type.
1446 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1447 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1450 case ICmpInst::ICMP_EQ:
1452 if (match(RHS, m_One()))
1455 case ICmpInst::ICMP_NE:
1457 if (match(RHS, m_Zero()))
1460 case ICmpInst::ICMP_UGT:
1462 if (match(RHS, m_Zero()))
1465 case ICmpInst::ICMP_UGE:
1467 if (match(RHS, m_One()))
1470 case ICmpInst::ICMP_SLT:
1472 if (match(RHS, m_Zero()))
1475 case ICmpInst::ICMP_SLE:
1477 if (match(RHS, m_One()))
1483 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1484 // different addresses, and what's more the address of a stack variable is
1485 // never null or equal to the address of a global. Note that generalizing
1486 // to the case where LHS is a global variable address or null is pointless,
1487 // since if both LHS and RHS are constants then we already constant folded
1488 // the compare, and if only one of them is then we moved it to RHS already.
1489 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1490 isa<ConstantPointerNull>(RHS)))
1491 // We already know that LHS != RHS.
1492 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1494 // If we are comparing with zero then try hard since this is a common case.
1495 if (match(RHS, m_Zero())) {
1496 bool LHSKnownNonNegative, LHSKnownNegative;
1499 assert(false && "Unknown ICmp predicate!");
1500 case ICmpInst::ICMP_ULT:
1501 return getFalse(ITy);
1502 case ICmpInst::ICMP_UGE:
1503 return getTrue(ITy);
1504 case ICmpInst::ICMP_EQ:
1505 case ICmpInst::ICMP_ULE:
1506 if (isKnownNonZero(LHS, TD))
1507 return getFalse(ITy);
1509 case ICmpInst::ICMP_NE:
1510 case ICmpInst::ICMP_UGT:
1511 if (isKnownNonZero(LHS, TD))
1512 return getTrue(ITy);
1514 case ICmpInst::ICMP_SLT:
1515 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1516 if (LHSKnownNegative)
1517 return getTrue(ITy);
1518 if (LHSKnownNonNegative)
1519 return getFalse(ITy);
1521 case ICmpInst::ICMP_SLE:
1522 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1523 if (LHSKnownNegative)
1524 return getTrue(ITy);
1525 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1526 return getFalse(ITy);
1528 case ICmpInst::ICMP_SGE:
1529 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1530 if (LHSKnownNegative)
1531 return getFalse(ITy);
1532 if (LHSKnownNonNegative)
1533 return getTrue(ITy);
1535 case ICmpInst::ICMP_SGT:
1536 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1537 if (LHSKnownNegative)
1538 return getFalse(ITy);
1539 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1540 return getTrue(ITy);
1545 // See if we are doing a comparison with a constant integer.
1546 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1547 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1548 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1549 if (RHS_CR.isEmptySet())
1550 return ConstantInt::getFalse(CI->getContext());
1551 if (RHS_CR.isFullSet())
1552 return ConstantInt::getTrue(CI->getContext());
1554 // Many binary operators with constant RHS have easy to compute constant
1555 // range. Use them to check whether the comparison is a tautology.
1556 uint32_t Width = CI->getBitWidth();
1557 APInt Lower = APInt(Width, 0);
1558 APInt Upper = APInt(Width, 0);
1560 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1561 // 'urem x, CI2' produces [0, CI2).
1562 Upper = CI2->getValue();
1563 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1564 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1565 Upper = CI2->getValue().abs();
1566 Lower = (-Upper) + 1;
1567 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1568 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1569 APInt NegOne = APInt::getAllOnesValue(Width);
1571 Upper = NegOne.udiv(CI2->getValue()) + 1;
1572 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1573 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1574 APInt IntMin = APInt::getSignedMinValue(Width);
1575 APInt IntMax = APInt::getSignedMaxValue(Width);
1576 APInt Val = CI2->getValue().abs();
1577 if (!Val.isMinValue()) {
1578 Lower = IntMin.sdiv(Val);
1579 Upper = IntMax.sdiv(Val) + 1;
1581 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1582 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1583 APInt NegOne = APInt::getAllOnesValue(Width);
1584 if (CI2->getValue().ult(Width))
1585 Upper = NegOne.lshr(CI2->getValue()) + 1;
1586 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1587 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1588 APInt IntMin = APInt::getSignedMinValue(Width);
1589 APInt IntMax = APInt::getSignedMaxValue(Width);
1590 if (CI2->getValue().ult(Width)) {
1591 Lower = IntMin.ashr(CI2->getValue());
1592 Upper = IntMax.ashr(CI2->getValue()) + 1;
1594 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1595 // 'or x, CI2' produces [CI2, UINT_MAX].
1596 Lower = CI2->getValue();
1597 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1598 // 'and x, CI2' produces [0, CI2].
1599 Upper = CI2->getValue() + 1;
1601 if (Lower != Upper) {
1602 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1603 if (RHS_CR.contains(LHS_CR))
1604 return ConstantInt::getTrue(RHS->getContext());
1605 if (RHS_CR.inverse().contains(LHS_CR))
1606 return ConstantInt::getFalse(RHS->getContext());
1610 // Compare of cast, for example (zext X) != 0 -> X != 0
1611 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1612 Instruction *LI = cast<CastInst>(LHS);
1613 Value *SrcOp = LI->getOperand(0);
1614 Type *SrcTy = SrcOp->getType();
1615 Type *DstTy = LI->getType();
1617 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1618 // if the integer type is the same size as the pointer type.
1619 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1620 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1621 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1622 // Transfer the cast to the constant.
1623 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1624 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1625 TD, DT, MaxRecurse-1))
1627 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1628 if (RI->getOperand(0)->getType() == SrcTy)
1629 // Compare without the cast.
1630 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1631 TD, DT, MaxRecurse-1))
1636 if (isa<ZExtInst>(LHS)) {
1637 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1639 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1640 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1641 // Compare X and Y. Note that signed predicates become unsigned.
1642 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1643 SrcOp, RI->getOperand(0), TD, DT,
1647 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1648 // too. If not, then try to deduce the result of the comparison.
1649 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1650 // Compute the constant that would happen if we truncated to SrcTy then
1651 // reextended to DstTy.
1652 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1653 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1655 // If the re-extended constant didn't change then this is effectively
1656 // also a case of comparing two zero-extended values.
1657 if (RExt == CI && MaxRecurse)
1658 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1659 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1662 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1663 // there. Use this to work out the result of the comparison.
1667 assert(false && "Unknown ICmp predicate!");
1669 case ICmpInst::ICMP_EQ:
1670 case ICmpInst::ICMP_UGT:
1671 case ICmpInst::ICMP_UGE:
1672 return ConstantInt::getFalse(CI->getContext());
1674 case ICmpInst::ICMP_NE:
1675 case ICmpInst::ICMP_ULT:
1676 case ICmpInst::ICMP_ULE:
1677 return ConstantInt::getTrue(CI->getContext());
1679 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1680 // is non-negative then LHS <s RHS.
1681 case ICmpInst::ICMP_SGT:
1682 case ICmpInst::ICMP_SGE:
1683 return CI->getValue().isNegative() ?
1684 ConstantInt::getTrue(CI->getContext()) :
1685 ConstantInt::getFalse(CI->getContext());
1687 case ICmpInst::ICMP_SLT:
1688 case ICmpInst::ICMP_SLE:
1689 return CI->getValue().isNegative() ?
1690 ConstantInt::getFalse(CI->getContext()) :
1691 ConstantInt::getTrue(CI->getContext());
1697 if (isa<SExtInst>(LHS)) {
1698 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1700 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1701 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1702 // Compare X and Y. Note that the predicate does not change.
1703 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1704 TD, DT, MaxRecurse-1))
1707 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1708 // too. If not, then try to deduce the result of the comparison.
1709 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1710 // Compute the constant that would happen if we truncated to SrcTy then
1711 // reextended to DstTy.
1712 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1713 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1715 // If the re-extended constant didn't change then this is effectively
1716 // also a case of comparing two sign-extended values.
1717 if (RExt == CI && MaxRecurse)
1718 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1722 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1723 // bits there. Use this to work out the result of the comparison.
1727 assert(false && "Unknown ICmp predicate!");
1728 case ICmpInst::ICMP_EQ:
1729 return ConstantInt::getFalse(CI->getContext());
1730 case ICmpInst::ICMP_NE:
1731 return ConstantInt::getTrue(CI->getContext());
1733 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1735 case ICmpInst::ICMP_SGT:
1736 case ICmpInst::ICMP_SGE:
1737 return CI->getValue().isNegative() ?
1738 ConstantInt::getTrue(CI->getContext()) :
1739 ConstantInt::getFalse(CI->getContext());
1740 case ICmpInst::ICMP_SLT:
1741 case ICmpInst::ICMP_SLE:
1742 return CI->getValue().isNegative() ?
1743 ConstantInt::getFalse(CI->getContext()) :
1744 ConstantInt::getTrue(CI->getContext());
1746 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1748 case ICmpInst::ICMP_UGT:
1749 case ICmpInst::ICMP_UGE:
1750 // Comparison is true iff the LHS <s 0.
1752 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1753 Constant::getNullValue(SrcTy),
1754 TD, DT, MaxRecurse-1))
1757 case ICmpInst::ICMP_ULT:
1758 case ICmpInst::ICMP_ULE:
1759 // Comparison is true iff the LHS >=s 0.
1761 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1762 Constant::getNullValue(SrcTy),
1763 TD, DT, MaxRecurse-1))
1772 // Special logic for binary operators.
1773 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1774 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1775 if (MaxRecurse && (LBO || RBO)) {
1776 // Analyze the case when either LHS or RHS is an add instruction.
1777 Value *A = 0, *B = 0, *C = 0, *D = 0;
1778 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1779 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1780 if (LBO && LBO->getOpcode() == Instruction::Add) {
1781 A = LBO->getOperand(0); B = LBO->getOperand(1);
1782 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1783 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1784 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1786 if (RBO && RBO->getOpcode() == Instruction::Add) {
1787 C = RBO->getOperand(0); D = RBO->getOperand(1);
1788 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1789 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1790 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1793 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1794 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1795 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1796 Constant::getNullValue(RHS->getType()),
1797 TD, DT, MaxRecurse-1))
1800 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1801 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1802 if (Value *V = SimplifyICmpInst(Pred,
1803 Constant::getNullValue(LHS->getType()),
1804 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1807 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1808 if (A && C && (A == C || A == D || B == C || B == D) &&
1809 NoLHSWrapProblem && NoRHSWrapProblem) {
1810 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1811 Value *Y = (A == C || A == D) ? B : A;
1812 Value *Z = (C == A || C == B) ? D : C;
1813 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1818 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1819 bool KnownNonNegative, KnownNegative;
1823 case ICmpInst::ICMP_SGT:
1824 case ICmpInst::ICMP_SGE:
1825 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1826 if (!KnownNonNegative)
1829 case ICmpInst::ICMP_EQ:
1830 case ICmpInst::ICMP_UGT:
1831 case ICmpInst::ICMP_UGE:
1832 return getFalse(ITy);
1833 case ICmpInst::ICMP_SLT:
1834 case ICmpInst::ICMP_SLE:
1835 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1836 if (!KnownNonNegative)
1839 case ICmpInst::ICMP_NE:
1840 case ICmpInst::ICMP_ULT:
1841 case ICmpInst::ICMP_ULE:
1842 return getTrue(ITy);
1845 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1846 bool KnownNonNegative, KnownNegative;
1850 case ICmpInst::ICMP_SGT:
1851 case ICmpInst::ICMP_SGE:
1852 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1853 if (!KnownNonNegative)
1856 case ICmpInst::ICMP_NE:
1857 case ICmpInst::ICMP_UGT:
1858 case ICmpInst::ICMP_UGE:
1859 return getTrue(ITy);
1860 case ICmpInst::ICMP_SLT:
1861 case ICmpInst::ICMP_SLE:
1862 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1863 if (!KnownNonNegative)
1866 case ICmpInst::ICMP_EQ:
1867 case ICmpInst::ICMP_ULT:
1868 case ICmpInst::ICMP_ULE:
1869 return getFalse(ITy);
1873 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1874 LBO->getOperand(1) == RBO->getOperand(1)) {
1875 switch (LBO->getOpcode()) {
1877 case Instruction::UDiv:
1878 case Instruction::LShr:
1879 if (ICmpInst::isSigned(Pred))
1882 case Instruction::SDiv:
1883 case Instruction::AShr:
1884 if (!LBO->isExact() || !RBO->isExact())
1886 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1887 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1890 case Instruction::Shl: {
1891 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
1892 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1895 if (!NSW && ICmpInst::isSigned(Pred))
1897 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1898 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1905 // Simplify comparisons involving max/min.
1907 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1908 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1910 // Signed variants on "max(a,b)>=a -> true".
1911 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1912 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1913 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1914 // We analyze this as smax(A, B) pred A.
1916 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1917 (A == LHS || B == LHS)) {
1918 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1919 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1920 // We analyze this as smax(A, B) swapped-pred A.
1921 P = CmpInst::getSwappedPredicate(Pred);
1922 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1923 (A == RHS || B == RHS)) {
1924 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1925 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1926 // We analyze this as smax(-A, -B) swapped-pred -A.
1927 // Note that we do not need to actually form -A or -B thanks to EqP.
1928 P = CmpInst::getSwappedPredicate(Pred);
1929 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1930 (A == LHS || B == LHS)) {
1931 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1932 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1933 // We analyze this as smax(-A, -B) pred -A.
1934 // Note that we do not need to actually form -A or -B thanks to EqP.
1937 if (P != CmpInst::BAD_ICMP_PREDICATE) {
1938 // Cases correspond to "max(A, B) p A".
1942 case CmpInst::ICMP_EQ:
1943 case CmpInst::ICMP_SLE:
1944 // Equivalent to "A EqP B". This may be the same as the condition tested
1945 // in the max/min; if so, we can just return that.
1946 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
1948 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
1950 // Otherwise, see if "A EqP B" simplifies.
1952 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
1955 case CmpInst::ICMP_NE:
1956 case CmpInst::ICMP_SGT: {
1957 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
1958 // Equivalent to "A InvEqP B". This may be the same as the condition
1959 // tested in the max/min; if so, we can just return that.
1960 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
1962 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
1964 // Otherwise, see if "A InvEqP B" simplifies.
1966 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
1970 case CmpInst::ICMP_SGE:
1972 return getTrue(ITy);
1973 case CmpInst::ICMP_SLT:
1975 return getFalse(ITy);
1979 // Unsigned variants on "max(a,b)>=a -> true".
1980 P = CmpInst::BAD_ICMP_PREDICATE;
1981 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1982 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
1983 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1984 // We analyze this as umax(A, B) pred A.
1986 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
1987 (A == LHS || B == LHS)) {
1988 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
1989 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1990 // We analyze this as umax(A, B) swapped-pred A.
1991 P = CmpInst::getSwappedPredicate(Pred);
1992 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
1993 (A == RHS || B == RHS)) {
1994 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
1995 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
1996 // We analyze this as umax(-A, -B) swapped-pred -A.
1997 // Note that we do not need to actually form -A or -B thanks to EqP.
1998 P = CmpInst::getSwappedPredicate(Pred);
1999 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2000 (A == LHS || B == LHS)) {
2001 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2002 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2003 // We analyze this as umax(-A, -B) pred -A.
2004 // Note that we do not need to actually form -A or -B thanks to EqP.
2007 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2008 // Cases correspond to "max(A, B) p A".
2012 case CmpInst::ICMP_EQ:
2013 case CmpInst::ICMP_ULE:
2014 // Equivalent to "A EqP B". This may be the same as the condition tested
2015 // in the max/min; if so, we can just return that.
2016 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2018 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2020 // Otherwise, see if "A EqP B" simplifies.
2022 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2025 case CmpInst::ICMP_NE:
2026 case CmpInst::ICMP_UGT: {
2027 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2028 // Equivalent to "A InvEqP B". This may be the same as the condition
2029 // tested in the max/min; if so, we can just return that.
2030 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2032 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2034 // Otherwise, see if "A InvEqP B" simplifies.
2036 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2040 case CmpInst::ICMP_UGE:
2042 return getTrue(ITy);
2043 case CmpInst::ICMP_ULT:
2045 return getFalse(ITy);
2049 // Variants on "max(x,y) >= min(x,z)".
2051 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2052 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2053 (A == C || A == D || B == C || B == D)) {
2054 // max(x, ?) pred min(x, ?).
2055 if (Pred == CmpInst::ICMP_SGE)
2057 return getTrue(ITy);
2058 if (Pred == CmpInst::ICMP_SLT)
2060 return getFalse(ITy);
2061 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2062 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2063 (A == C || A == D || B == C || B == D)) {
2064 // min(x, ?) pred max(x, ?).
2065 if (Pred == CmpInst::ICMP_SLE)
2067 return getTrue(ITy);
2068 if (Pred == CmpInst::ICMP_SGT)
2070 return getFalse(ITy);
2071 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2072 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2073 (A == C || A == D || B == C || B == D)) {
2074 // max(x, ?) pred min(x, ?).
2075 if (Pred == CmpInst::ICMP_UGE)
2077 return getTrue(ITy);
2078 if (Pred == CmpInst::ICMP_ULT)
2080 return getFalse(ITy);
2081 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2082 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2083 (A == C || A == D || B == C || B == D)) {
2084 // min(x, ?) pred max(x, ?).
2085 if (Pred == CmpInst::ICMP_ULE)
2087 return getTrue(ITy);
2088 if (Pred == CmpInst::ICMP_UGT)
2090 return getFalse(ITy);
2093 // If the comparison is with the result of a select instruction, check whether
2094 // comparing with either branch of the select always yields the same value.
2095 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2096 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2099 // If the comparison is with the result of a phi instruction, check whether
2100 // doing the compare with each incoming phi value yields a common result.
2101 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2102 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2108 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2109 const TargetData *TD, const DominatorTree *DT) {
2110 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2113 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2114 /// fold the result. If not, this returns null.
2115 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2116 const TargetData *TD, const DominatorTree *DT,
2117 unsigned MaxRecurse) {
2118 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2119 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2121 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2122 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2123 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
2125 // If we have a constant, make sure it is on the RHS.
2126 std::swap(LHS, RHS);
2127 Pred = CmpInst::getSwappedPredicate(Pred);
2130 // Fold trivial predicates.
2131 if (Pred == FCmpInst::FCMP_FALSE)
2132 return ConstantInt::get(GetCompareTy(LHS), 0);
2133 if (Pred == FCmpInst::FCMP_TRUE)
2134 return ConstantInt::get(GetCompareTy(LHS), 1);
2136 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2137 return UndefValue::get(GetCompareTy(LHS));
2139 // fcmp x,x -> true/false. Not all compares are foldable.
2141 if (CmpInst::isTrueWhenEqual(Pred))
2142 return ConstantInt::get(GetCompareTy(LHS), 1);
2143 if (CmpInst::isFalseWhenEqual(Pred))
2144 return ConstantInt::get(GetCompareTy(LHS), 0);
2147 // Handle fcmp with constant RHS
2148 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2149 // If the constant is a nan, see if we can fold the comparison based on it.
2150 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2151 if (CFP->getValueAPF().isNaN()) {
2152 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2153 return ConstantInt::getFalse(CFP->getContext());
2154 assert(FCmpInst::isUnordered(Pred) &&
2155 "Comparison must be either ordered or unordered!");
2156 // True if unordered.
2157 return ConstantInt::getTrue(CFP->getContext());
2159 // Check whether the constant is an infinity.
2160 if (CFP->getValueAPF().isInfinity()) {
2161 if (CFP->getValueAPF().isNegative()) {
2163 case FCmpInst::FCMP_OLT:
2164 // No value is ordered and less than negative infinity.
2165 return ConstantInt::getFalse(CFP->getContext());
2166 case FCmpInst::FCMP_UGE:
2167 // All values are unordered with or at least negative infinity.
2168 return ConstantInt::getTrue(CFP->getContext());
2174 case FCmpInst::FCMP_OGT:
2175 // No value is ordered and greater than infinity.
2176 return ConstantInt::getFalse(CFP->getContext());
2177 case FCmpInst::FCMP_ULE:
2178 // All values are unordered with and at most infinity.
2179 return ConstantInt::getTrue(CFP->getContext());
2188 // If the comparison is with the result of a select instruction, check whether
2189 // comparing with either branch of the select always yields the same value.
2190 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2191 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2194 // If the comparison is with the result of a phi instruction, check whether
2195 // doing the compare with each incoming phi value yields a common result.
2196 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2197 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2203 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2204 const TargetData *TD, const DominatorTree *DT) {
2205 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2208 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2209 /// the result. If not, this returns null.
2210 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2211 const TargetData *TD, const DominatorTree *) {
2212 // select true, X, Y -> X
2213 // select false, X, Y -> Y
2214 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2215 return CB->getZExtValue() ? TrueVal : FalseVal;
2217 // select C, X, X -> X
2218 if (TrueVal == FalseVal)
2221 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2222 if (isa<Constant>(TrueVal))
2226 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2228 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2234 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2235 /// fold the result. If not, this returns null.
2236 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops,
2237 const TargetData *TD, const DominatorTree *) {
2238 // The type of the GEP pointer operand.
2239 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
2241 // getelementptr P -> P.
2242 if (Ops.size() == 1)
2245 if (isa<UndefValue>(Ops[0])) {
2246 // Compute the (pointer) type returned by the GEP instruction.
2247 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2248 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2249 return UndefValue::get(GEPTy);
2252 if (Ops.size() == 2) {
2253 // getelementptr P, 0 -> P.
2254 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2257 // getelementptr P, N -> P if P points to a type of zero size.
2259 Type *Ty = PtrTy->getElementType();
2260 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2265 // Check to see if this is constant foldable.
2266 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2267 if (!isa<Constant>(Ops[i]))
2270 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2273 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2274 /// can fold the result. If not, this returns null.
2275 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2276 ArrayRef<unsigned> Idxs,
2278 const DominatorTree *) {
2279 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2280 if (Constant *CVal = dyn_cast<Constant>(Val))
2281 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2283 // insertvalue x, undef, n -> x
2284 if (match(Val, m_Undef()))
2287 // insertvalue x, (extractvalue y, n), n
2288 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2289 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2290 EV->getIndices() == Idxs) {
2291 // insertvalue undef, (extractvalue y, n), n -> y
2292 if (match(Agg, m_Undef()))
2293 return EV->getAggregateOperand();
2295 // insertvalue y, (extractvalue y, n), n -> y
2296 if (Agg == EV->getAggregateOperand())
2303 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2304 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2305 // If all of the PHI's incoming values are the same then replace the PHI node
2306 // with the common value.
2307 Value *CommonValue = 0;
2308 bool HasUndefInput = false;
2309 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2310 Value *Incoming = PN->getIncomingValue(i);
2311 // If the incoming value is the phi node itself, it can safely be skipped.
2312 if (Incoming == PN) continue;
2313 if (isa<UndefValue>(Incoming)) {
2314 // Remember that we saw an undef value, but otherwise ignore them.
2315 HasUndefInput = true;
2318 if (CommonValue && Incoming != CommonValue)
2319 return 0; // Not the same, bail out.
2320 CommonValue = Incoming;
2323 // If CommonValue is null then all of the incoming values were either undef or
2324 // equal to the phi node itself.
2326 return UndefValue::get(PN->getType());
2328 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2329 // instruction, we cannot return X as the result of the PHI node unless it
2330 // dominates the PHI block.
2332 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2338 //=== Helper functions for higher up the class hierarchy.
2340 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2341 /// fold the result. If not, this returns null.
2342 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2343 const TargetData *TD, const DominatorTree *DT,
2344 unsigned MaxRecurse) {
2346 case Instruction::Add:
2347 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2348 TD, DT, MaxRecurse);
2349 case Instruction::Sub:
2350 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2351 TD, DT, MaxRecurse);
2352 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
2353 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2354 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
2355 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
2356 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2357 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2358 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
2359 case Instruction::Shl:
2360 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2361 TD, DT, MaxRecurse);
2362 case Instruction::LShr:
2363 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2364 case Instruction::AShr:
2365 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2366 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
2367 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
2368 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
2370 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2371 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2372 Constant *COps[] = {CLHS, CRHS};
2373 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD);
2376 // If the operation is associative, try some generic simplifications.
2377 if (Instruction::isAssociative(Opcode))
2378 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2382 // If the operation is with the result of a select instruction, check whether
2383 // operating on either branch of the select always yields the same value.
2384 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2385 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
2389 // If the operation is with the result of a phi instruction, check whether
2390 // operating on all incoming values of the phi always yields the same value.
2391 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2392 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
2399 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2400 const TargetData *TD, const DominatorTree *DT) {
2401 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
2404 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2405 /// fold the result.
2406 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2407 const TargetData *TD, const DominatorTree *DT,
2408 unsigned MaxRecurse) {
2409 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2410 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2411 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2414 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2415 const TargetData *TD, const DominatorTree *DT) {
2416 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2419 /// SimplifyInstruction - See if we can compute a simplified version of this
2420 /// instruction. If not, this returns null.
2421 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2422 const DominatorTree *DT) {
2425 switch (I->getOpcode()) {
2427 Result = ConstantFoldInstruction(I, TD);
2429 case Instruction::Add:
2430 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2431 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2432 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2435 case Instruction::Sub:
2436 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2437 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2438 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2441 case Instruction::Mul:
2442 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2444 case Instruction::SDiv:
2445 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2447 case Instruction::UDiv:
2448 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2450 case Instruction::FDiv:
2451 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2453 case Instruction::SRem:
2454 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2456 case Instruction::URem:
2457 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2459 case Instruction::FRem:
2460 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2462 case Instruction::Shl:
2463 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2464 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2465 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2468 case Instruction::LShr:
2469 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2470 cast<BinaryOperator>(I)->isExact(),
2473 case Instruction::AShr:
2474 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2475 cast<BinaryOperator>(I)->isExact(),
2478 case Instruction::And:
2479 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2481 case Instruction::Or:
2482 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2484 case Instruction::Xor:
2485 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2487 case Instruction::ICmp:
2488 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2489 I->getOperand(0), I->getOperand(1), TD, DT);
2491 case Instruction::FCmp:
2492 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2493 I->getOperand(0), I->getOperand(1), TD, DT);
2495 case Instruction::Select:
2496 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2497 I->getOperand(2), TD, DT);
2499 case Instruction::GetElementPtr: {
2500 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2501 Result = SimplifyGEPInst(Ops, TD, DT);
2504 case Instruction::InsertValue: {
2505 InsertValueInst *IV = cast<InsertValueInst>(I);
2506 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2507 IV->getInsertedValueOperand(),
2508 IV->getIndices(), TD, DT);
2511 case Instruction::PHI:
2512 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2516 /// If called on unreachable code, the above logic may report that the
2517 /// instruction simplified to itself. Make life easier for users by
2518 /// detecting that case here, returning a safe value instead.
2519 return Result == I ? UndefValue::get(I->getType()) : Result;
2522 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2523 /// delete the From instruction. In addition to a basic RAUW, this does a
2524 /// recursive simplification of the newly formed instructions. This catches
2525 /// things where one simplification exposes other opportunities. This only
2526 /// simplifies and deletes scalar operations, it does not change the CFG.
2528 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2529 const TargetData *TD,
2530 const DominatorTree *DT) {
2531 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2533 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2534 // we can know if it gets deleted out from under us or replaced in a
2535 // recursive simplification.
2536 WeakVH FromHandle(From);
2537 WeakVH ToHandle(To);
2539 while (!From->use_empty()) {
2540 // Update the instruction to use the new value.
2541 Use &TheUse = From->use_begin().getUse();
2542 Instruction *User = cast<Instruction>(TheUse.getUser());
2545 // Check to see if the instruction can be folded due to the operand
2546 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2547 // the 'or' with -1.
2548 Value *SimplifiedVal;
2550 // Sanity check to make sure 'User' doesn't dangle across
2551 // SimplifyInstruction.
2552 AssertingVH<> UserHandle(User);
2554 SimplifiedVal = SimplifyInstruction(User, TD, DT);
2555 if (SimplifiedVal == 0) continue;
2558 // Recursively simplify this user to the new value.
2559 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
2560 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2563 assert(ToHandle && "To value deleted by recursive simplification?");
2565 // If the recursive simplification ended up revisiting and deleting
2566 // 'From' then we're done.
2571 // If 'From' has value handles referring to it, do a real RAUW to update them.
2572 From->replaceAllUsesWith(To);
2574 From->eraseFromParent();