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 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
52 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
53 Instruction *I = dyn_cast<Instruction>(V);
55 // Arguments and constants dominate all instructions.
58 // If we have a DominatorTree then do a precise test.
60 return DT->dominates(I, P);
62 // Otherwise, if the instruction is in the entry block, and is not an invoke,
63 // then it obviously dominates all phi nodes.
64 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
71 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
72 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
73 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
74 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
75 /// Returns the simplified value, or null if no simplification was performed.
76 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
77 unsigned OpcToExpand, const TargetData *TD,
78 const DominatorTree *DT, unsigned MaxRecurse) {
79 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
80 // Recursion is always used, so bail out at once if we already hit the limit.
84 // Check whether the expression has the form "(A op' B) op C".
85 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
86 if (Op0->getOpcode() == OpcodeToExpand) {
87 // It does! Try turning it into "(A op C) op' (B op C)".
88 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
89 // Do "A op C" and "B op C" both simplify?
90 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
91 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
92 // They do! Return "L op' R" if it simplifies or is already available.
93 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
94 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
95 && L == B && R == A)) {
99 // Otherwise return "L op' R" if it simplifies.
100 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
108 // Check whether the expression has the form "A op (B op' C)".
109 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
110 if (Op1->getOpcode() == OpcodeToExpand) {
111 // It does! Try turning it into "(A op B) op' (A op C)".
112 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
113 // Do "A op B" and "A op C" both simplify?
114 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
115 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
116 // They do! Return "L op' R" if it simplifies or is already available.
117 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
118 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
119 && L == C && R == B)) {
123 // Otherwise return "L op' R" if it simplifies.
124 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
135 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
136 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
137 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
138 /// Returns the simplified value, or null if no simplification was performed.
139 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
140 unsigned OpcToExtract, const TargetData *TD,
141 const DominatorTree *DT, unsigned MaxRecurse) {
142 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
143 // Recursion is always used, so bail out at once if we already hit the limit.
147 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
148 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
150 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
151 !Op1 || Op1->getOpcode() != OpcodeToExtract)
154 // The expression has the form "(A op' B) op (C op' D)".
155 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
156 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
158 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
159 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
160 // commutative case, "(A op' B) op (C op' A)"?
161 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
162 Value *DD = A == C ? D : C;
163 // Form "A op' (B op DD)" if it simplifies completely.
164 // Does "B op DD" simplify?
165 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
166 // It does! Return "A op' V" if it simplifies or is already available.
167 // If V equals B then "A op' V" is just the LHS. If V equals DD then
168 // "A op' V" is just the RHS.
169 if (V == B || V == DD) {
171 return V == B ? LHS : RHS;
173 // Otherwise return "A op' V" if it simplifies.
174 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
181 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
182 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
183 // commutative case, "(A op' B) op (B op' D)"?
184 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
185 Value *CC = B == D ? C : D;
186 // Form "(A op CC) op' B" if it simplifies completely..
187 // Does "A op CC" simplify?
188 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
189 // It does! Return "V op' B" if it simplifies or is already available.
190 // If V equals A then "V op' B" is just the LHS. If V equals CC then
191 // "V op' B" is just the RHS.
192 if (V == A || V == CC) {
194 return V == A ? LHS : RHS;
196 // Otherwise return "V op' B" if it simplifies.
197 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
207 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
208 /// operations. Returns the simpler value, or null if none was found.
209 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
210 const TargetData *TD,
211 const DominatorTree *DT,
212 unsigned MaxRecurse) {
213 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
214 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
216 // Recursion is always used, so bail out at once if we already hit the limit.
220 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
221 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
223 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
224 if (Op0 && Op0->getOpcode() == Opcode) {
225 Value *A = Op0->getOperand(0);
226 Value *B = Op0->getOperand(1);
229 // Does "B op C" simplify?
230 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
231 // It does! Return "A op V" if it simplifies or is already available.
232 // If V equals B then "A op V" is just the LHS.
233 if (V == B) return LHS;
234 // Otherwise return "A op V" if it simplifies.
235 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
242 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
243 if (Op1 && Op1->getOpcode() == Opcode) {
245 Value *B = Op1->getOperand(0);
246 Value *C = Op1->getOperand(1);
248 // Does "A op B" simplify?
249 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
250 // It does! Return "V op C" if it simplifies or is already available.
251 // If V equals B then "V op C" is just the RHS.
252 if (V == B) return RHS;
253 // Otherwise return "V op C" if it simplifies.
254 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
261 // The remaining transforms require commutativity as well as associativity.
262 if (!Instruction::isCommutative(Opcode))
265 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
266 if (Op0 && Op0->getOpcode() == Opcode) {
267 Value *A = Op0->getOperand(0);
268 Value *B = Op0->getOperand(1);
271 // Does "C op A" simplify?
272 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
273 // It does! Return "V op B" if it simplifies or is already available.
274 // If V equals A then "V op B" is just the LHS.
275 if (V == A) return LHS;
276 // Otherwise return "V op B" if it simplifies.
277 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
284 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
285 if (Op1 && Op1->getOpcode() == Opcode) {
287 Value *B = Op1->getOperand(0);
288 Value *C = Op1->getOperand(1);
290 // Does "C op A" simplify?
291 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
292 // It does! Return "B op V" if it simplifies or is already available.
293 // If V equals C then "B op V" is just the RHS.
294 if (V == C) return RHS;
295 // Otherwise return "B op V" if it simplifies.
296 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
306 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
307 /// instruction as an operand, try to simplify the binop by seeing whether
308 /// evaluating it on both branches of the select results in the same value.
309 /// Returns the common value if so, otherwise returns null.
310 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
311 const TargetData *TD,
312 const DominatorTree *DT,
313 unsigned MaxRecurse) {
314 // Recursion is always used, so bail out at once if we already hit the limit.
319 if (isa<SelectInst>(LHS)) {
320 SI = cast<SelectInst>(LHS);
322 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
323 SI = cast<SelectInst>(RHS);
326 // Evaluate the BinOp on the true and false branches of the select.
330 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
331 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
333 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
334 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
337 // If they simplified to the same value, then return the common value.
338 // If they both failed to simplify then return null.
342 // If one branch simplified to undef, return the other one.
343 if (TV && isa<UndefValue>(TV))
345 if (FV && isa<UndefValue>(FV))
348 // If applying the operation did not change the true and false select values,
349 // then the result of the binop is the select itself.
350 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
353 // If one branch simplified and the other did not, and the simplified
354 // value is equal to the unsimplified one, return the simplified value.
355 // For example, select (cond, X, X & Z) & Z -> X & Z.
356 if ((FV && !TV) || (TV && !FV)) {
357 // Check that the simplified value has the form "X op Y" where "op" is the
358 // same as the original operation.
359 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
360 if (Simplified && Simplified->getOpcode() == Opcode) {
361 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
362 // We already know that "op" is the same as for the simplified value. See
363 // if the operands match too. If so, return the simplified value.
364 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
365 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
366 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
367 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
368 Simplified->getOperand(1) == UnsimplifiedRHS)
370 if (Simplified->isCommutative() &&
371 Simplified->getOperand(1) == UnsimplifiedLHS &&
372 Simplified->getOperand(0) == UnsimplifiedRHS)
380 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
381 /// try to simplify the comparison by seeing whether both branches of the select
382 /// result in the same value. Returns the common value if so, otherwise returns
384 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
385 Value *RHS, const TargetData *TD,
386 const DominatorTree *DT,
387 unsigned MaxRecurse) {
388 // Recursion is always used, so bail out at once if we already hit the limit.
392 // Make sure the select is on the LHS.
393 if (!isa<SelectInst>(LHS)) {
395 Pred = CmpInst::getSwappedPredicate(Pred);
397 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
398 SelectInst *SI = cast<SelectInst>(LHS);
400 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
401 // Does "cmp TV, RHS" simplify?
402 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
404 // It does! Does "cmp FV, RHS" simplify?
405 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
407 // It does! If they simplified to the same value, then use it as the
408 // result of the original comparison.
411 Value *Cond = SI->getCondition();
412 // If the false value simplified to false, then the result of the compare
413 // is equal to "Cond && TCmp". This also catches the case when the false
414 // value simplified to false and the true value to true, returning "Cond".
415 if (match(FCmp, m_Zero()))
416 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
418 // If the true value simplified to true, then the result of the compare
419 // is equal to "Cond || FCmp".
420 if (match(TCmp, m_One()))
421 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
423 // Finally, if the false value simplified to true and the true value to
424 // false, then the result of the compare is equal to "!Cond".
425 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
427 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
436 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
437 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
438 /// it on the incoming phi values yields the same result for every value. If so
439 /// returns the common value, otherwise returns null.
440 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
441 const TargetData *TD, const DominatorTree *DT,
442 unsigned MaxRecurse) {
443 // Recursion is always used, so bail out at once if we already hit the limit.
448 if (isa<PHINode>(LHS)) {
449 PI = cast<PHINode>(LHS);
450 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
451 if (!ValueDominatesPHI(RHS, PI, DT))
454 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
455 PI = cast<PHINode>(RHS);
456 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
457 if (!ValueDominatesPHI(LHS, PI, DT))
461 // Evaluate the BinOp on the incoming phi values.
462 Value *CommonValue = 0;
463 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
464 Value *Incoming = PI->getIncomingValue(i);
465 // If the incoming value is the phi node itself, it can safely be skipped.
466 if (Incoming == PI) continue;
467 Value *V = PI == LHS ?
468 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
469 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
470 // If the operation failed to simplify, or simplified to a different value
471 // to previously, then give up.
472 if (!V || (CommonValue && V != CommonValue))
480 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
481 /// try to simplify the comparison by seeing whether comparing with all of the
482 /// incoming phi values yields the same result every time. If so returns the
483 /// common result, otherwise returns null.
484 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
485 const TargetData *TD, const DominatorTree *DT,
486 unsigned MaxRecurse) {
487 // Recursion is always used, so bail out at once if we already hit the limit.
491 // Make sure the phi is on the LHS.
492 if (!isa<PHINode>(LHS)) {
494 Pred = CmpInst::getSwappedPredicate(Pred);
496 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
497 PHINode *PI = cast<PHINode>(LHS);
499 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
500 if (!ValueDominatesPHI(RHS, PI, DT))
503 // Evaluate the BinOp on the incoming phi values.
504 Value *CommonValue = 0;
505 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
506 Value *Incoming = PI->getIncomingValue(i);
507 // If the incoming value is the phi node itself, it can safely be skipped.
508 if (Incoming == PI) continue;
509 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
510 // If the operation failed to simplify, or simplified to a different value
511 // to previously, then give up.
512 if (!V || (CommonValue && V != CommonValue))
520 /// SimplifyAddInst - Given operands for an Add, see if we can
521 /// fold the result. If not, this returns null.
522 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
523 const TargetData *TD, const DominatorTree *DT,
524 unsigned MaxRecurse) {
525 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
526 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
527 Constant *Ops[] = { CLHS, CRHS };
528 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
532 // Canonicalize the constant to the RHS.
536 // X + undef -> undef
537 if (match(Op1, m_Undef()))
541 if (match(Op1, m_Zero()))
548 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
549 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
552 // X + ~X -> -1 since ~X = -X-1
553 if (match(Op0, m_Not(m_Specific(Op1))) ||
554 match(Op1, m_Not(m_Specific(Op0))))
555 return Constant::getAllOnesValue(Op0->getType());
558 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
559 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
562 // Try some generic simplifications for associative operations.
563 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
567 // Mul distributes over Add. Try some generic simplifications based on this.
568 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
572 // Threading Add over selects and phi nodes is pointless, so don't bother.
573 // Threading over the select in "A + select(cond, B, C)" means evaluating
574 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
575 // only if B and C are equal. If B and C are equal then (since we assume
576 // that operands have already been simplified) "select(cond, B, C)" should
577 // have been simplified to the common value of B and C already. Analysing
578 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
579 // for threading over phi nodes.
584 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
585 const TargetData *TD, const DominatorTree *DT) {
586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
589 /// SimplifySubInst - Given operands for a Sub, see if we can
590 /// fold the result. If not, this returns null.
591 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
592 const TargetData *TD, const DominatorTree *DT,
593 unsigned MaxRecurse) {
594 if (Constant *CLHS = dyn_cast<Constant>(Op0))
595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596 Constant *Ops[] = { CLHS, CRHS };
597 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
601 // X - undef -> undef
602 // undef - X -> undef
603 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
604 return UndefValue::get(Op0->getType());
607 if (match(Op1, m_Zero()))
612 return Constant::getNullValue(Op0->getType());
617 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
618 match(Op0, m_Shl(m_Specific(Op1), m_One())))
621 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
622 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
623 Value *Y = 0, *Z = Op1;
624 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
625 // See if "V === Y - Z" simplifies.
626 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
627 // It does! Now see if "X + V" simplifies.
628 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
630 // It does, we successfully reassociated!
634 // See if "V === X - Z" simplifies.
635 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
636 // It does! Now see if "Y + V" simplifies.
637 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
639 // It does, we successfully reassociated!
645 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
646 // For example, X - (X + 1) -> -1
648 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
649 // See if "V === X - Y" simplifies.
650 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
651 // It does! Now see if "V - Z" simplifies.
652 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
654 // It does, we successfully reassociated!
658 // See if "V === X - Z" simplifies.
659 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
660 // It does! Now see if "V - Y" simplifies.
661 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
663 // It does, we successfully reassociated!
669 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
670 // For example, X - (X - Y) -> Y.
672 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
673 // See if "V === Z - X" simplifies.
674 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
675 // It does! Now see if "V + Y" simplifies.
676 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
678 // It does, we successfully reassociated!
683 // Mul distributes over Sub. Try some generic simplifications based on this.
684 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
689 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
690 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
693 // Threading Sub over selects and phi nodes is pointless, so don't bother.
694 // Threading over the select in "A - select(cond, B, C)" means evaluating
695 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
696 // only if B and C are equal. If B and C are equal then (since we assume
697 // that operands have already been simplified) "select(cond, B, C)" should
698 // have been simplified to the common value of B and C already. Analysing
699 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
700 // for threading over phi nodes.
705 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
706 const TargetData *TD, const DominatorTree *DT) {
707 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
710 /// SimplifyMulInst - Given operands for a Mul, see if we can
711 /// fold the result. If not, this returns null.
712 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
713 const DominatorTree *DT, unsigned MaxRecurse) {
714 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
715 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
716 Constant *Ops[] = { CLHS, CRHS };
717 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
721 // Canonicalize the constant to the RHS.
726 if (match(Op1, m_Undef()))
727 return Constant::getNullValue(Op0->getType());
730 if (match(Op1, m_Zero()))
734 if (match(Op1, m_One()))
737 // (X / Y) * Y -> X if the division is exact.
738 Value *X = 0, *Y = 0;
739 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
740 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
741 BinaryOperator *Div = cast<BinaryOperator>(Y == Op1 ? Op0 : Op1);
747 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
748 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
751 // Try some generic simplifications for associative operations.
752 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
756 // Mul distributes over Add. Try some generic simplifications based on this.
757 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
761 // If the operation is with the result of a select instruction, check whether
762 // operating on either branch of the select always yields the same value.
763 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
764 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
768 // If the operation is with the result of a phi instruction, check whether
769 // operating on all incoming values of the phi always yields the same value.
770 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
771 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
778 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
779 const DominatorTree *DT) {
780 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
783 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
784 /// fold the result. If not, this returns null.
785 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
786 const TargetData *TD, const DominatorTree *DT,
787 unsigned MaxRecurse) {
788 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
789 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
790 Constant *Ops[] = { C0, C1 };
791 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
795 bool isSigned = Opcode == Instruction::SDiv;
797 // X / undef -> undef
798 if (match(Op1, m_Undef()))
802 if (match(Op0, m_Undef()))
803 return Constant::getNullValue(Op0->getType());
805 // 0 / X -> 0, we don't need to preserve faults!
806 if (match(Op0, m_Zero()))
810 if (match(Op1, m_One()))
813 if (Op0->getType()->isIntegerTy(1))
814 // It can't be division by zero, hence it must be division by one.
819 return ConstantInt::get(Op0->getType(), 1);
821 // (X * Y) / Y -> X if the multiplication does not overflow.
822 Value *X = 0, *Y = 0;
823 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
824 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
825 BinaryOperator *Mul = cast<BinaryOperator>(Op0);
826 // If the Mul knows it does not overflow, then we are good to go.
827 if ((isSigned && Mul->hasNoSignedWrap()) ||
828 (!isSigned && Mul->hasNoUnsignedWrap()))
830 // If X has the form X = A / Y then X * Y cannot overflow.
831 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
832 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
836 // (X rem Y) / Y -> 0
837 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
838 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
839 return Constant::getNullValue(Op0->getType());
841 // If the operation is with the result of a select instruction, check whether
842 // operating on either branch of the select always yields the same value.
843 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
844 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
847 // If the operation is with the result of a phi instruction, check whether
848 // operating on all incoming values of the phi always yields the same value.
849 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
850 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
856 /// SimplifySDivInst - Given operands for an SDiv, see if we can
857 /// fold the result. If not, this returns null.
858 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
859 const DominatorTree *DT, unsigned MaxRecurse) {
860 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
866 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
867 const DominatorTree *DT) {
868 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
871 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
872 /// fold the result. If not, this returns null.
873 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
874 const DominatorTree *DT, unsigned MaxRecurse) {
875 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
881 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
882 const DominatorTree *DT) {
883 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
886 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
887 const DominatorTree *, unsigned) {
888 // undef / X -> undef (the undef could be a snan).
889 if (match(Op0, m_Undef()))
892 // X / undef -> undef
893 if (match(Op1, m_Undef()))
899 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
900 const DominatorTree *DT) {
901 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
904 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
905 /// fold the result. If not, this returns null.
906 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
907 const TargetData *TD, const DominatorTree *DT,
908 unsigned MaxRecurse) {
909 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
910 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
911 Constant *Ops[] = { C0, C1 };
912 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
917 if (match(Op0, m_Zero()))
921 if (match(Op1, m_Zero()))
924 // X shift by undef -> undef because it may shift by the bitwidth.
925 if (match(Op1, m_Undef()))
928 // Shifting by the bitwidth or more is undefined.
929 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
930 if (CI->getValue().getLimitedValue() >=
931 Op0->getType()->getScalarSizeInBits())
932 return UndefValue::get(Op0->getType());
934 // If the operation is with the result of a select instruction, check whether
935 // operating on either branch of the select always yields the same value.
936 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
937 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
940 // If the operation is with the result of a phi instruction, check whether
941 // operating on all incoming values of the phi always yields the same value.
942 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
943 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
949 /// SimplifyShlInst - Given operands for an Shl, see if we can
950 /// fold the result. If not, this returns null.
951 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
952 const TargetData *TD, const DominatorTree *DT,
953 unsigned MaxRecurse) {
954 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
958 if (match(Op0, m_Undef()))
959 return Constant::getNullValue(Op0->getType());
961 // (X >> A) << A -> X
963 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
964 cast<PossiblyExactOperator>(Op0)->isExact())
969 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
970 const TargetData *TD, const DominatorTree *DT) {
971 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
974 /// SimplifyLShrInst - Given operands for an LShr, see if we can
975 /// fold the result. If not, this returns null.
976 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
977 const TargetData *TD, const DominatorTree *DT,
978 unsigned MaxRecurse) {
979 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
983 if (match(Op0, m_Undef()))
984 return Constant::getNullValue(Op0->getType());
986 // (X << A) >> A -> X
988 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
989 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
995 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
996 const TargetData *TD, const DominatorTree *DT) {
997 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1000 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1001 /// fold the result. If not, this returns null.
1002 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1003 const TargetData *TD, const DominatorTree *DT,
1004 unsigned MaxRecurse) {
1005 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1008 // all ones >>a X -> all ones
1009 if (match(Op0, m_AllOnes()))
1012 // undef >>a X -> all ones
1013 if (match(Op0, m_Undef()))
1014 return Constant::getAllOnesValue(Op0->getType());
1016 // (X << A) >> A -> X
1018 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1019 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1025 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1026 const TargetData *TD, const DominatorTree *DT) {
1027 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1030 /// SimplifyAndInst - Given operands for an And, see if we can
1031 /// fold the result. If not, this returns null.
1032 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1033 const DominatorTree *DT, unsigned MaxRecurse) {
1034 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1035 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1036 Constant *Ops[] = { CLHS, CRHS };
1037 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1041 // Canonicalize the constant to the RHS.
1042 std::swap(Op0, Op1);
1046 if (match(Op1, m_Undef()))
1047 return Constant::getNullValue(Op0->getType());
1054 if (match(Op1, m_Zero()))
1058 if (match(Op1, m_AllOnes()))
1061 // A & ~A = ~A & A = 0
1062 if (match(Op0, m_Not(m_Specific(Op1))) ||
1063 match(Op1, m_Not(m_Specific(Op0))))
1064 return Constant::getNullValue(Op0->getType());
1067 Value *A = 0, *B = 0;
1068 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1069 (A == Op1 || B == Op1))
1073 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1074 (A == Op0 || B == Op0))
1077 // Try some generic simplifications for associative operations.
1078 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1082 // And distributes over Or. Try some generic simplifications based on this.
1083 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1084 TD, DT, MaxRecurse))
1087 // And distributes over Xor. Try some generic simplifications based on this.
1088 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1089 TD, DT, MaxRecurse))
1092 // Or distributes over And. Try some generic simplifications based on this.
1093 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1094 TD, DT, MaxRecurse))
1097 // If the operation is with the result of a select instruction, check whether
1098 // operating on either branch of the select always yields the same value.
1099 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1100 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
1104 // If the operation is with the result of a phi instruction, check whether
1105 // operating on all incoming values of the phi always yields the same value.
1106 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1107 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
1114 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1115 const DominatorTree *DT) {
1116 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
1119 /// SimplifyOrInst - Given operands for an Or, see if we can
1120 /// fold the result. If not, this returns null.
1121 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1122 const DominatorTree *DT, unsigned MaxRecurse) {
1123 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1124 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1125 Constant *Ops[] = { CLHS, CRHS };
1126 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1130 // Canonicalize the constant to the RHS.
1131 std::swap(Op0, Op1);
1135 if (match(Op1, m_Undef()))
1136 return Constant::getAllOnesValue(Op0->getType());
1143 if (match(Op1, m_Zero()))
1147 if (match(Op1, m_AllOnes()))
1150 // A | ~A = ~A | A = -1
1151 if (match(Op0, m_Not(m_Specific(Op1))) ||
1152 match(Op1, m_Not(m_Specific(Op0))))
1153 return Constant::getAllOnesValue(Op0->getType());
1156 Value *A = 0, *B = 0;
1157 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1158 (A == Op1 || B == Op1))
1162 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1163 (A == Op0 || B == Op0))
1166 // ~(A & ?) | A = -1
1167 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1168 (A == Op1 || B == Op1))
1169 return Constant::getAllOnesValue(Op1->getType());
1171 // A | ~(A & ?) = -1
1172 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1173 (A == Op0 || B == Op0))
1174 return Constant::getAllOnesValue(Op0->getType());
1176 // Try some generic simplifications for associative operations.
1177 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1181 // Or distributes over And. Try some generic simplifications based on this.
1182 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1183 TD, DT, MaxRecurse))
1186 // And distributes over Or. Try some generic simplifications based on this.
1187 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1188 TD, DT, MaxRecurse))
1191 // If the operation is with the result of a select instruction, check whether
1192 // operating on either branch of the select always yields the same value.
1193 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1194 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
1198 // If the operation is with the result of a phi instruction, check whether
1199 // operating on all incoming values of the phi always yields the same value.
1200 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1201 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
1208 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1209 const DominatorTree *DT) {
1210 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
1213 /// SimplifyXorInst - Given operands for a Xor, see if we can
1214 /// fold the result. If not, this returns null.
1215 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1216 const DominatorTree *DT, unsigned MaxRecurse) {
1217 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1218 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1219 Constant *Ops[] = { CLHS, CRHS };
1220 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1224 // Canonicalize the constant to the RHS.
1225 std::swap(Op0, Op1);
1228 // A ^ undef -> undef
1229 if (match(Op1, m_Undef()))
1233 if (match(Op1, m_Zero()))
1238 return Constant::getNullValue(Op0->getType());
1240 // A ^ ~A = ~A ^ A = -1
1241 if (match(Op0, m_Not(m_Specific(Op1))) ||
1242 match(Op1, m_Not(m_Specific(Op0))))
1243 return Constant::getAllOnesValue(Op0->getType());
1245 // Try some generic simplifications for associative operations.
1246 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1250 // And distributes over Xor. Try some generic simplifications based on this.
1251 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1252 TD, DT, MaxRecurse))
1255 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1256 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1257 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1258 // only if B and C are equal. If B and C are equal then (since we assume
1259 // that operands have already been simplified) "select(cond, B, C)" should
1260 // have been simplified to the common value of B and C already. Analysing
1261 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1262 // for threading over phi nodes.
1267 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1268 const DominatorTree *DT) {
1269 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1272 static const Type *GetCompareTy(Value *Op) {
1273 return CmpInst::makeCmpResultType(Op->getType());
1276 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1277 /// fold the result. If not, this returns null.
1278 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1279 const TargetData *TD, const DominatorTree *DT,
1280 unsigned MaxRecurse) {
1281 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1282 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1284 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1285 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1286 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1288 // If we have a constant, make sure it is on the RHS.
1289 std::swap(LHS, RHS);
1290 Pred = CmpInst::getSwappedPredicate(Pred);
1293 const Type *ITy = GetCompareTy(LHS); // The return type.
1294 const Type *OpTy = LHS->getType(); // The operand type.
1296 // icmp X, X -> true/false
1297 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1298 // because X could be 0.
1299 if (LHS == RHS || isa<UndefValue>(RHS))
1300 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1302 // Special case logic when the operands have i1 type.
1303 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1304 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1307 case ICmpInst::ICMP_EQ:
1309 if (match(RHS, m_One()))
1312 case ICmpInst::ICMP_NE:
1314 if (match(RHS, m_Zero()))
1317 case ICmpInst::ICMP_UGT:
1319 if (match(RHS, m_Zero()))
1322 case ICmpInst::ICMP_UGE:
1324 if (match(RHS, m_One()))
1327 case ICmpInst::ICMP_SLT:
1329 if (match(RHS, m_Zero()))
1332 case ICmpInst::ICMP_SLE:
1334 if (match(RHS, m_One()))
1340 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1341 // different addresses, and what's more the address of a stack variable is
1342 // never null or equal to the address of a global. Note that generalizing
1343 // to the case where LHS is a global variable address or null is pointless,
1344 // since if both LHS and RHS are constants then we already constant folded
1345 // the compare, and if only one of them is then we moved it to RHS already.
1346 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1347 isa<ConstantPointerNull>(RHS)))
1348 // We already know that LHS != RHS.
1349 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1351 // If we are comparing with zero then try hard since this is a common case.
1352 if (match(RHS, m_Zero())) {
1353 bool LHSKnownNonNegative, LHSKnownNegative;
1356 assert(false && "Unknown ICmp predicate!");
1357 case ICmpInst::ICMP_ULT:
1358 return ConstantInt::getFalse(LHS->getContext());
1359 case ICmpInst::ICMP_UGE:
1360 return ConstantInt::getTrue(LHS->getContext());
1361 case ICmpInst::ICMP_EQ:
1362 case ICmpInst::ICMP_ULE:
1363 if (isKnownNonZero(LHS, TD))
1364 return ConstantInt::getFalse(LHS->getContext());
1366 case ICmpInst::ICMP_NE:
1367 case ICmpInst::ICMP_UGT:
1368 if (isKnownNonZero(LHS, TD))
1369 return ConstantInt::getTrue(LHS->getContext());
1371 case ICmpInst::ICMP_SLT:
1372 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1373 if (LHSKnownNegative)
1374 return ConstantInt::getTrue(LHS->getContext());
1375 if (LHSKnownNonNegative)
1376 return ConstantInt::getFalse(LHS->getContext());
1378 case ICmpInst::ICMP_SLE:
1379 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1380 if (LHSKnownNegative)
1381 return ConstantInt::getTrue(LHS->getContext());
1382 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1383 return ConstantInt::getFalse(LHS->getContext());
1385 case ICmpInst::ICMP_SGE:
1386 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1387 if (LHSKnownNegative)
1388 return ConstantInt::getFalse(LHS->getContext());
1389 if (LHSKnownNonNegative)
1390 return ConstantInt::getTrue(LHS->getContext());
1392 case ICmpInst::ICMP_SGT:
1393 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1394 if (LHSKnownNegative)
1395 return ConstantInt::getFalse(LHS->getContext());
1396 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1397 return ConstantInt::getTrue(LHS->getContext());
1402 // See if we are doing a comparison with a constant integer.
1403 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1404 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1405 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1406 if (RHS_CR.isEmptySet())
1407 return ConstantInt::getFalse(CI->getContext());
1408 if (RHS_CR.isFullSet())
1409 return ConstantInt::getTrue(CI->getContext());
1411 // Many binary operators with constant RHS have easy to compute constant
1412 // range. Use them to check whether the comparison is a tautology.
1413 uint32_t Width = CI->getBitWidth();
1414 APInt Lower = APInt(Width, 0);
1415 APInt Upper = APInt(Width, 0);
1417 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1418 // 'urem x, CI2' produces [0, CI2).
1419 Upper = CI2->getValue();
1420 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1421 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1422 Upper = CI2->getValue().abs();
1423 Lower = (-Upper) + 1;
1424 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1425 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1426 APInt NegOne = APInt::getAllOnesValue(Width);
1428 Upper = NegOne.udiv(CI2->getValue()) + 1;
1429 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1430 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1431 APInt IntMin = APInt::getSignedMinValue(Width);
1432 APInt IntMax = APInt::getSignedMaxValue(Width);
1433 APInt Val = CI2->getValue().abs();
1434 if (!Val.isMinValue()) {
1435 Lower = IntMin.sdiv(Val);
1436 Upper = IntMax.sdiv(Val) + 1;
1438 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1439 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1440 APInt NegOne = APInt::getAllOnesValue(Width);
1441 if (CI2->getValue().ult(Width))
1442 Upper = NegOne.lshr(CI2->getValue()) + 1;
1443 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1444 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1445 APInt IntMin = APInt::getSignedMinValue(Width);
1446 APInt IntMax = APInt::getSignedMaxValue(Width);
1447 if (CI2->getValue().ult(Width)) {
1448 Lower = IntMin.ashr(CI2->getValue());
1449 Upper = IntMax.ashr(CI2->getValue()) + 1;
1451 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1452 // 'or x, CI2' produces [CI2, UINT_MAX].
1453 Lower = CI2->getValue();
1454 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1455 // 'and x, CI2' produces [0, CI2].
1456 Upper = CI2->getValue() + 1;
1458 if (Lower != Upper) {
1459 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1460 if (RHS_CR.contains(LHS_CR))
1461 return ConstantInt::getTrue(RHS->getContext());
1462 if (RHS_CR.inverse().contains(LHS_CR))
1463 return ConstantInt::getFalse(RHS->getContext());
1467 // Compare of cast, for example (zext X) != 0 -> X != 0
1468 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1469 Instruction *LI = cast<CastInst>(LHS);
1470 Value *SrcOp = LI->getOperand(0);
1471 const Type *SrcTy = SrcOp->getType();
1472 const Type *DstTy = LI->getType();
1474 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1475 // if the integer type is the same size as the pointer type.
1476 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1477 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1478 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1479 // Transfer the cast to the constant.
1480 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1481 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1482 TD, DT, MaxRecurse-1))
1484 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1485 if (RI->getOperand(0)->getType() == SrcTy)
1486 // Compare without the cast.
1487 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1488 TD, DT, MaxRecurse-1))
1493 if (isa<ZExtInst>(LHS)) {
1494 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1496 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1497 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1498 // Compare X and Y. Note that signed predicates become unsigned.
1499 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1500 SrcOp, RI->getOperand(0), TD, DT,
1504 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1505 // too. If not, then try to deduce the result of the comparison.
1506 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1507 // Compute the constant that would happen if we truncated to SrcTy then
1508 // reextended to DstTy.
1509 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1510 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1512 // If the re-extended constant didn't change then this is effectively
1513 // also a case of comparing two zero-extended values.
1514 if (RExt == CI && MaxRecurse)
1515 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1516 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1519 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1520 // there. Use this to work out the result of the comparison.
1524 assert(false && "Unknown ICmp predicate!");
1526 case ICmpInst::ICMP_EQ:
1527 case ICmpInst::ICMP_UGT:
1528 case ICmpInst::ICMP_UGE:
1529 return ConstantInt::getFalse(CI->getContext());
1531 case ICmpInst::ICMP_NE:
1532 case ICmpInst::ICMP_ULT:
1533 case ICmpInst::ICMP_ULE:
1534 return ConstantInt::getTrue(CI->getContext());
1536 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1537 // is non-negative then LHS <s RHS.
1538 case ICmpInst::ICMP_SGT:
1539 case ICmpInst::ICMP_SGE:
1540 return CI->getValue().isNegative() ?
1541 ConstantInt::getTrue(CI->getContext()) :
1542 ConstantInt::getFalse(CI->getContext());
1544 case ICmpInst::ICMP_SLT:
1545 case ICmpInst::ICMP_SLE:
1546 return CI->getValue().isNegative() ?
1547 ConstantInt::getFalse(CI->getContext()) :
1548 ConstantInt::getTrue(CI->getContext());
1554 if (isa<SExtInst>(LHS)) {
1555 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1557 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1558 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1559 // Compare X and Y. Note that the predicate does not change.
1560 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1561 TD, DT, MaxRecurse-1))
1564 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1565 // too. If not, then try to deduce the result of the comparison.
1566 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1567 // Compute the constant that would happen if we truncated to SrcTy then
1568 // reextended to DstTy.
1569 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1570 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1572 // If the re-extended constant didn't change then this is effectively
1573 // also a case of comparing two sign-extended values.
1574 if (RExt == CI && MaxRecurse)
1575 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1579 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1580 // bits there. Use this to work out the result of the comparison.
1584 assert(false && "Unknown ICmp predicate!");
1585 case ICmpInst::ICMP_EQ:
1586 return ConstantInt::getFalse(CI->getContext());
1587 case ICmpInst::ICMP_NE:
1588 return ConstantInt::getTrue(CI->getContext());
1590 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1592 case ICmpInst::ICMP_SGT:
1593 case ICmpInst::ICMP_SGE:
1594 return CI->getValue().isNegative() ?
1595 ConstantInt::getTrue(CI->getContext()) :
1596 ConstantInt::getFalse(CI->getContext());
1597 case ICmpInst::ICMP_SLT:
1598 case ICmpInst::ICMP_SLE:
1599 return CI->getValue().isNegative() ?
1600 ConstantInt::getFalse(CI->getContext()) :
1601 ConstantInt::getTrue(CI->getContext());
1603 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1605 case ICmpInst::ICMP_UGT:
1606 case ICmpInst::ICMP_UGE:
1607 // Comparison is true iff the LHS <s 0.
1609 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1610 Constant::getNullValue(SrcTy),
1611 TD, DT, MaxRecurse-1))
1614 case ICmpInst::ICMP_ULT:
1615 case ICmpInst::ICMP_ULE:
1616 // Comparison is true iff the LHS >=s 0.
1618 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1619 Constant::getNullValue(SrcTy),
1620 TD, DT, MaxRecurse-1))
1629 // Special logic for binary operators.
1630 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1631 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1632 if (MaxRecurse && (LBO || RBO)) {
1633 // Analyze the case when either LHS or RHS is an add instruction.
1634 Value *A = 0, *B = 0, *C = 0, *D = 0;
1635 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1636 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1637 if (LBO && LBO->getOpcode() == Instruction::Add) {
1638 A = LBO->getOperand(0); B = LBO->getOperand(1);
1639 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1640 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1641 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1643 if (RBO && RBO->getOpcode() == Instruction::Add) {
1644 C = RBO->getOperand(0); D = RBO->getOperand(1);
1645 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1646 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1647 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1650 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1651 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1652 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1653 Constant::getNullValue(RHS->getType()),
1654 TD, DT, MaxRecurse-1))
1657 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1658 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1659 if (Value *V = SimplifyICmpInst(Pred,
1660 Constant::getNullValue(LHS->getType()),
1661 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1664 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1665 if (A && C && (A == C || A == D || B == C || B == D) &&
1666 NoLHSWrapProblem && NoRHSWrapProblem) {
1667 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1668 Value *Y = (A == C || A == D) ? B : A;
1669 Value *Z = (C == A || C == B) ? D : C;
1670 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1675 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1676 bool KnownNonNegative, KnownNegative;
1680 case ICmpInst::ICMP_SGT:
1681 case ICmpInst::ICMP_SGE:
1682 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1683 if (!KnownNonNegative)
1686 case ICmpInst::ICMP_EQ:
1687 case ICmpInst::ICMP_UGT:
1688 case ICmpInst::ICMP_UGE:
1689 return ConstantInt::getFalse(RHS->getContext());
1690 case ICmpInst::ICMP_SLT:
1691 case ICmpInst::ICMP_SLE:
1692 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1693 if (!KnownNonNegative)
1696 case ICmpInst::ICMP_NE:
1697 case ICmpInst::ICMP_ULT:
1698 case ICmpInst::ICMP_ULE:
1699 return ConstantInt::getTrue(RHS->getContext());
1702 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1703 bool KnownNonNegative, KnownNegative;
1707 case ICmpInst::ICMP_SGT:
1708 case ICmpInst::ICMP_SGE:
1709 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1710 if (!KnownNonNegative)
1713 case ICmpInst::ICMP_NE:
1714 case ICmpInst::ICMP_UGT:
1715 case ICmpInst::ICMP_UGE:
1716 return ConstantInt::getTrue(RHS->getContext());
1717 case ICmpInst::ICMP_SLT:
1718 case ICmpInst::ICMP_SLE:
1719 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1720 if (!KnownNonNegative)
1723 case ICmpInst::ICMP_EQ:
1724 case ICmpInst::ICMP_ULT:
1725 case ICmpInst::ICMP_ULE:
1726 return ConstantInt::getFalse(RHS->getContext());
1730 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1731 LBO->getOperand(1) == RBO->getOperand(1)) {
1732 switch (LBO->getOpcode()) {
1734 case Instruction::UDiv:
1735 case Instruction::LShr:
1736 if (ICmpInst::isSigned(Pred))
1739 case Instruction::SDiv:
1740 case Instruction::AShr:
1741 if (!LBO->isExact() && !RBO->isExact())
1743 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1744 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1747 case Instruction::Shl: {
1748 bool NUW = LBO->hasNoUnsignedWrap() && LBO->hasNoUnsignedWrap();
1749 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1752 if (!NSW && ICmpInst::isSigned(Pred))
1754 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1755 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1762 // If the comparison is with the result of a select instruction, check whether
1763 // comparing with either branch of the select always yields the same value.
1764 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1765 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1768 // If the comparison is with the result of a phi instruction, check whether
1769 // doing the compare with each incoming phi value yields a common result.
1770 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1771 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1777 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1778 const TargetData *TD, const DominatorTree *DT) {
1779 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1782 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1783 /// fold the result. If not, this returns null.
1784 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1785 const TargetData *TD, const DominatorTree *DT,
1786 unsigned MaxRecurse) {
1787 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1788 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1790 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1791 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1792 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1794 // If we have a constant, make sure it is on the RHS.
1795 std::swap(LHS, RHS);
1796 Pred = CmpInst::getSwappedPredicate(Pred);
1799 // Fold trivial predicates.
1800 if (Pred == FCmpInst::FCMP_FALSE)
1801 return ConstantInt::get(GetCompareTy(LHS), 0);
1802 if (Pred == FCmpInst::FCMP_TRUE)
1803 return ConstantInt::get(GetCompareTy(LHS), 1);
1805 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1806 return UndefValue::get(GetCompareTy(LHS));
1808 // fcmp x,x -> true/false. Not all compares are foldable.
1810 if (CmpInst::isTrueWhenEqual(Pred))
1811 return ConstantInt::get(GetCompareTy(LHS), 1);
1812 if (CmpInst::isFalseWhenEqual(Pred))
1813 return ConstantInt::get(GetCompareTy(LHS), 0);
1816 // Handle fcmp with constant RHS
1817 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1818 // If the constant is a nan, see if we can fold the comparison based on it.
1819 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1820 if (CFP->getValueAPF().isNaN()) {
1821 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1822 return ConstantInt::getFalse(CFP->getContext());
1823 assert(FCmpInst::isUnordered(Pred) &&
1824 "Comparison must be either ordered or unordered!");
1825 // True if unordered.
1826 return ConstantInt::getTrue(CFP->getContext());
1828 // Check whether the constant is an infinity.
1829 if (CFP->getValueAPF().isInfinity()) {
1830 if (CFP->getValueAPF().isNegative()) {
1832 case FCmpInst::FCMP_OLT:
1833 // No value is ordered and less than negative infinity.
1834 return ConstantInt::getFalse(CFP->getContext());
1835 case FCmpInst::FCMP_UGE:
1836 // All values are unordered with or at least negative infinity.
1837 return ConstantInt::getTrue(CFP->getContext());
1843 case FCmpInst::FCMP_OGT:
1844 // No value is ordered and greater than infinity.
1845 return ConstantInt::getFalse(CFP->getContext());
1846 case FCmpInst::FCMP_ULE:
1847 // All values are unordered with and at most infinity.
1848 return ConstantInt::getTrue(CFP->getContext());
1857 // If the comparison is with the result of a select instruction, check whether
1858 // comparing with either branch of the select always yields the same value.
1859 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1860 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1863 // If the comparison is with the result of a phi instruction, check whether
1864 // doing the compare with each incoming phi value yields a common result.
1865 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1866 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1872 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1873 const TargetData *TD, const DominatorTree *DT) {
1874 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1877 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1878 /// the result. If not, this returns null.
1879 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1880 const TargetData *TD, const DominatorTree *) {
1881 // select true, X, Y -> X
1882 // select false, X, Y -> Y
1883 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1884 return CB->getZExtValue() ? TrueVal : FalseVal;
1886 // select C, X, X -> X
1887 if (TrueVal == FalseVal)
1890 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1892 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1894 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1895 if (isa<Constant>(TrueVal))
1903 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1904 /// fold the result. If not, this returns null.
1905 Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
1906 const TargetData *TD, const DominatorTree *) {
1907 // The type of the GEP pointer operand.
1908 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1910 // getelementptr P -> P.
1914 if (isa<UndefValue>(Ops[0])) {
1915 // Compute the (pointer) type returned by the GEP instruction.
1916 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1918 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1919 return UndefValue::get(GEPTy);
1923 // getelementptr P, 0 -> P.
1924 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1927 // getelementptr P, N -> P if P points to a type of zero size.
1929 const Type *Ty = PtrTy->getElementType();
1930 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
1935 // Check to see if this is constant foldable.
1936 for (unsigned i = 0; i != NumOps; ++i)
1937 if (!isa<Constant>(Ops[i]))
1940 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1941 (Constant *const*)Ops+1, NumOps-1);
1944 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1945 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1946 // If all of the PHI's incoming values are the same then replace the PHI node
1947 // with the common value.
1948 Value *CommonValue = 0;
1949 bool HasUndefInput = false;
1950 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1951 Value *Incoming = PN->getIncomingValue(i);
1952 // If the incoming value is the phi node itself, it can safely be skipped.
1953 if (Incoming == PN) continue;
1954 if (isa<UndefValue>(Incoming)) {
1955 // Remember that we saw an undef value, but otherwise ignore them.
1956 HasUndefInput = true;
1959 if (CommonValue && Incoming != CommonValue)
1960 return 0; // Not the same, bail out.
1961 CommonValue = Incoming;
1964 // If CommonValue is null then all of the incoming values were either undef or
1965 // equal to the phi node itself.
1967 return UndefValue::get(PN->getType());
1969 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1970 // instruction, we cannot return X as the result of the PHI node unless it
1971 // dominates the PHI block.
1973 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1979 //=== Helper functions for higher up the class hierarchy.
1981 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1982 /// fold the result. If not, this returns null.
1983 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
1984 const TargetData *TD, const DominatorTree *DT,
1985 unsigned MaxRecurse) {
1987 case Instruction::Add:
1988 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
1989 TD, DT, MaxRecurse);
1990 case Instruction::Sub:
1991 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
1992 TD, DT, MaxRecurse);
1993 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
1994 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
1995 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
1996 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
1997 case Instruction::Shl:
1998 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
1999 TD, DT, MaxRecurse);
2000 case Instruction::LShr:
2001 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2002 case Instruction::AShr:
2003 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2004 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
2005 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
2006 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
2008 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2009 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2010 Constant *COps[] = {CLHS, CRHS};
2011 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
2014 // If the operation is associative, try some generic simplifications.
2015 if (Instruction::isAssociative(Opcode))
2016 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2020 // If the operation is with the result of a select instruction, check whether
2021 // operating on either branch of the select always yields the same value.
2022 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2023 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
2027 // If the operation is with the result of a phi instruction, check whether
2028 // operating on all incoming values of the phi always yields the same value.
2029 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2030 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
2037 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2038 const TargetData *TD, const DominatorTree *DT) {
2039 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
2042 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2043 /// fold the result.
2044 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2045 const TargetData *TD, const DominatorTree *DT,
2046 unsigned MaxRecurse) {
2047 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2048 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2049 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2052 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2053 const TargetData *TD, const DominatorTree *DT) {
2054 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2057 /// SimplifyInstruction - See if we can compute a simplified version of this
2058 /// instruction. If not, this returns null.
2059 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2060 const DominatorTree *DT) {
2063 switch (I->getOpcode()) {
2065 Result = ConstantFoldInstruction(I, TD);
2067 case Instruction::Add:
2068 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2069 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2070 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2073 case Instruction::Sub:
2074 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2075 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2076 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2079 case Instruction::Mul:
2080 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2082 case Instruction::SDiv:
2083 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2085 case Instruction::UDiv:
2086 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2088 case Instruction::FDiv:
2089 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2091 case Instruction::Shl:
2092 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2093 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2094 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2097 case Instruction::LShr:
2098 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2099 cast<BinaryOperator>(I)->isExact(),
2102 case Instruction::AShr:
2103 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2104 cast<BinaryOperator>(I)->isExact(),
2107 case Instruction::And:
2108 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2110 case Instruction::Or:
2111 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2113 case Instruction::Xor:
2114 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2116 case Instruction::ICmp:
2117 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2118 I->getOperand(0), I->getOperand(1), TD, DT);
2120 case Instruction::FCmp:
2121 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2122 I->getOperand(0), I->getOperand(1), TD, DT);
2124 case Instruction::Select:
2125 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2126 I->getOperand(2), TD, DT);
2128 case Instruction::GetElementPtr: {
2129 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2130 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
2133 case Instruction::PHI:
2134 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2138 /// If called on unreachable code, the above logic may report that the
2139 /// instruction simplified to itself. Make life easier for users by
2140 /// detecting that case here, returning a safe value instead.
2141 return Result == I ? UndefValue::get(I->getType()) : Result;
2144 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2145 /// delete the From instruction. In addition to a basic RAUW, this does a
2146 /// recursive simplification of the newly formed instructions. This catches
2147 /// things where one simplification exposes other opportunities. This only
2148 /// simplifies and deletes scalar operations, it does not change the CFG.
2150 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2151 const TargetData *TD,
2152 const DominatorTree *DT) {
2153 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2155 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2156 // we can know if it gets deleted out from under us or replaced in a
2157 // recursive simplification.
2158 WeakVH FromHandle(From);
2159 WeakVH ToHandle(To);
2161 while (!From->use_empty()) {
2162 // Update the instruction to use the new value.
2163 Use &TheUse = From->use_begin().getUse();
2164 Instruction *User = cast<Instruction>(TheUse.getUser());
2167 // Check to see if the instruction can be folded due to the operand
2168 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2169 // the 'or' with -1.
2170 Value *SimplifiedVal;
2172 // Sanity check to make sure 'User' doesn't dangle across
2173 // SimplifyInstruction.
2174 AssertingVH<> UserHandle(User);
2176 SimplifiedVal = SimplifyInstruction(User, TD, DT);
2177 if (SimplifiedVal == 0) continue;
2180 // Recursively simplify this user to the new value.
2181 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
2182 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2185 assert(ToHandle && "To value deleted by recursive simplification?");
2187 // If the recursive simplification ended up revisiting and deleting
2188 // 'From' then we're done.
2193 // If 'From' has value handles referring to it, do a real RAUW to update them.
2194 From->replaceAllUsesWith(To);
2196 From->eraseFromParent();