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/AliasAnalysis.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/Support/ConstantRange.h"
29 #include "llvm/Support/PatternMatch.h"
30 #include "llvm/Support/ValueHandle.h"
31 #include "llvm/Target/TargetData.h"
33 using namespace llvm::PatternMatch;
35 enum { RecursionLimit = 3 };
37 STATISTIC(NumExpand, "Number of expansions");
38 STATISTIC(NumFactor , "Number of factorizations");
39 STATISTIC(NumReassoc, "Number of reassociations");
41 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
42 const TargetLibraryInfo *, const DominatorTree *,
44 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
45 const TargetLibraryInfo *, const DominatorTree *,
47 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
48 const TargetLibraryInfo *, const DominatorTree *,
50 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
51 const TargetLibraryInfo *, const DominatorTree *,
53 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
54 const TargetLibraryInfo *, const DominatorTree *,
57 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
58 /// a vector with every element false, as appropriate for the type.
59 static Constant *getFalse(Type *Ty) {
60 assert(Ty->getScalarType()->isIntegerTy(1) &&
61 "Expected i1 type or a vector of i1!");
62 return Constant::getNullValue(Ty);
65 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
66 /// a vector with every element true, as appropriate for the type.
67 static Constant *getTrue(Type *Ty) {
68 assert(Ty->getScalarType()->isIntegerTy(1) &&
69 "Expected i1 type or a vector of i1!");
70 return Constant::getAllOnesValue(Ty);
73 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
74 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
76 CmpInst *Cmp = dyn_cast<CmpInst>(V);
79 CmpInst::Predicate CPred = Cmp->getPredicate();
80 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
81 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
83 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
87 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
88 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
89 Instruction *I = dyn_cast<Instruction>(V);
91 // Arguments and constants dominate all instructions.
94 // If we have a DominatorTree then do a precise test.
96 return DT->dominates(I, P);
98 // Otherwise, if the instruction is in the entry block, and is not an invoke,
99 // then it obviously dominates all phi nodes.
100 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
107 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
108 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
109 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
110 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
111 /// Returns the simplified value, or null if no simplification was performed.
112 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
113 unsigned OpcToExpand, const TargetData *TD,
114 const TargetLibraryInfo *TLI, const DominatorTree *DT,
115 unsigned MaxRecurse) {
116 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
117 // Recursion is always used, so bail out at once if we already hit the limit.
121 // Check whether the expression has the form "(A op' B) op C".
122 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
123 if (Op0->getOpcode() == OpcodeToExpand) {
124 // It does! Try turning it into "(A op C) op' (B op C)".
125 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
126 // Do "A op C" and "B op C" both simplify?
127 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
128 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
129 // They do! Return "L op' R" if it simplifies or is already available.
130 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
131 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
132 && L == B && R == A)) {
136 // Otherwise return "L op' R" if it simplifies.
137 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
145 // Check whether the expression has the form "A op (B op' C)".
146 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
147 if (Op1->getOpcode() == OpcodeToExpand) {
148 // It does! Try turning it into "(A op B) op' (A op C)".
149 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
150 // Do "A op B" and "A op C" both simplify?
151 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
152 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
153 // They do! Return "L op' R" if it simplifies or is already available.
154 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
155 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
156 && L == C && R == B)) {
160 // Otherwise return "L op' R" if it simplifies.
161 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
172 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
173 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
174 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
175 /// Returns the simplified value, or null if no simplification was performed.
176 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
177 unsigned OpcToExtract, const TargetData *TD,
178 const TargetLibraryInfo *TLI,
179 const DominatorTree *DT,
180 unsigned MaxRecurse) {
181 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
182 // Recursion is always used, so bail out at once if we already hit the limit.
186 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
187 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
189 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
190 !Op1 || Op1->getOpcode() != OpcodeToExtract)
193 // The expression has the form "(A op' B) op (C op' D)".
194 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
195 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
197 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
198 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
199 // commutative case, "(A op' B) op (C op' A)"?
200 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
201 Value *DD = A == C ? D : C;
202 // Form "A op' (B op DD)" if it simplifies completely.
203 // Does "B op DD" simplify?
204 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
205 // It does! Return "A op' V" if it simplifies or is already available.
206 // If V equals B then "A op' V" is just the LHS. If V equals DD then
207 // "A op' V" is just the RHS.
208 if (V == B || V == DD) {
210 return V == B ? LHS : RHS;
212 // Otherwise return "A op' V" if it simplifies.
213 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
221 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
222 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
223 // commutative case, "(A op' B) op (B op' D)"?
224 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
225 Value *CC = B == D ? C : D;
226 // Form "(A op CC) op' B" if it simplifies completely..
227 // Does "A op CC" simplify?
228 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
229 // It does! Return "V op' B" if it simplifies or is already available.
230 // If V equals A then "V op' B" is just the LHS. If V equals CC then
231 // "V op' B" is just the RHS.
232 if (V == A || V == CC) {
234 return V == A ? LHS : RHS;
236 // Otherwise return "V op' B" if it simplifies.
237 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
248 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
249 /// operations. Returns the simpler value, or null if none was found.
250 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
251 const TargetData *TD,
252 const TargetLibraryInfo *TLI,
253 const DominatorTree *DT,
254 unsigned MaxRecurse) {
255 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
256 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
258 // Recursion is always used, so bail out at once if we already hit the limit.
262 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
263 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
265 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
266 if (Op0 && Op0->getOpcode() == Opcode) {
267 Value *A = Op0->getOperand(0);
268 Value *B = Op0->getOperand(1);
271 // Does "B op C" simplify?
272 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
273 // It does! Return "A op V" if it simplifies or is already available.
274 // If V equals B then "A op V" is just the LHS.
275 if (V == B) return LHS;
276 // Otherwise return "A op V" if it simplifies.
277 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
284 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
285 if (Op1 && Op1->getOpcode() == Opcode) {
287 Value *B = Op1->getOperand(0);
288 Value *C = Op1->getOperand(1);
290 // Does "A op B" simplify?
291 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
292 // It does! Return "V op C" if it simplifies or is already available.
293 // If V equals B then "V op C" is just the RHS.
294 if (V == B) return RHS;
295 // Otherwise return "V op C" if it simplifies.
296 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
303 // The remaining transforms require commutativity as well as associativity.
304 if (!Instruction::isCommutative(Opcode))
307 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
308 if (Op0 && Op0->getOpcode() == Opcode) {
309 Value *A = Op0->getOperand(0);
310 Value *B = Op0->getOperand(1);
313 // Does "C op A" simplify?
314 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
315 // It does! Return "V op B" if it simplifies or is already available.
316 // If V equals A then "V op B" is just the LHS.
317 if (V == A) return LHS;
318 // Otherwise return "V op B" if it simplifies.
319 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
326 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
327 if (Op1 && Op1->getOpcode() == Opcode) {
329 Value *B = Op1->getOperand(0);
330 Value *C = Op1->getOperand(1);
332 // Does "C op A" simplify?
333 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
334 // It does! Return "B op V" if it simplifies or is already available.
335 // If V equals C then "B op V" is just the RHS.
336 if (V == C) return RHS;
337 // Otherwise return "B op V" if it simplifies.
338 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
348 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
349 /// instruction as an operand, try to simplify the binop by seeing whether
350 /// evaluating it on both branches of the select results in the same value.
351 /// Returns the common value if so, otherwise returns null.
352 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
353 const TargetData *TD,
354 const TargetLibraryInfo *TLI,
355 const DominatorTree *DT,
356 unsigned MaxRecurse) {
357 // Recursion is always used, so bail out at once if we already hit the limit.
362 if (isa<SelectInst>(LHS)) {
363 SI = cast<SelectInst>(LHS);
365 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
366 SI = cast<SelectInst>(RHS);
369 // Evaluate the BinOp on the true and false branches of the select.
373 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
374 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
376 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
380 // If they simplified to the same value, then return the common value.
381 // If they both failed to simplify then return null.
385 // If one branch simplified to undef, return the other one.
386 if (TV && isa<UndefValue>(TV))
388 if (FV && isa<UndefValue>(FV))
391 // If applying the operation did not change the true and false select values,
392 // then the result of the binop is the select itself.
393 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
396 // If one branch simplified and the other did not, and the simplified
397 // value is equal to the unsimplified one, return the simplified value.
398 // For example, select (cond, X, X & Z) & Z -> X & Z.
399 if ((FV && !TV) || (TV && !FV)) {
400 // Check that the simplified value has the form "X op Y" where "op" is the
401 // same as the original operation.
402 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
403 if (Simplified && Simplified->getOpcode() == Opcode) {
404 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
405 // We already know that "op" is the same as for the simplified value. See
406 // if the operands match too. If so, return the simplified value.
407 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
408 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
409 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
410 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
411 Simplified->getOperand(1) == UnsimplifiedRHS)
413 if (Simplified->isCommutative() &&
414 Simplified->getOperand(1) == UnsimplifiedLHS &&
415 Simplified->getOperand(0) == UnsimplifiedRHS)
423 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
424 /// try to simplify the comparison by seeing whether both branches of the select
425 /// result in the same value. Returns the common value if so, otherwise returns
427 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
428 Value *RHS, const TargetData *TD,
429 const TargetLibraryInfo *TLI,
430 const DominatorTree *DT,
431 unsigned MaxRecurse) {
432 // Recursion is always used, so bail out at once if we already hit the limit.
436 // Make sure the select is on the LHS.
437 if (!isa<SelectInst>(LHS)) {
439 Pred = CmpInst::getSwappedPredicate(Pred);
441 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
442 SelectInst *SI = cast<SelectInst>(LHS);
443 Value *Cond = SI->getCondition();
444 Value *TV = SI->getTrueValue();
445 Value *FV = SI->getFalseValue();
447 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
448 // Does "cmp TV, RHS" simplify?
449 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
451 // It not only simplified, it simplified to the select condition. Replace
453 TCmp = getTrue(Cond->getType());
455 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
456 // condition then we can replace it with 'true'. Otherwise give up.
457 if (!isSameCompare(Cond, Pred, TV, RHS))
459 TCmp = getTrue(Cond->getType());
462 // Does "cmp FV, RHS" simplify?
463 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
465 // It not only simplified, it simplified to the select condition. Replace
467 FCmp = getFalse(Cond->getType());
469 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
470 // condition then we can replace it with 'false'. Otherwise give up.
471 if (!isSameCompare(Cond, Pred, FV, RHS))
473 FCmp = getFalse(Cond->getType());
476 // If both sides simplified to the same value, then use it as the result of
477 // the original comparison.
481 // The remaining cases only make sense if the select condition has the same
482 // type as the result of the comparison, so bail out if this is not so.
483 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
485 // If the false value simplified to false, then the result of the compare
486 // is equal to "Cond && TCmp". This also catches the case when the false
487 // value simplified to false and the true value to true, returning "Cond".
488 if (match(FCmp, m_Zero()))
489 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
491 // If the true value simplified to true, then the result of the compare
492 // is equal to "Cond || FCmp".
493 if (match(TCmp, m_One()))
494 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
496 // Finally, if the false value simplified to true and the true value to
497 // false, then the result of the compare is equal to "!Cond".
498 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
500 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
501 TD, TLI, DT, MaxRecurse))
507 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
508 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
509 /// it on the incoming phi values yields the same result for every value. If so
510 /// returns the common value, otherwise returns null.
511 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
512 const TargetData *TD,
513 const TargetLibraryInfo *TLI,
514 const DominatorTree *DT,
515 unsigned MaxRecurse) {
516 // Recursion is always used, so bail out at once if we already hit the limit.
521 if (isa<PHINode>(LHS)) {
522 PI = cast<PHINode>(LHS);
523 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
524 if (!ValueDominatesPHI(RHS, PI, DT))
527 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
528 PI = cast<PHINode>(RHS);
529 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
530 if (!ValueDominatesPHI(LHS, PI, DT))
534 // Evaluate the BinOp on the incoming phi values.
535 Value *CommonValue = 0;
536 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
537 Value *Incoming = PI->getIncomingValue(i);
538 // If the incoming value is the phi node itself, it can safely be skipped.
539 if (Incoming == PI) continue;
540 Value *V = PI == LHS ?
541 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
542 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
543 // If the operation failed to simplify, or simplified to a different value
544 // to previously, then give up.
545 if (!V || (CommonValue && V != CommonValue))
553 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
554 /// try to simplify the comparison by seeing whether comparing with all of the
555 /// incoming phi values yields the same result every time. If so returns the
556 /// common result, otherwise returns null.
557 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
558 const TargetData *TD,
559 const TargetLibraryInfo *TLI,
560 const DominatorTree *DT,
561 unsigned MaxRecurse) {
562 // Recursion is always used, so bail out at once if we already hit the limit.
566 // Make sure the phi is on the LHS.
567 if (!isa<PHINode>(LHS)) {
569 Pred = CmpInst::getSwappedPredicate(Pred);
571 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
572 PHINode *PI = cast<PHINode>(LHS);
574 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
575 if (!ValueDominatesPHI(RHS, PI, DT))
578 // Evaluate the BinOp on the incoming phi values.
579 Value *CommonValue = 0;
580 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
581 Value *Incoming = PI->getIncomingValue(i);
582 // If the incoming value is the phi node itself, it can safely be skipped.
583 if (Incoming == PI) continue;
584 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
585 // If the operation failed to simplify, or simplified to a different value
586 // to previously, then give up.
587 if (!V || (CommonValue && V != CommonValue))
595 /// SimplifyAddInst - Given operands for an Add, see if we can
596 /// fold the result. If not, this returns null.
597 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
598 const TargetData *TD,
599 const TargetLibraryInfo *TLI,
600 const DominatorTree *DT,
601 unsigned MaxRecurse) {
602 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
603 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
604 Constant *Ops[] = { CLHS, CRHS };
605 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
609 // Canonicalize the constant to the RHS.
613 // X + undef -> undef
614 if (match(Op1, m_Undef()))
618 if (match(Op1, m_Zero()))
625 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
626 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
629 // X + ~X -> -1 since ~X = -X-1
630 if (match(Op0, m_Not(m_Specific(Op1))) ||
631 match(Op1, m_Not(m_Specific(Op0))))
632 return Constant::getAllOnesValue(Op0->getType());
635 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
636 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
639 // Try some generic simplifications for associative operations.
640 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
644 // Mul distributes over Add. Try some generic simplifications based on this.
645 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
646 TD, TLI, DT, MaxRecurse))
649 // Threading Add over selects and phi nodes is pointless, so don't bother.
650 // Threading over the select in "A + select(cond, B, C)" means evaluating
651 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
652 // only if B and C are equal. If B and C are equal then (since we assume
653 // that operands have already been simplified) "select(cond, B, C)" should
654 // have been simplified to the common value of B and C already. Analysing
655 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
656 // for threading over phi nodes.
661 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
662 const TargetData *TD, const TargetLibraryInfo *TLI,
663 const DominatorTree *DT) {
664 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
667 /// SimplifySubInst - Given operands for a Sub, see if we can
668 /// fold the result. If not, this returns null.
669 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
670 const TargetData *TD,
671 const TargetLibraryInfo *TLI,
672 const DominatorTree *DT,
673 unsigned MaxRecurse) {
674 if (Constant *CLHS = dyn_cast<Constant>(Op0))
675 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
676 Constant *Ops[] = { CLHS, CRHS };
677 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
681 // X - undef -> undef
682 // undef - X -> undef
683 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
684 return UndefValue::get(Op0->getType());
687 if (match(Op1, m_Zero()))
692 return Constant::getNullValue(Op0->getType());
697 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
698 match(Op0, m_Shl(m_Specific(Op1), m_One())))
701 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
702 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
703 Value *Y = 0, *Z = Op1;
704 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
705 // See if "V === Y - Z" simplifies.
706 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
707 // It does! Now see if "X + V" simplifies.
708 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
710 // It does, we successfully reassociated!
714 // See if "V === X - Z" simplifies.
715 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
716 // It does! Now see if "Y + V" simplifies.
717 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
719 // It does, we successfully reassociated!
725 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
726 // For example, X - (X + 1) -> -1
728 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
729 // See if "V === X - Y" simplifies.
730 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
731 // It does! Now see if "V - Z" simplifies.
732 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
734 // It does, we successfully reassociated!
738 // See if "V === X - Z" simplifies.
739 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
740 // It does! Now see if "V - Y" simplifies.
741 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
743 // It does, we successfully reassociated!
749 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
750 // For example, X - (X - Y) -> Y.
752 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
753 // See if "V === Z - X" simplifies.
754 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
755 // It does! Now see if "V + Y" simplifies.
756 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
758 // It does, we successfully reassociated!
763 // Mul distributes over Sub. Try some generic simplifications based on this.
764 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
765 TD, TLI, DT, MaxRecurse))
769 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
770 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
773 // Threading Sub over selects and phi nodes is pointless, so don't bother.
774 // Threading over the select in "A - select(cond, B, C)" means evaluating
775 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
776 // only if B and C are equal. If B and C are equal then (since we assume
777 // that operands have already been simplified) "select(cond, B, C)" should
778 // have been simplified to the common value of B and C already. Analysing
779 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
780 // for threading over phi nodes.
785 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
786 const TargetData *TD,
787 const TargetLibraryInfo *TLI,
788 const DominatorTree *DT) {
789 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
792 /// SimplifyMulInst - Given operands for a Mul, see if we can
793 /// fold the result. If not, this returns null.
794 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
795 const TargetLibraryInfo *TLI,
796 const DominatorTree *DT, unsigned MaxRecurse) {
797 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
798 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
799 Constant *Ops[] = { CLHS, CRHS };
800 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
804 // Canonicalize the constant to the RHS.
809 if (match(Op1, m_Undef()))
810 return Constant::getNullValue(Op0->getType());
813 if (match(Op1, m_Zero()))
817 if (match(Op1, m_One()))
820 // (X / Y) * Y -> X if the division is exact.
822 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
823 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
827 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
828 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
831 // Try some generic simplifications for associative operations.
832 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
836 // Mul distributes over Add. Try some generic simplifications based on this.
837 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
838 TD, TLI, DT, MaxRecurse))
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(Instruction::Mul, Op0, Op1, TD, TLI, DT,
848 // If the operation is with the result of a phi instruction, check whether
849 // operating on all incoming values of the phi always yields the same value.
850 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
851 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
858 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
859 const TargetLibraryInfo *TLI,
860 const DominatorTree *DT) {
861 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
864 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
865 /// fold the result. If not, this returns null.
866 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
867 const TargetData *TD, const TargetLibraryInfo *TLI,
868 const DominatorTree *DT, unsigned MaxRecurse) {
869 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
870 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
871 Constant *Ops[] = { C0, C1 };
872 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
876 bool isSigned = Opcode == Instruction::SDiv;
878 // X / undef -> undef
879 if (match(Op1, m_Undef()))
883 if (match(Op0, m_Undef()))
884 return Constant::getNullValue(Op0->getType());
886 // 0 / X -> 0, we don't need to preserve faults!
887 if (match(Op0, m_Zero()))
891 if (match(Op1, m_One()))
894 if (Op0->getType()->isIntegerTy(1))
895 // It can't be division by zero, hence it must be division by one.
900 return ConstantInt::get(Op0->getType(), 1);
902 // (X * Y) / Y -> X if the multiplication does not overflow.
903 Value *X = 0, *Y = 0;
904 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
905 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
906 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
907 // If the Mul knows it does not overflow, then we are good to go.
908 if ((isSigned && Mul->hasNoSignedWrap()) ||
909 (!isSigned && Mul->hasNoUnsignedWrap()))
911 // If X has the form X = A / Y then X * Y cannot overflow.
912 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
913 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
917 // (X rem Y) / Y -> 0
918 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
919 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
920 return Constant::getNullValue(Op0->getType());
922 // If the operation is with the result of a select instruction, check whether
923 // operating on either branch of the select always yields the same value.
924 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
925 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
929 // If the operation is with the result of a phi instruction, check whether
930 // operating on all incoming values of the phi always yields the same value.
931 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
932 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
939 /// SimplifySDivInst - Given operands for an SDiv, see if we can
940 /// fold the result. If not, this returns null.
941 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
942 const TargetLibraryInfo *TLI,
943 const DominatorTree *DT, unsigned MaxRecurse) {
944 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
951 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
952 const TargetLibraryInfo *TLI,
953 const DominatorTree *DT) {
954 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
957 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
958 /// fold the result. If not, this returns null.
959 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
960 const TargetLibraryInfo *TLI,
961 const DominatorTree *DT, unsigned MaxRecurse) {
962 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
969 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
970 const TargetLibraryInfo *TLI,
971 const DominatorTree *DT) {
972 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
975 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
976 const TargetLibraryInfo *,
977 const DominatorTree *, unsigned) {
978 // undef / X -> undef (the undef could be a snan).
979 if (match(Op0, m_Undef()))
982 // X / undef -> undef
983 if (match(Op1, m_Undef()))
989 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
990 const TargetLibraryInfo *TLI,
991 const DominatorTree *DT) {
992 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
995 /// SimplifyRem - Given operands for an SRem or URem, see if we can
996 /// fold the result. If not, this returns null.
997 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
998 const TargetData *TD, const TargetLibraryInfo *TLI,
999 const DominatorTree *DT, unsigned MaxRecurse) {
1000 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1001 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1002 Constant *Ops[] = { C0, C1 };
1003 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1007 // X % undef -> undef
1008 if (match(Op1, m_Undef()))
1012 if (match(Op0, m_Undef()))
1013 return Constant::getNullValue(Op0->getType());
1015 // 0 % X -> 0, we don't need to preserve faults!
1016 if (match(Op0, m_Zero()))
1019 // X % 0 -> undef, we don't need to preserve faults!
1020 if (match(Op1, m_Zero()))
1021 return UndefValue::get(Op0->getType());
1024 if (match(Op1, m_One()))
1025 return Constant::getNullValue(Op0->getType());
1027 if (Op0->getType()->isIntegerTy(1))
1028 // It can't be remainder by zero, hence it must be remainder by one.
1029 return Constant::getNullValue(Op0->getType());
1033 return Constant::getNullValue(Op0->getType());
1035 // If the operation is with the result of a select instruction, check whether
1036 // operating on either branch of the select always yields the same value.
1037 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1038 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1041 // If the operation is with the result of a phi instruction, check whether
1042 // operating on all incoming values of the phi always yields the same value.
1043 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1044 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1050 /// SimplifySRemInst - Given operands for an SRem, see if we can
1051 /// fold the result. If not, this returns null.
1052 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1053 const TargetLibraryInfo *TLI,
1054 const DominatorTree *DT,
1055 unsigned MaxRecurse) {
1056 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1062 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1063 const TargetLibraryInfo *TLI,
1064 const DominatorTree *DT) {
1065 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1068 /// SimplifyURemInst - Given operands for a URem, see if we can
1069 /// fold the result. If not, this returns null.
1070 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1071 const TargetLibraryInfo *TLI,
1072 const DominatorTree *DT,
1073 unsigned MaxRecurse) {
1074 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1080 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1081 const TargetLibraryInfo *TLI,
1082 const DominatorTree *DT) {
1083 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1086 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1087 const TargetLibraryInfo *,
1088 const DominatorTree *,
1090 // undef % X -> undef (the undef could be a snan).
1091 if (match(Op0, m_Undef()))
1094 // X % undef -> undef
1095 if (match(Op1, m_Undef()))
1101 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1102 const TargetLibraryInfo *TLI,
1103 const DominatorTree *DT) {
1104 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1107 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1108 /// fold the result. If not, this returns null.
1109 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1110 const TargetData *TD, const TargetLibraryInfo *TLI,
1111 const DominatorTree *DT, unsigned MaxRecurse) {
1112 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1113 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1114 Constant *Ops[] = { C0, C1 };
1115 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1119 // 0 shift by X -> 0
1120 if (match(Op0, m_Zero()))
1123 // X shift by 0 -> X
1124 if (match(Op1, m_Zero()))
1127 // X shift by undef -> undef because it may shift by the bitwidth.
1128 if (match(Op1, m_Undef()))
1131 // Shifting by the bitwidth or more is undefined.
1132 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1133 if (CI->getValue().getLimitedValue() >=
1134 Op0->getType()->getScalarSizeInBits())
1135 return UndefValue::get(Op0->getType());
1137 // If the operation is with the result of a select instruction, check whether
1138 // operating on either branch of the select always yields the same value.
1139 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1140 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1143 // If the operation is with the result of a phi instruction, check whether
1144 // operating on all incoming values of the phi always yields the same value.
1145 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1146 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1152 /// SimplifyShlInst - Given operands for an Shl, see if we can
1153 /// fold the result. If not, this returns null.
1154 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1155 const TargetData *TD,
1156 const TargetLibraryInfo *TLI,
1157 const DominatorTree *DT, unsigned MaxRecurse) {
1158 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
1162 if (match(Op0, m_Undef()))
1163 return Constant::getNullValue(Op0->getType());
1165 // (X >> A) << A -> X
1167 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1172 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1173 const TargetData *TD, const TargetLibraryInfo *TLI,
1174 const DominatorTree *DT) {
1175 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
1178 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1179 /// fold the result. If not, this returns null.
1180 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1181 const TargetData *TD,
1182 const TargetLibraryInfo *TLI,
1183 const DominatorTree *DT,
1184 unsigned MaxRecurse) {
1185 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1189 if (match(Op0, m_Undef()))
1190 return Constant::getNullValue(Op0->getType());
1192 // (X << A) >> A -> X
1194 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1195 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1201 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1202 const TargetData *TD,
1203 const TargetLibraryInfo *TLI,
1204 const DominatorTree *DT) {
1205 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1208 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1209 /// fold the result. If not, this returns null.
1210 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1211 const TargetData *TD,
1212 const TargetLibraryInfo *TLI,
1213 const DominatorTree *DT,
1214 unsigned MaxRecurse) {
1215 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1218 // all ones >>a X -> all ones
1219 if (match(Op0, m_AllOnes()))
1222 // undef >>a X -> all ones
1223 if (match(Op0, m_Undef()))
1224 return Constant::getAllOnesValue(Op0->getType());
1226 // (X << A) >> A -> X
1228 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1229 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1235 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1236 const TargetData *TD,
1237 const TargetLibraryInfo *TLI,
1238 const DominatorTree *DT) {
1239 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1242 /// SimplifyAndInst - Given operands for an And, see if we can
1243 /// fold the result. If not, this returns null.
1244 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1245 const TargetLibraryInfo *TLI,
1246 const DominatorTree *DT,
1247 unsigned MaxRecurse) {
1248 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1249 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1250 Constant *Ops[] = { CLHS, CRHS };
1251 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1255 // Canonicalize the constant to the RHS.
1256 std::swap(Op0, Op1);
1260 if (match(Op1, m_Undef()))
1261 return Constant::getNullValue(Op0->getType());
1268 if (match(Op1, m_Zero()))
1272 if (match(Op1, m_AllOnes()))
1275 // A & ~A = ~A & A = 0
1276 if (match(Op0, m_Not(m_Specific(Op1))) ||
1277 match(Op1, m_Not(m_Specific(Op0))))
1278 return Constant::getNullValue(Op0->getType());
1281 Value *A = 0, *B = 0;
1282 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1283 (A == Op1 || B == Op1))
1287 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1288 (A == Op0 || B == Op0))
1291 // A & (-A) = A if A is a power of two or zero.
1292 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1293 match(Op1, m_Neg(m_Specific(Op0)))) {
1294 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1296 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1300 // Try some generic simplifications for associative operations.
1301 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1305 // And distributes over Or. Try some generic simplifications based on this.
1306 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1307 TD, TLI, DT, MaxRecurse))
1310 // And distributes over Xor. Try some generic simplifications based on this.
1311 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1312 TD, TLI, DT, MaxRecurse))
1315 // Or distributes over And. Try some generic simplifications based on this.
1316 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1317 TD, TLI, DT, MaxRecurse))
1320 // If the operation is with the result of a select instruction, check whether
1321 // operating on either branch of the select always yields the same value.
1322 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1323 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1327 // If the operation is with the result of a phi instruction, check whether
1328 // operating on all incoming values of the phi always yields the same value.
1329 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1330 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
1337 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1338 const TargetLibraryInfo *TLI,
1339 const DominatorTree *DT) {
1340 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1343 /// SimplifyOrInst - Given operands for an Or, see if we can
1344 /// fold the result. If not, this returns null.
1345 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1346 const TargetLibraryInfo *TLI,
1347 const DominatorTree *DT, unsigned MaxRecurse) {
1348 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1349 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1350 Constant *Ops[] = { CLHS, CRHS };
1351 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1355 // Canonicalize the constant to the RHS.
1356 std::swap(Op0, Op1);
1360 if (match(Op1, m_Undef()))
1361 return Constant::getAllOnesValue(Op0->getType());
1368 if (match(Op1, m_Zero()))
1372 if (match(Op1, m_AllOnes()))
1375 // A | ~A = ~A | A = -1
1376 if (match(Op0, m_Not(m_Specific(Op1))) ||
1377 match(Op1, m_Not(m_Specific(Op0))))
1378 return Constant::getAllOnesValue(Op0->getType());
1381 Value *A = 0, *B = 0;
1382 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1383 (A == Op1 || B == Op1))
1387 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1388 (A == Op0 || B == Op0))
1391 // ~(A & ?) | A = -1
1392 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1393 (A == Op1 || B == Op1))
1394 return Constant::getAllOnesValue(Op1->getType());
1396 // A | ~(A & ?) = -1
1397 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1398 (A == Op0 || B == Op0))
1399 return Constant::getAllOnesValue(Op0->getType());
1401 // Try some generic simplifications for associative operations.
1402 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1406 // Or distributes over And. Try some generic simplifications based on this.
1407 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1408 TLI, DT, MaxRecurse))
1411 // And distributes over Or. Try some generic simplifications based on this.
1412 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1413 TD, TLI, DT, MaxRecurse))
1416 // If the operation is with the result of a select instruction, check whether
1417 // operating on either branch of the select always yields the same value.
1418 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1419 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
1423 // If the operation is with the result of a phi instruction, check whether
1424 // operating on all incoming values of the phi always yields the same value.
1425 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1426 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
1433 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1434 const TargetLibraryInfo *TLI,
1435 const DominatorTree *DT) {
1436 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1439 /// SimplifyXorInst - Given operands for a Xor, see if we can
1440 /// fold the result. If not, this returns null.
1441 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1442 const TargetLibraryInfo *TLI,
1443 const DominatorTree *DT, unsigned MaxRecurse) {
1444 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1445 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1446 Constant *Ops[] = { CLHS, CRHS };
1447 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1451 // Canonicalize the constant to the RHS.
1452 std::swap(Op0, Op1);
1455 // A ^ undef -> undef
1456 if (match(Op1, m_Undef()))
1460 if (match(Op1, m_Zero()))
1465 return Constant::getNullValue(Op0->getType());
1467 // A ^ ~A = ~A ^ A = -1
1468 if (match(Op0, m_Not(m_Specific(Op1))) ||
1469 match(Op1, m_Not(m_Specific(Op0))))
1470 return Constant::getAllOnesValue(Op0->getType());
1472 // Try some generic simplifications for associative operations.
1473 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1477 // And distributes over Xor. Try some generic simplifications based on this.
1478 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1479 TD, TLI, DT, MaxRecurse))
1482 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1483 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1484 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1485 // only if B and C are equal. If B and C are equal then (since we assume
1486 // that operands have already been simplified) "select(cond, B, C)" should
1487 // have been simplified to the common value of B and C already. Analysing
1488 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1489 // for threading over phi nodes.
1494 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1495 const TargetLibraryInfo *TLI,
1496 const DominatorTree *DT) {
1497 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1500 static Type *GetCompareTy(Value *Op) {
1501 return CmpInst::makeCmpResultType(Op->getType());
1504 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1505 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1506 /// otherwise return null. Helper function for analyzing max/min idioms.
1507 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1508 Value *LHS, Value *RHS) {
1509 SelectInst *SI = dyn_cast<SelectInst>(V);
1512 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1515 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1516 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1518 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1519 LHS == CmpRHS && RHS == CmpLHS)
1524 /// stripPointerAdjustments - This is like Value::stripPointerCasts, but also
1525 /// removes inbounds gep operations, regardless of their indices.
1526 static Value *stripPointerAdjustmentsImpl(Value *V,
1527 SmallPtrSet<GEPOperator*, 8> &VisitedGEPs) {
1528 GEPOperator *GEP = dyn_cast<GEPOperator>(V);
1529 if (GEP == 0 || !GEP->isInBounds())
1532 // If we've already seen this GEP, we will end up infinitely looping. This
1533 // can happen in unreachable code.
1534 if (!VisitedGEPs.insert(GEP))
1537 return stripPointerAdjustmentsImpl(GEP->getOperand(0)->stripPointerCasts(),
1541 static Value *stripPointerAdjustments(Value *V) {
1542 SmallPtrSet<GEPOperator*, 8> VisitedGEPs;
1543 return stripPointerAdjustmentsImpl(V, VisitedGEPs);
1547 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1548 /// fold the result. If not, this returns null.
1549 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1550 const TargetData *TD,
1551 const TargetLibraryInfo *TLI,
1552 const DominatorTree *DT,
1553 unsigned MaxRecurse) {
1554 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1555 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1557 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1558 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1559 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
1561 // If we have a constant, make sure it is on the RHS.
1562 std::swap(LHS, RHS);
1563 Pred = CmpInst::getSwappedPredicate(Pred);
1566 Type *ITy = GetCompareTy(LHS); // The return type.
1567 Type *OpTy = LHS->getType(); // The operand type.
1569 // icmp X, X -> true/false
1570 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1571 // because X could be 0.
1572 if (LHS == RHS || isa<UndefValue>(RHS))
1573 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1575 // Special case logic when the operands have i1 type.
1576 if (OpTy->getScalarType()->isIntegerTy(1)) {
1579 case ICmpInst::ICMP_EQ:
1581 if (match(RHS, m_One()))
1584 case ICmpInst::ICMP_NE:
1586 if (match(RHS, m_Zero()))
1589 case ICmpInst::ICMP_UGT:
1591 if (match(RHS, m_Zero()))
1594 case ICmpInst::ICMP_UGE:
1596 if (match(RHS, m_One()))
1599 case ICmpInst::ICMP_SLT:
1601 if (match(RHS, m_Zero()))
1604 case ICmpInst::ICMP_SLE:
1606 if (match(RHS, m_One()))
1612 // icmp <object*>, <object*/null> - Different identified objects have
1613 // different addresses, and what's more the address of a stack variable is
1614 // never equal to another argument. Note that generalizing to the case where
1615 // LHS is a global variable address or null is pointless, since if both LHS
1616 // and RHS are constants then we already constant folded the compare, and if
1617 // only one of them is then we moved it to RHS already.
1618 Value *LHSPtr = LHS->stripPointerCasts();
1619 Value *RHSPtr = RHS->stripPointerCasts();
1620 if (LHSPtr == RHSPtr)
1621 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1623 // Be more aggressive about stripping pointer adjustments when checking a
1624 // comparison of an alloca address to another object. We can rip off all
1625 // inbounds GEP operations, even if they are variable.
1626 LHSPtr = stripPointerAdjustments(LHSPtr);
1627 if (llvm::isIdentifiedObject(LHSPtr)) {
1628 RHSPtr = stripPointerAdjustments(RHSPtr);
1629 // If both sides are different identified objects, they aren't equal unless
1631 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
1632 (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)))
1633 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1635 // Assume that the null is on the right.
1636 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr))
1637 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1639 // A local instruction (alloca or noalias call) can't equal any incoming
1641 if ((isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr)) ||
1642 (isa<Instruction>(RHSPtr) && isa<Argument>(LHSPtr)))
1643 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1646 // If we are comparing with zero then try hard since this is a common case.
1647 if (match(RHS, m_Zero())) {
1648 bool LHSKnownNonNegative, LHSKnownNegative;
1650 default: llvm_unreachable("Unknown ICmp predicate!");
1651 case ICmpInst::ICMP_ULT:
1652 return getFalse(ITy);
1653 case ICmpInst::ICMP_UGE:
1654 return getTrue(ITy);
1655 case ICmpInst::ICMP_EQ:
1656 case ICmpInst::ICMP_ULE:
1657 if (isKnownNonZero(LHS, TD))
1658 return getFalse(ITy);
1660 case ICmpInst::ICMP_NE:
1661 case ICmpInst::ICMP_UGT:
1662 if (isKnownNonZero(LHS, TD))
1663 return getTrue(ITy);
1665 case ICmpInst::ICMP_SLT:
1666 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1667 if (LHSKnownNegative)
1668 return getTrue(ITy);
1669 if (LHSKnownNonNegative)
1670 return getFalse(ITy);
1672 case ICmpInst::ICMP_SLE:
1673 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1674 if (LHSKnownNegative)
1675 return getTrue(ITy);
1676 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1677 return getFalse(ITy);
1679 case ICmpInst::ICMP_SGE:
1680 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1681 if (LHSKnownNegative)
1682 return getFalse(ITy);
1683 if (LHSKnownNonNegative)
1684 return getTrue(ITy);
1686 case ICmpInst::ICMP_SGT:
1687 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1688 if (LHSKnownNegative)
1689 return getFalse(ITy);
1690 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1691 return getTrue(ITy);
1696 // See if we are doing a comparison with a constant integer.
1697 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1698 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1699 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1700 if (RHS_CR.isEmptySet())
1701 return ConstantInt::getFalse(CI->getContext());
1702 if (RHS_CR.isFullSet())
1703 return ConstantInt::getTrue(CI->getContext());
1705 // Many binary operators with constant RHS have easy to compute constant
1706 // range. Use them to check whether the comparison is a tautology.
1707 uint32_t Width = CI->getBitWidth();
1708 APInt Lower = APInt(Width, 0);
1709 APInt Upper = APInt(Width, 0);
1711 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1712 // 'urem x, CI2' produces [0, CI2).
1713 Upper = CI2->getValue();
1714 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1715 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1716 Upper = CI2->getValue().abs();
1717 Lower = (-Upper) + 1;
1718 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1719 // 'udiv CI2, x' produces [0, CI2].
1720 Upper = CI2->getValue() + 1;
1721 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1722 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1723 APInt NegOne = APInt::getAllOnesValue(Width);
1725 Upper = NegOne.udiv(CI2->getValue()) + 1;
1726 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1727 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1728 APInt IntMin = APInt::getSignedMinValue(Width);
1729 APInt IntMax = APInt::getSignedMaxValue(Width);
1730 APInt Val = CI2->getValue().abs();
1731 if (!Val.isMinValue()) {
1732 Lower = IntMin.sdiv(Val);
1733 Upper = IntMax.sdiv(Val) + 1;
1735 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1736 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1737 APInt NegOne = APInt::getAllOnesValue(Width);
1738 if (CI2->getValue().ult(Width))
1739 Upper = NegOne.lshr(CI2->getValue()) + 1;
1740 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1741 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1742 APInt IntMin = APInt::getSignedMinValue(Width);
1743 APInt IntMax = APInt::getSignedMaxValue(Width);
1744 if (CI2->getValue().ult(Width)) {
1745 Lower = IntMin.ashr(CI2->getValue());
1746 Upper = IntMax.ashr(CI2->getValue()) + 1;
1748 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1749 // 'or x, CI2' produces [CI2, UINT_MAX].
1750 Lower = CI2->getValue();
1751 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1752 // 'and x, CI2' produces [0, CI2].
1753 Upper = CI2->getValue() + 1;
1755 if (Lower != Upper) {
1756 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1757 if (RHS_CR.contains(LHS_CR))
1758 return ConstantInt::getTrue(RHS->getContext());
1759 if (RHS_CR.inverse().contains(LHS_CR))
1760 return ConstantInt::getFalse(RHS->getContext());
1764 // Compare of cast, for example (zext X) != 0 -> X != 0
1765 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1766 Instruction *LI = cast<CastInst>(LHS);
1767 Value *SrcOp = LI->getOperand(0);
1768 Type *SrcTy = SrcOp->getType();
1769 Type *DstTy = LI->getType();
1771 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1772 // if the integer type is the same size as the pointer type.
1773 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1774 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1775 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1776 // Transfer the cast to the constant.
1777 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1778 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1779 TD, TLI, DT, MaxRecurse-1))
1781 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1782 if (RI->getOperand(0)->getType() == SrcTy)
1783 // Compare without the cast.
1784 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1785 TD, TLI, DT, MaxRecurse-1))
1790 if (isa<ZExtInst>(LHS)) {
1791 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1793 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1794 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1795 // Compare X and Y. Note that signed predicates become unsigned.
1796 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1797 SrcOp, RI->getOperand(0), TD, TLI, DT,
1801 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1802 // too. If not, then try to deduce the result of the comparison.
1803 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1804 // Compute the constant that would happen if we truncated to SrcTy then
1805 // reextended to DstTy.
1806 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1807 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1809 // If the re-extended constant didn't change then this is effectively
1810 // also a case of comparing two zero-extended values.
1811 if (RExt == CI && MaxRecurse)
1812 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1813 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
1816 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1817 // there. Use this to work out the result of the comparison.
1820 default: llvm_unreachable("Unknown ICmp predicate!");
1822 case ICmpInst::ICMP_EQ:
1823 case ICmpInst::ICMP_UGT:
1824 case ICmpInst::ICMP_UGE:
1825 return ConstantInt::getFalse(CI->getContext());
1827 case ICmpInst::ICMP_NE:
1828 case ICmpInst::ICMP_ULT:
1829 case ICmpInst::ICMP_ULE:
1830 return ConstantInt::getTrue(CI->getContext());
1832 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1833 // is non-negative then LHS <s RHS.
1834 case ICmpInst::ICMP_SGT:
1835 case ICmpInst::ICMP_SGE:
1836 return CI->getValue().isNegative() ?
1837 ConstantInt::getTrue(CI->getContext()) :
1838 ConstantInt::getFalse(CI->getContext());
1840 case ICmpInst::ICMP_SLT:
1841 case ICmpInst::ICMP_SLE:
1842 return CI->getValue().isNegative() ?
1843 ConstantInt::getFalse(CI->getContext()) :
1844 ConstantInt::getTrue(CI->getContext());
1850 if (isa<SExtInst>(LHS)) {
1851 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1853 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1854 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1855 // Compare X and Y. Note that the predicate does not change.
1856 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1857 TD, TLI, DT, MaxRecurse-1))
1860 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1861 // too. If not, then try to deduce the result of the comparison.
1862 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1863 // Compute the constant that would happen if we truncated to SrcTy then
1864 // reextended to DstTy.
1865 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1866 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1868 // If the re-extended constant didn't change then this is effectively
1869 // also a case of comparing two sign-extended values.
1870 if (RExt == CI && MaxRecurse)
1871 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
1875 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1876 // bits there. Use this to work out the result of the comparison.
1879 default: llvm_unreachable("Unknown ICmp predicate!");
1880 case ICmpInst::ICMP_EQ:
1881 return ConstantInt::getFalse(CI->getContext());
1882 case ICmpInst::ICMP_NE:
1883 return ConstantInt::getTrue(CI->getContext());
1885 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1887 case ICmpInst::ICMP_SGT:
1888 case ICmpInst::ICMP_SGE:
1889 return CI->getValue().isNegative() ?
1890 ConstantInt::getTrue(CI->getContext()) :
1891 ConstantInt::getFalse(CI->getContext());
1892 case ICmpInst::ICMP_SLT:
1893 case ICmpInst::ICMP_SLE:
1894 return CI->getValue().isNegative() ?
1895 ConstantInt::getFalse(CI->getContext()) :
1896 ConstantInt::getTrue(CI->getContext());
1898 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1900 case ICmpInst::ICMP_UGT:
1901 case ICmpInst::ICMP_UGE:
1902 // Comparison is true iff the LHS <s 0.
1904 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1905 Constant::getNullValue(SrcTy),
1906 TD, TLI, DT, MaxRecurse-1))
1909 case ICmpInst::ICMP_ULT:
1910 case ICmpInst::ICMP_ULE:
1911 // Comparison is true iff the LHS >=s 0.
1913 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1914 Constant::getNullValue(SrcTy),
1915 TD, TLI, DT, MaxRecurse-1))
1924 // Special logic for binary operators.
1925 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1926 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1927 if (MaxRecurse && (LBO || RBO)) {
1928 // Analyze the case when either LHS or RHS is an add instruction.
1929 Value *A = 0, *B = 0, *C = 0, *D = 0;
1930 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1931 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1932 if (LBO && LBO->getOpcode() == Instruction::Add) {
1933 A = LBO->getOperand(0); B = LBO->getOperand(1);
1934 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1935 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1936 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1938 if (RBO && RBO->getOpcode() == Instruction::Add) {
1939 C = RBO->getOperand(0); D = RBO->getOperand(1);
1940 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1941 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1942 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1945 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1946 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1947 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1948 Constant::getNullValue(RHS->getType()),
1949 TD, TLI, DT, MaxRecurse-1))
1952 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1953 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1954 if (Value *V = SimplifyICmpInst(Pred,
1955 Constant::getNullValue(LHS->getType()),
1956 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
1959 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1960 if (A && C && (A == C || A == D || B == C || B == D) &&
1961 NoLHSWrapProblem && NoRHSWrapProblem) {
1962 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1963 Value *Y = (A == C || A == D) ? B : A;
1964 Value *Z = (C == A || C == B) ? D : C;
1965 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
1970 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1971 bool KnownNonNegative, KnownNegative;
1975 case ICmpInst::ICMP_SGT:
1976 case ICmpInst::ICMP_SGE:
1977 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1978 if (!KnownNonNegative)
1981 case ICmpInst::ICMP_EQ:
1982 case ICmpInst::ICMP_UGT:
1983 case ICmpInst::ICMP_UGE:
1984 return getFalse(ITy);
1985 case ICmpInst::ICMP_SLT:
1986 case ICmpInst::ICMP_SLE:
1987 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1988 if (!KnownNonNegative)
1991 case ICmpInst::ICMP_NE:
1992 case ICmpInst::ICMP_ULT:
1993 case ICmpInst::ICMP_ULE:
1994 return getTrue(ITy);
1997 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1998 bool KnownNonNegative, KnownNegative;
2002 case ICmpInst::ICMP_SGT:
2003 case ICmpInst::ICMP_SGE:
2004 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2005 if (!KnownNonNegative)
2008 case ICmpInst::ICMP_NE:
2009 case ICmpInst::ICMP_UGT:
2010 case ICmpInst::ICMP_UGE:
2011 return getTrue(ITy);
2012 case ICmpInst::ICMP_SLT:
2013 case ICmpInst::ICMP_SLE:
2014 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2015 if (!KnownNonNegative)
2018 case ICmpInst::ICMP_EQ:
2019 case ICmpInst::ICMP_ULT:
2020 case ICmpInst::ICMP_ULE:
2021 return getFalse(ITy);
2026 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2027 // icmp pred (X /u Y), X
2028 if (Pred == ICmpInst::ICMP_UGT)
2029 return getFalse(ITy);
2030 if (Pred == ICmpInst::ICMP_ULE)
2031 return getTrue(ITy);
2034 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2035 LBO->getOperand(1) == RBO->getOperand(1)) {
2036 switch (LBO->getOpcode()) {
2038 case Instruction::UDiv:
2039 case Instruction::LShr:
2040 if (ICmpInst::isSigned(Pred))
2043 case Instruction::SDiv:
2044 case Instruction::AShr:
2045 if (!LBO->isExact() || !RBO->isExact())
2047 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2048 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2051 case Instruction::Shl: {
2052 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2053 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2056 if (!NSW && ICmpInst::isSigned(Pred))
2058 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2059 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2066 // Simplify comparisons involving max/min.
2068 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2069 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2071 // Signed variants on "max(a,b)>=a -> true".
2072 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2073 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2074 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2075 // We analyze this as smax(A, B) pred A.
2077 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2078 (A == LHS || B == LHS)) {
2079 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2080 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2081 // We analyze this as smax(A, B) swapped-pred A.
2082 P = CmpInst::getSwappedPredicate(Pred);
2083 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2084 (A == RHS || B == RHS)) {
2085 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2086 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2087 // We analyze this as smax(-A, -B) swapped-pred -A.
2088 // Note that we do not need to actually form -A or -B thanks to EqP.
2089 P = CmpInst::getSwappedPredicate(Pred);
2090 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2091 (A == LHS || B == LHS)) {
2092 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2093 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2094 // We analyze this as smax(-A, -B) pred -A.
2095 // Note that we do not need to actually form -A or -B thanks to EqP.
2098 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2099 // Cases correspond to "max(A, B) p A".
2103 case CmpInst::ICMP_EQ:
2104 case CmpInst::ICMP_SLE:
2105 // Equivalent to "A EqP B". This may be the same as the condition tested
2106 // in the max/min; if so, we can just return that.
2107 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2109 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2111 // Otherwise, see if "A EqP B" simplifies.
2113 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2116 case CmpInst::ICMP_NE:
2117 case CmpInst::ICMP_SGT: {
2118 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2119 // Equivalent to "A InvEqP B". This may be the same as the condition
2120 // tested in the max/min; if so, we can just return that.
2121 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2123 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2125 // Otherwise, see if "A InvEqP B" simplifies.
2127 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2131 case CmpInst::ICMP_SGE:
2133 return getTrue(ITy);
2134 case CmpInst::ICMP_SLT:
2136 return getFalse(ITy);
2140 // Unsigned variants on "max(a,b)>=a -> true".
2141 P = CmpInst::BAD_ICMP_PREDICATE;
2142 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2143 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2144 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2145 // We analyze this as umax(A, B) pred A.
2147 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2148 (A == LHS || B == LHS)) {
2149 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2150 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2151 // We analyze this as umax(A, B) swapped-pred A.
2152 P = CmpInst::getSwappedPredicate(Pred);
2153 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2154 (A == RHS || B == RHS)) {
2155 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2156 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2157 // We analyze this as umax(-A, -B) swapped-pred -A.
2158 // Note that we do not need to actually form -A or -B thanks to EqP.
2159 P = CmpInst::getSwappedPredicate(Pred);
2160 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2161 (A == LHS || B == LHS)) {
2162 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2163 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2164 // We analyze this as umax(-A, -B) pred -A.
2165 // Note that we do not need to actually form -A or -B thanks to EqP.
2168 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2169 // Cases correspond to "max(A, B) p A".
2173 case CmpInst::ICMP_EQ:
2174 case CmpInst::ICMP_ULE:
2175 // Equivalent to "A EqP B". This may be the same as the condition tested
2176 // in the max/min; if so, we can just return that.
2177 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2179 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2181 // Otherwise, see if "A EqP B" simplifies.
2183 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2186 case CmpInst::ICMP_NE:
2187 case CmpInst::ICMP_UGT: {
2188 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2189 // Equivalent to "A InvEqP B". This may be the same as the condition
2190 // tested in the max/min; if so, we can just return that.
2191 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2193 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2195 // Otherwise, see if "A InvEqP B" simplifies.
2197 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2201 case CmpInst::ICMP_UGE:
2203 return getTrue(ITy);
2204 case CmpInst::ICMP_ULT:
2206 return getFalse(ITy);
2210 // Variants on "max(x,y) >= min(x,z)".
2212 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2213 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2214 (A == C || A == D || B == C || B == D)) {
2215 // max(x, ?) pred min(x, ?).
2216 if (Pred == CmpInst::ICMP_SGE)
2218 return getTrue(ITy);
2219 if (Pred == CmpInst::ICMP_SLT)
2221 return getFalse(ITy);
2222 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2223 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2224 (A == C || A == D || B == C || B == D)) {
2225 // min(x, ?) pred max(x, ?).
2226 if (Pred == CmpInst::ICMP_SLE)
2228 return getTrue(ITy);
2229 if (Pred == CmpInst::ICMP_SGT)
2231 return getFalse(ITy);
2232 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2233 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2234 (A == C || A == D || B == C || B == D)) {
2235 // max(x, ?) pred min(x, ?).
2236 if (Pred == CmpInst::ICMP_UGE)
2238 return getTrue(ITy);
2239 if (Pred == CmpInst::ICMP_ULT)
2241 return getFalse(ITy);
2242 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2243 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2244 (A == C || A == D || B == C || B == D)) {
2245 // min(x, ?) pred max(x, ?).
2246 if (Pred == CmpInst::ICMP_ULE)
2248 return getTrue(ITy);
2249 if (Pred == CmpInst::ICMP_UGT)
2251 return getFalse(ITy);
2254 // Simplify comparisons of GEPs.
2255 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2256 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2257 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2258 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices()) {
2259 // The bases are equal and the indices are constant. Build a constant
2260 // expression GEP with the same indices and a null base pointer to see
2261 // what constant folding can make out of it.
2262 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2263 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2264 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2266 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2267 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2268 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2273 // If the comparison is with the result of a select instruction, check whether
2274 // comparing with either branch of the select always yields the same value.
2275 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2276 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2279 // If the comparison is with the result of a phi instruction, check whether
2280 // doing the compare with each incoming phi value yields a common result.
2281 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2282 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2288 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2289 const TargetData *TD,
2290 const TargetLibraryInfo *TLI,
2291 const DominatorTree *DT) {
2292 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2295 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2296 /// fold the result. If not, this returns null.
2297 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2298 const TargetData *TD,
2299 const TargetLibraryInfo *TLI,
2300 const DominatorTree *DT,
2301 unsigned MaxRecurse) {
2302 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2303 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2305 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2306 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2307 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
2309 // If we have a constant, make sure it is on the RHS.
2310 std::swap(LHS, RHS);
2311 Pred = CmpInst::getSwappedPredicate(Pred);
2314 // Fold trivial predicates.
2315 if (Pred == FCmpInst::FCMP_FALSE)
2316 return ConstantInt::get(GetCompareTy(LHS), 0);
2317 if (Pred == FCmpInst::FCMP_TRUE)
2318 return ConstantInt::get(GetCompareTy(LHS), 1);
2320 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2321 return UndefValue::get(GetCompareTy(LHS));
2323 // fcmp x,x -> true/false. Not all compares are foldable.
2325 if (CmpInst::isTrueWhenEqual(Pred))
2326 return ConstantInt::get(GetCompareTy(LHS), 1);
2327 if (CmpInst::isFalseWhenEqual(Pred))
2328 return ConstantInt::get(GetCompareTy(LHS), 0);
2331 // Handle fcmp with constant RHS
2332 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2333 // If the constant is a nan, see if we can fold the comparison based on it.
2334 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2335 if (CFP->getValueAPF().isNaN()) {
2336 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2337 return ConstantInt::getFalse(CFP->getContext());
2338 assert(FCmpInst::isUnordered(Pred) &&
2339 "Comparison must be either ordered or unordered!");
2340 // True if unordered.
2341 return ConstantInt::getTrue(CFP->getContext());
2343 // Check whether the constant is an infinity.
2344 if (CFP->getValueAPF().isInfinity()) {
2345 if (CFP->getValueAPF().isNegative()) {
2347 case FCmpInst::FCMP_OLT:
2348 // No value is ordered and less than negative infinity.
2349 return ConstantInt::getFalse(CFP->getContext());
2350 case FCmpInst::FCMP_UGE:
2351 // All values are unordered with or at least negative infinity.
2352 return ConstantInt::getTrue(CFP->getContext());
2358 case FCmpInst::FCMP_OGT:
2359 // No value is ordered and greater than infinity.
2360 return ConstantInt::getFalse(CFP->getContext());
2361 case FCmpInst::FCMP_ULE:
2362 // All values are unordered with and at most infinity.
2363 return ConstantInt::getTrue(CFP->getContext());
2372 // If the comparison is with the result of a select instruction, check whether
2373 // comparing with either branch of the select always yields the same value.
2374 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2375 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2378 // If the comparison is with the result of a phi instruction, check whether
2379 // doing the compare with each incoming phi value yields a common result.
2380 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2381 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2387 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2388 const TargetData *TD,
2389 const TargetLibraryInfo *TLI,
2390 const DominatorTree *DT) {
2391 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2394 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2395 /// the result. If not, this returns null.
2396 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2397 const TargetData *TD, const DominatorTree *) {
2398 // select true, X, Y -> X
2399 // select false, X, Y -> Y
2400 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2401 return CB->getZExtValue() ? TrueVal : FalseVal;
2403 // select C, X, X -> X
2404 if (TrueVal == FalseVal)
2407 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2408 if (isa<Constant>(TrueVal))
2412 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2414 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2420 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2421 /// fold the result. If not, this returns null.
2422 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2423 const DominatorTree *) {
2424 // The type of the GEP pointer operand.
2425 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2426 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2430 // getelementptr P -> P.
2431 if (Ops.size() == 1)
2434 if (isa<UndefValue>(Ops[0])) {
2435 // Compute the (pointer) type returned by the GEP instruction.
2436 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2437 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2438 return UndefValue::get(GEPTy);
2441 if (Ops.size() == 2) {
2442 // getelementptr P, 0 -> P.
2443 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2446 // getelementptr P, N -> P if P points to a type of zero size.
2448 Type *Ty = PtrTy->getElementType();
2449 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2454 // Check to see if this is constant foldable.
2455 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2456 if (!isa<Constant>(Ops[i]))
2459 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2462 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2463 /// can fold the result. If not, this returns null.
2464 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2465 ArrayRef<unsigned> Idxs,
2467 const DominatorTree *) {
2468 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2469 if (Constant *CVal = dyn_cast<Constant>(Val))
2470 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2472 // insertvalue x, undef, n -> x
2473 if (match(Val, m_Undef()))
2476 // insertvalue x, (extractvalue y, n), n
2477 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2478 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2479 EV->getIndices() == Idxs) {
2480 // insertvalue undef, (extractvalue y, n), n -> y
2481 if (match(Agg, m_Undef()))
2482 return EV->getAggregateOperand();
2484 // insertvalue y, (extractvalue y, n), n -> y
2485 if (Agg == EV->getAggregateOperand())
2492 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2493 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2494 // If all of the PHI's incoming values are the same then replace the PHI node
2495 // with the common value.
2496 Value *CommonValue = 0;
2497 bool HasUndefInput = false;
2498 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2499 Value *Incoming = PN->getIncomingValue(i);
2500 // If the incoming value is the phi node itself, it can safely be skipped.
2501 if (Incoming == PN) continue;
2502 if (isa<UndefValue>(Incoming)) {
2503 // Remember that we saw an undef value, but otherwise ignore them.
2504 HasUndefInput = true;
2507 if (CommonValue && Incoming != CommonValue)
2508 return 0; // Not the same, bail out.
2509 CommonValue = Incoming;
2512 // If CommonValue is null then all of the incoming values were either undef or
2513 // equal to the phi node itself.
2515 return UndefValue::get(PN->getType());
2517 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2518 // instruction, we cannot return X as the result of the PHI node unless it
2519 // dominates the PHI block.
2521 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2526 //=== Helper functions for higher up the class hierarchy.
2528 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2529 /// fold the result. If not, this returns null.
2530 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2531 const TargetData *TD,
2532 const TargetLibraryInfo *TLI,
2533 const DominatorTree *DT,
2534 unsigned MaxRecurse) {
2536 case Instruction::Add:
2537 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2538 TD, TLI, DT, MaxRecurse);
2539 case Instruction::Sub:
2540 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2541 TD, TLI, DT, MaxRecurse);
2542 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2544 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2546 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2548 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2550 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2552 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2554 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2556 case Instruction::Shl:
2557 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2558 TD, TLI, DT, MaxRecurse);
2559 case Instruction::LShr:
2560 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2562 case Instruction::AShr:
2563 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2565 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2567 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2569 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2572 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2573 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2574 Constant *COps[] = {CLHS, CRHS};
2575 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
2578 // If the operation is associative, try some generic simplifications.
2579 if (Instruction::isAssociative(Opcode))
2580 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
2584 // If the operation is with the result of a select instruction, check whether
2585 // operating on either branch of the select always yields the same value.
2586 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2587 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
2591 // If the operation is with the result of a phi instruction, check whether
2592 // operating on all incoming values of the phi always yields the same value.
2593 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2594 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2602 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2603 const TargetData *TD, const TargetLibraryInfo *TLI,
2604 const DominatorTree *DT) {
2605 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
2608 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2609 /// fold the result.
2610 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2611 const TargetData *TD,
2612 const TargetLibraryInfo *TLI,
2613 const DominatorTree *DT,
2614 unsigned MaxRecurse) {
2615 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2616 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2617 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2620 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2621 const TargetData *TD, const TargetLibraryInfo *TLI,
2622 const DominatorTree *DT) {
2623 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2626 static Value *SimplifyCallInst(CallInst *CI) {
2627 // call undef -> undef
2628 if (isa<UndefValue>(CI->getCalledValue()))
2629 return UndefValue::get(CI->getType());
2634 /// SimplifyInstruction - See if we can compute a simplified version of this
2635 /// instruction. If not, this returns null.
2636 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2637 const TargetLibraryInfo *TLI,
2638 const DominatorTree *DT) {
2641 switch (I->getOpcode()) {
2643 Result = ConstantFoldInstruction(I, TD, TLI);
2645 case Instruction::Add:
2646 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2647 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2648 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2651 case Instruction::Sub:
2652 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2653 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2654 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2657 case Instruction::Mul:
2658 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2660 case Instruction::SDiv:
2661 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2663 case Instruction::UDiv:
2664 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2666 case Instruction::FDiv:
2667 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2669 case Instruction::SRem:
2670 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2672 case Instruction::URem:
2673 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2675 case Instruction::FRem:
2676 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2678 case Instruction::Shl:
2679 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2680 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2681 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2684 case Instruction::LShr:
2685 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2686 cast<BinaryOperator>(I)->isExact(),
2689 case Instruction::AShr:
2690 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2691 cast<BinaryOperator>(I)->isExact(),
2694 case Instruction::And:
2695 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2697 case Instruction::Or:
2698 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2700 case Instruction::Xor:
2701 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2703 case Instruction::ICmp:
2704 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2705 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2707 case Instruction::FCmp:
2708 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2709 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2711 case Instruction::Select:
2712 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2713 I->getOperand(2), TD, DT);
2715 case Instruction::GetElementPtr: {
2716 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2717 Result = SimplifyGEPInst(Ops, TD, DT);
2720 case Instruction::InsertValue: {
2721 InsertValueInst *IV = cast<InsertValueInst>(I);
2722 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2723 IV->getInsertedValueOperand(),
2724 IV->getIndices(), TD, DT);
2727 case Instruction::PHI:
2728 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2730 case Instruction::Call:
2731 Result = SimplifyCallInst(cast<CallInst>(I));
2735 /// If called on unreachable code, the above logic may report that the
2736 /// instruction simplified to itself. Make life easier for users by
2737 /// detecting that case here, returning a safe value instead.
2738 return Result == I ? UndefValue::get(I->getType()) : Result;
2741 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2742 /// delete the From instruction. In addition to a basic RAUW, this does a
2743 /// recursive simplification of the newly formed instructions. This catches
2744 /// things where one simplification exposes other opportunities. This only
2745 /// simplifies and deletes scalar operations, it does not change the CFG.
2747 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2748 const TargetData *TD,
2749 const TargetLibraryInfo *TLI,
2750 const DominatorTree *DT) {
2751 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2753 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2754 // we can know if it gets deleted out from under us or replaced in a
2755 // recursive simplification.
2756 WeakVH FromHandle(From);
2757 WeakVH ToHandle(To);
2759 while (!From->use_empty()) {
2760 // Update the instruction to use the new value.
2761 Use &TheUse = From->use_begin().getUse();
2762 Instruction *User = cast<Instruction>(TheUse.getUser());
2765 // Check to see if the instruction can be folded due to the operand
2766 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2767 // the 'or' with -1.
2768 Value *SimplifiedVal;
2770 // Sanity check to make sure 'User' doesn't dangle across
2771 // SimplifyInstruction.
2772 AssertingVH<> UserHandle(User);
2774 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
2775 if (SimplifiedVal == 0) continue;
2778 // Recursively simplify this user to the new value.
2779 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
2780 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2783 assert(ToHandle && "To value deleted by recursive simplification?");
2785 // If the recursive simplification ended up revisiting and deleting
2786 // 'From' then we're done.
2791 // If 'From' has value handles referring to it, do a real RAUW to update them.
2792 From->replaceAllUsesWith(To);
2794 From->eraseFromParent();