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->isReachableFromEntry(P->getParent()) ||
97 !DT->isReachableFromEntry(I->getParent()) || DT->dominates(I, P);
99 // Otherwise, if the instruction is in the entry block, and is not an invoke,
100 // then it obviously dominates all phi nodes.
101 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
108 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
109 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
110 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
111 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
112 /// Returns the simplified value, or null if no simplification was performed.
113 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
114 unsigned OpcToExpand, const TargetData *TD,
115 const TargetLibraryInfo *TLI, const DominatorTree *DT,
116 unsigned MaxRecurse) {
117 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
118 // Recursion is always used, so bail out at once if we already hit the limit.
122 // Check whether the expression has the form "(A op' B) op C".
123 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
124 if (Op0->getOpcode() == OpcodeToExpand) {
125 // It does! Try turning it into "(A op C) op' (B op C)".
126 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
127 // Do "A op C" and "B op C" both simplify?
128 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
129 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
130 // They do! Return "L op' R" if it simplifies or is already available.
131 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
132 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
133 && L == B && R == A)) {
137 // Otherwise return "L op' R" if it simplifies.
138 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
146 // Check whether the expression has the form "A op (B op' C)".
147 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
148 if (Op1->getOpcode() == OpcodeToExpand) {
149 // It does! Try turning it into "(A op B) op' (A op C)".
150 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
151 // Do "A op B" and "A op C" both simplify?
152 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
153 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
154 // They do! Return "L op' R" if it simplifies or is already available.
155 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
156 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
157 && L == C && R == B)) {
161 // Otherwise return "L op' R" if it simplifies.
162 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
173 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
174 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
175 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
176 /// Returns the simplified value, or null if no simplification was performed.
177 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
178 unsigned OpcToExtract, const TargetData *TD,
179 const TargetLibraryInfo *TLI,
180 const DominatorTree *DT,
181 unsigned MaxRecurse) {
182 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
183 // Recursion is always used, so bail out at once if we already hit the limit.
187 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
188 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
190 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
191 !Op1 || Op1->getOpcode() != OpcodeToExtract)
194 // The expression has the form "(A op' B) op (C op' D)".
195 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
196 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
198 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
199 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
200 // commutative case, "(A op' B) op (C op' A)"?
201 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
202 Value *DD = A == C ? D : C;
203 // Form "A op' (B op DD)" if it simplifies completely.
204 // Does "B op DD" simplify?
205 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
206 // It does! Return "A op' V" if it simplifies or is already available.
207 // If V equals B then "A op' V" is just the LHS. If V equals DD then
208 // "A op' V" is just the RHS.
209 if (V == B || V == DD) {
211 return V == B ? LHS : RHS;
213 // Otherwise return "A op' V" if it simplifies.
214 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
222 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
223 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
224 // commutative case, "(A op' B) op (B op' D)"?
225 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
226 Value *CC = B == D ? C : D;
227 // Form "(A op CC) op' B" if it simplifies completely..
228 // Does "A op CC" simplify?
229 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
230 // It does! Return "V op' B" if it simplifies or is already available.
231 // If V equals A then "V op' B" is just the LHS. If V equals CC then
232 // "V op' B" is just the RHS.
233 if (V == A || V == CC) {
235 return V == A ? LHS : RHS;
237 // Otherwise return "V op' B" if it simplifies.
238 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
249 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
250 /// operations. Returns the simpler value, or null if none was found.
251 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
252 const TargetData *TD,
253 const TargetLibraryInfo *TLI,
254 const DominatorTree *DT,
255 unsigned MaxRecurse) {
256 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
257 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
259 // Recursion is always used, so bail out at once if we already hit the limit.
263 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
264 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
266 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
267 if (Op0 && Op0->getOpcode() == Opcode) {
268 Value *A = Op0->getOperand(0);
269 Value *B = Op0->getOperand(1);
272 // Does "B op C" simplify?
273 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
274 // It does! Return "A op V" if it simplifies or is already available.
275 // If V equals B then "A op V" is just the LHS.
276 if (V == B) return LHS;
277 // Otherwise return "A op V" if it simplifies.
278 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
285 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
286 if (Op1 && Op1->getOpcode() == Opcode) {
288 Value *B = Op1->getOperand(0);
289 Value *C = Op1->getOperand(1);
291 // Does "A op B" simplify?
292 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
293 // It does! Return "V op C" if it simplifies or is already available.
294 // If V equals B then "V op C" is just the RHS.
295 if (V == B) return RHS;
296 // Otherwise return "V op C" if it simplifies.
297 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
304 // The remaining transforms require commutativity as well as associativity.
305 if (!Instruction::isCommutative(Opcode))
308 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
309 if (Op0 && Op0->getOpcode() == Opcode) {
310 Value *A = Op0->getOperand(0);
311 Value *B = Op0->getOperand(1);
314 // Does "C op A" simplify?
315 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
316 // It does! Return "V op B" if it simplifies or is already available.
317 // If V equals A then "V op B" is just the LHS.
318 if (V == A) return LHS;
319 // Otherwise return "V op B" if it simplifies.
320 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
327 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
328 if (Op1 && Op1->getOpcode() == Opcode) {
330 Value *B = Op1->getOperand(0);
331 Value *C = Op1->getOperand(1);
333 // Does "C op A" simplify?
334 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
335 // It does! Return "B op V" if it simplifies or is already available.
336 // If V equals C then "B op V" is just the RHS.
337 if (V == C) return RHS;
338 // Otherwise return "B op V" if it simplifies.
339 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
349 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
350 /// instruction as an operand, try to simplify the binop by seeing whether
351 /// evaluating it on both branches of the select results in the same value.
352 /// Returns the common value if so, otherwise returns null.
353 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
354 const TargetData *TD,
355 const TargetLibraryInfo *TLI,
356 const DominatorTree *DT,
357 unsigned MaxRecurse) {
358 // Recursion is always used, so bail out at once if we already hit the limit.
363 if (isa<SelectInst>(LHS)) {
364 SI = cast<SelectInst>(LHS);
366 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
367 SI = cast<SelectInst>(RHS);
370 // Evaluate the BinOp on the true and false branches of the select.
374 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
375 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
377 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
378 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
381 // If they simplified to the same value, then return the common value.
382 // If they both failed to simplify then return null.
386 // If one branch simplified to undef, return the other one.
387 if (TV && isa<UndefValue>(TV))
389 if (FV && isa<UndefValue>(FV))
392 // If applying the operation did not change the true and false select values,
393 // then the result of the binop is the select itself.
394 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
397 // If one branch simplified and the other did not, and the simplified
398 // value is equal to the unsimplified one, return the simplified value.
399 // For example, select (cond, X, X & Z) & Z -> X & Z.
400 if ((FV && !TV) || (TV && !FV)) {
401 // Check that the simplified value has the form "X op Y" where "op" is the
402 // same as the original operation.
403 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
404 if (Simplified && Simplified->getOpcode() == Opcode) {
405 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
406 // We already know that "op" is the same as for the simplified value. See
407 // if the operands match too. If so, return the simplified value.
408 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
409 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
410 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
411 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
412 Simplified->getOperand(1) == UnsimplifiedRHS)
414 if (Simplified->isCommutative() &&
415 Simplified->getOperand(1) == UnsimplifiedLHS &&
416 Simplified->getOperand(0) == UnsimplifiedRHS)
424 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
425 /// try to simplify the comparison by seeing whether both branches of the select
426 /// result in the same value. Returns the common value if so, otherwise returns
428 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
429 Value *RHS, const TargetData *TD,
430 const TargetLibraryInfo *TLI,
431 const DominatorTree *DT,
432 unsigned MaxRecurse) {
433 // Recursion is always used, so bail out at once if we already hit the limit.
437 // Make sure the select is on the LHS.
438 if (!isa<SelectInst>(LHS)) {
440 Pred = CmpInst::getSwappedPredicate(Pred);
442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443 SelectInst *SI = cast<SelectInst>(LHS);
444 Value *Cond = SI->getCondition();
445 Value *TV = SI->getTrueValue();
446 Value *FV = SI->getFalseValue();
448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
449 // Does "cmp TV, RHS" simplify?
450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
452 // It not only simplified, it simplified to the select condition. Replace
454 TCmp = getTrue(Cond->getType());
456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
457 // condition then we can replace it with 'true'. Otherwise give up.
458 if (!isSameCompare(Cond, Pred, TV, RHS))
460 TCmp = getTrue(Cond->getType());
463 // Does "cmp FV, RHS" simplify?
464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
466 // It not only simplified, it simplified to the select condition. Replace
468 FCmp = getFalse(Cond->getType());
470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
471 // condition then we can replace it with 'false'. Otherwise give up.
472 if (!isSameCompare(Cond, Pred, FV, RHS))
474 FCmp = getFalse(Cond->getType());
477 // If both sides simplified to the same value, then use it as the result of
478 // the original comparison.
482 // The remaining cases only make sense if the select condition has the same
483 // type as the result of the comparison, so bail out if this is not so.
484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
486 // If the false value simplified to false, then the result of the compare
487 // is equal to "Cond && TCmp". This also catches the case when the false
488 // value simplified to false and the true value to true, returning "Cond".
489 if (match(FCmp, m_Zero()))
490 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
492 // If the true value simplified to true, then the result of the compare
493 // is equal to "Cond || FCmp".
494 if (match(TCmp, m_One()))
495 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
497 // Finally, if the false value simplified to true and the true value to
498 // false, then the result of the compare is equal to "!Cond".
499 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
502 TD, TLI, DT, MaxRecurse))
508 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510 /// it on the incoming phi values yields the same result for every value. If so
511 /// returns the common value, otherwise returns null.
512 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
513 const TargetData *TD,
514 const TargetLibraryInfo *TLI,
515 const DominatorTree *DT,
516 unsigned MaxRecurse) {
517 // Recursion is always used, so bail out at once if we already hit the limit.
522 if (isa<PHINode>(LHS)) {
523 PI = cast<PHINode>(LHS);
524 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
525 if (!ValueDominatesPHI(RHS, PI, DT))
528 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
529 PI = cast<PHINode>(RHS);
530 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
531 if (!ValueDominatesPHI(LHS, PI, DT))
535 // Evaluate the BinOp on the incoming phi values.
536 Value *CommonValue = 0;
537 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
538 Value *Incoming = PI->getIncomingValue(i);
539 // If the incoming value is the phi node itself, it can safely be skipped.
540 if (Incoming == PI) continue;
541 Value *V = PI == LHS ?
542 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
543 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
544 // If the operation failed to simplify, or simplified to a different value
545 // to previously, then give up.
546 if (!V || (CommonValue && V != CommonValue))
554 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
555 /// try to simplify the comparison by seeing whether comparing with all of the
556 /// incoming phi values yields the same result every time. If so returns the
557 /// common result, otherwise returns null.
558 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
559 const TargetData *TD,
560 const TargetLibraryInfo *TLI,
561 const DominatorTree *DT,
562 unsigned MaxRecurse) {
563 // Recursion is always used, so bail out at once if we already hit the limit.
567 // Make sure the phi is on the LHS.
568 if (!isa<PHINode>(LHS)) {
570 Pred = CmpInst::getSwappedPredicate(Pred);
572 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
573 PHINode *PI = cast<PHINode>(LHS);
575 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
576 if (!ValueDominatesPHI(RHS, PI, DT))
579 // Evaluate the BinOp on the incoming phi values.
580 Value *CommonValue = 0;
581 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
582 Value *Incoming = PI->getIncomingValue(i);
583 // If the incoming value is the phi node itself, it can safely be skipped.
584 if (Incoming == PI) continue;
585 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
586 // If the operation failed to simplify, or simplified to a different value
587 // to previously, then give up.
588 if (!V || (CommonValue && V != CommonValue))
596 /// SimplifyAddInst - Given operands for an Add, see if we can
597 /// fold the result. If not, this returns null.
598 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
599 const TargetData *TD,
600 const TargetLibraryInfo *TLI,
601 const DominatorTree *DT,
602 unsigned MaxRecurse) {
603 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
604 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
605 Constant *Ops[] = { CLHS, CRHS };
606 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
610 // Canonicalize the constant to the RHS.
614 // X + undef -> undef
615 if (match(Op1, m_Undef()))
619 if (match(Op1, m_Zero()))
626 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
627 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
630 // X + ~X -> -1 since ~X = -X-1
631 if (match(Op0, m_Not(m_Specific(Op1))) ||
632 match(Op1, m_Not(m_Specific(Op0))))
633 return Constant::getAllOnesValue(Op0->getType());
636 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
637 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
640 // Try some generic simplifications for associative operations.
641 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
645 // Mul distributes over Add. Try some generic simplifications based on this.
646 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
647 TD, TLI, DT, MaxRecurse))
650 // Threading Add over selects and phi nodes is pointless, so don't bother.
651 // Threading over the select in "A + select(cond, B, C)" means evaluating
652 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
653 // only if B and C are equal. If B and C are equal then (since we assume
654 // that operands have already been simplified) "select(cond, B, C)" should
655 // have been simplified to the common value of B and C already. Analysing
656 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
657 // for threading over phi nodes.
662 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
663 const TargetData *TD, const TargetLibraryInfo *TLI,
664 const DominatorTree *DT) {
665 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
668 /// SimplifySubInst - Given operands for a Sub, see if we can
669 /// fold the result. If not, this returns null.
670 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
671 const TargetData *TD,
672 const TargetLibraryInfo *TLI,
673 const DominatorTree *DT,
674 unsigned MaxRecurse) {
675 if (Constant *CLHS = dyn_cast<Constant>(Op0))
676 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
677 Constant *Ops[] = { CLHS, CRHS };
678 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
682 // X - undef -> undef
683 // undef - X -> undef
684 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
685 return UndefValue::get(Op0->getType());
688 if (match(Op1, m_Zero()))
693 return Constant::getNullValue(Op0->getType());
698 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
699 match(Op0, m_Shl(m_Specific(Op1), m_One())))
702 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
703 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
704 Value *Y = 0, *Z = Op1;
705 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
706 // See if "V === Y - Z" simplifies.
707 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
708 // It does! Now see if "X + V" simplifies.
709 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
711 // It does, we successfully reassociated!
715 // See if "V === X - Z" simplifies.
716 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
717 // It does! Now see if "Y + V" simplifies.
718 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
720 // It does, we successfully reassociated!
726 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
727 // For example, X - (X + 1) -> -1
729 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
730 // See if "V === X - Y" simplifies.
731 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
732 // It does! Now see if "V - Z" simplifies.
733 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
735 // It does, we successfully reassociated!
739 // See if "V === X - Z" simplifies.
740 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
741 // It does! Now see if "V - Y" simplifies.
742 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
744 // It does, we successfully reassociated!
750 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
751 // For example, X - (X - Y) -> Y.
753 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
754 // See if "V === Z - X" simplifies.
755 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
756 // It does! Now see if "V + Y" simplifies.
757 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
759 // It does, we successfully reassociated!
764 // Mul distributes over Sub. Try some generic simplifications based on this.
765 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
766 TD, TLI, DT, MaxRecurse))
770 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
771 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
774 // Threading Sub over selects and phi nodes is pointless, so don't bother.
775 // Threading over the select in "A - select(cond, B, C)" means evaluating
776 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
777 // only if B and C are equal. If B and C are equal then (since we assume
778 // that operands have already been simplified) "select(cond, B, C)" should
779 // have been simplified to the common value of B and C already. Analysing
780 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
781 // for threading over phi nodes.
786 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
787 const TargetData *TD,
788 const TargetLibraryInfo *TLI,
789 const DominatorTree *DT) {
790 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
793 /// SimplifyMulInst - Given operands for a Mul, see if we can
794 /// fold the result. If not, this returns null.
795 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
796 const TargetLibraryInfo *TLI,
797 const DominatorTree *DT, unsigned MaxRecurse) {
798 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
799 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
800 Constant *Ops[] = { CLHS, CRHS };
801 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
805 // Canonicalize the constant to the RHS.
810 if (match(Op1, m_Undef()))
811 return Constant::getNullValue(Op0->getType());
814 if (match(Op1, m_Zero()))
818 if (match(Op1, m_One()))
821 // (X / Y) * Y -> X if the division is exact.
823 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
824 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
828 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
829 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
832 // Try some generic simplifications for associative operations.
833 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
837 // Mul distributes over Add. Try some generic simplifications based on this.
838 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
839 TD, TLI, DT, MaxRecurse))
842 // If the operation is with the result of a select instruction, check whether
843 // operating on either branch of the select always yields the same value.
844 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
845 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
849 // If the operation is with the result of a phi instruction, check whether
850 // operating on all incoming values of the phi always yields the same value.
851 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
852 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
859 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
860 const TargetLibraryInfo *TLI,
861 const DominatorTree *DT) {
862 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
865 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
866 /// fold the result. If not, this returns null.
867 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
868 const TargetData *TD, const TargetLibraryInfo *TLI,
869 const DominatorTree *DT, unsigned MaxRecurse) {
870 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
871 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
872 Constant *Ops[] = { C0, C1 };
873 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
877 bool isSigned = Opcode == Instruction::SDiv;
879 // X / undef -> undef
880 if (match(Op1, m_Undef()))
884 if (match(Op0, m_Undef()))
885 return Constant::getNullValue(Op0->getType());
887 // 0 / X -> 0, we don't need to preserve faults!
888 if (match(Op0, m_Zero()))
892 if (match(Op1, m_One()))
895 if (Op0->getType()->isIntegerTy(1))
896 // It can't be division by zero, hence it must be division by one.
901 return ConstantInt::get(Op0->getType(), 1);
903 // (X * Y) / Y -> X if the multiplication does not overflow.
904 Value *X = 0, *Y = 0;
905 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
906 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
907 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
908 // If the Mul knows it does not overflow, then we are good to go.
909 if ((isSigned && Mul->hasNoSignedWrap()) ||
910 (!isSigned && Mul->hasNoUnsignedWrap()))
912 // If X has the form X = A / Y then X * Y cannot overflow.
913 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
914 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
918 // (X rem Y) / Y -> 0
919 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
920 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
921 return Constant::getNullValue(Op0->getType());
923 // If the operation is with the result of a select instruction, check whether
924 // operating on either branch of the select always yields the same value.
925 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
926 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
930 // If the operation is with the result of a phi instruction, check whether
931 // operating on all incoming values of the phi always yields the same value.
932 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
933 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
940 /// SimplifySDivInst - Given operands for an SDiv, see if we can
941 /// fold the result. If not, this returns null.
942 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
943 const TargetLibraryInfo *TLI,
944 const DominatorTree *DT, unsigned MaxRecurse) {
945 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
952 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
953 const TargetLibraryInfo *TLI,
954 const DominatorTree *DT) {
955 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
958 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
959 /// fold the result. If not, this returns null.
960 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
961 const TargetLibraryInfo *TLI,
962 const DominatorTree *DT, unsigned MaxRecurse) {
963 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
970 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
971 const TargetLibraryInfo *TLI,
972 const DominatorTree *DT) {
973 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
976 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
977 const TargetLibraryInfo *,
978 const DominatorTree *, unsigned) {
979 // undef / X -> undef (the undef could be a snan).
980 if (match(Op0, m_Undef()))
983 // X / undef -> undef
984 if (match(Op1, m_Undef()))
990 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
991 const TargetLibraryInfo *TLI,
992 const DominatorTree *DT) {
993 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
996 /// SimplifyRem - Given operands for an SRem or URem, see if we can
997 /// fold the result. If not, this returns null.
998 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
999 const TargetData *TD, const TargetLibraryInfo *TLI,
1000 const DominatorTree *DT, unsigned MaxRecurse) {
1001 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1002 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1003 Constant *Ops[] = { C0, C1 };
1004 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1008 // X % undef -> undef
1009 if (match(Op1, m_Undef()))
1013 if (match(Op0, m_Undef()))
1014 return Constant::getNullValue(Op0->getType());
1016 // 0 % X -> 0, we don't need to preserve faults!
1017 if (match(Op0, m_Zero()))
1020 // X % 0 -> undef, we don't need to preserve faults!
1021 if (match(Op1, m_Zero()))
1022 return UndefValue::get(Op0->getType());
1025 if (match(Op1, m_One()))
1026 return Constant::getNullValue(Op0->getType());
1028 if (Op0->getType()->isIntegerTy(1))
1029 // It can't be remainder by zero, hence it must be remainder by one.
1030 return Constant::getNullValue(Op0->getType());
1034 return Constant::getNullValue(Op0->getType());
1036 // If the operation is with the result of a select instruction, check whether
1037 // operating on either branch of the select always yields the same value.
1038 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1039 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1042 // If the operation is with the result of a phi instruction, check whether
1043 // operating on all incoming values of the phi always yields the same value.
1044 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1045 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1051 /// SimplifySRemInst - Given operands for an SRem, see if we can
1052 /// fold the result. If not, this returns null.
1053 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1054 const TargetLibraryInfo *TLI,
1055 const DominatorTree *DT,
1056 unsigned MaxRecurse) {
1057 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1063 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1064 const TargetLibraryInfo *TLI,
1065 const DominatorTree *DT) {
1066 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1069 /// SimplifyURemInst - Given operands for a URem, see if we can
1070 /// fold the result. If not, this returns null.
1071 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1072 const TargetLibraryInfo *TLI,
1073 const DominatorTree *DT,
1074 unsigned MaxRecurse) {
1075 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1081 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1082 const TargetLibraryInfo *TLI,
1083 const DominatorTree *DT) {
1084 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1087 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1088 const TargetLibraryInfo *,
1089 const DominatorTree *,
1091 // undef % X -> undef (the undef could be a snan).
1092 if (match(Op0, m_Undef()))
1095 // X % undef -> undef
1096 if (match(Op1, m_Undef()))
1102 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1103 const TargetLibraryInfo *TLI,
1104 const DominatorTree *DT) {
1105 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1108 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1109 /// fold the result. If not, this returns null.
1110 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1111 const TargetData *TD, const TargetLibraryInfo *TLI,
1112 const DominatorTree *DT, unsigned MaxRecurse) {
1113 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1114 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1115 Constant *Ops[] = { C0, C1 };
1116 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1120 // 0 shift by X -> 0
1121 if (match(Op0, m_Zero()))
1124 // X shift by 0 -> X
1125 if (match(Op1, m_Zero()))
1128 // X shift by undef -> undef because it may shift by the bitwidth.
1129 if (match(Op1, m_Undef()))
1132 // Shifting by the bitwidth or more is undefined.
1133 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1134 if (CI->getValue().getLimitedValue() >=
1135 Op0->getType()->getScalarSizeInBits())
1136 return UndefValue::get(Op0->getType());
1138 // If the operation is with the result of a select instruction, check whether
1139 // operating on either branch of the select always yields the same value.
1140 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1141 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1144 // If the operation is with the result of a phi instruction, check whether
1145 // operating on all incoming values of the phi always yields the same value.
1146 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1147 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1153 /// SimplifyShlInst - Given operands for an Shl, see if we can
1154 /// fold the result. If not, this returns null.
1155 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1156 const TargetData *TD,
1157 const TargetLibraryInfo *TLI,
1158 const DominatorTree *DT, unsigned MaxRecurse) {
1159 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
1163 if (match(Op0, m_Undef()))
1164 return Constant::getNullValue(Op0->getType());
1166 // (X >> A) << A -> X
1168 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1173 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1174 const TargetData *TD, const TargetLibraryInfo *TLI,
1175 const DominatorTree *DT) {
1176 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
1179 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1180 /// fold the result. If not, this returns null.
1181 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1182 const TargetData *TD,
1183 const TargetLibraryInfo *TLI,
1184 const DominatorTree *DT,
1185 unsigned MaxRecurse) {
1186 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1190 if (match(Op0, m_Undef()))
1191 return Constant::getNullValue(Op0->getType());
1193 // (X << A) >> A -> X
1195 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1196 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1202 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1203 const TargetData *TD,
1204 const TargetLibraryInfo *TLI,
1205 const DominatorTree *DT) {
1206 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1209 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1210 /// fold the result. If not, this returns null.
1211 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1212 const TargetData *TD,
1213 const TargetLibraryInfo *TLI,
1214 const DominatorTree *DT,
1215 unsigned MaxRecurse) {
1216 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1219 // all ones >>a X -> all ones
1220 if (match(Op0, m_AllOnes()))
1223 // undef >>a X -> all ones
1224 if (match(Op0, m_Undef()))
1225 return Constant::getAllOnesValue(Op0->getType());
1227 // (X << A) >> A -> X
1229 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1230 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1236 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1237 const TargetData *TD,
1238 const TargetLibraryInfo *TLI,
1239 const DominatorTree *DT) {
1240 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1243 /// SimplifyAndInst - Given operands for an And, see if we can
1244 /// fold the result. If not, this returns null.
1245 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1246 const TargetLibraryInfo *TLI,
1247 const DominatorTree *DT,
1248 unsigned MaxRecurse) {
1249 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1250 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1251 Constant *Ops[] = { CLHS, CRHS };
1252 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1256 // Canonicalize the constant to the RHS.
1257 std::swap(Op0, Op1);
1261 if (match(Op1, m_Undef()))
1262 return Constant::getNullValue(Op0->getType());
1269 if (match(Op1, m_Zero()))
1273 if (match(Op1, m_AllOnes()))
1276 // A & ~A = ~A & A = 0
1277 if (match(Op0, m_Not(m_Specific(Op1))) ||
1278 match(Op1, m_Not(m_Specific(Op0))))
1279 return Constant::getNullValue(Op0->getType());
1282 Value *A = 0, *B = 0;
1283 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1284 (A == Op1 || B == Op1))
1288 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1289 (A == Op0 || B == Op0))
1292 // A & (-A) = A if A is a power of two or zero.
1293 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1294 match(Op1, m_Neg(m_Specific(Op0)))) {
1295 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1297 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1301 // Try some generic simplifications for associative operations.
1302 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1306 // And distributes over Or. Try some generic simplifications based on this.
1307 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1308 TD, TLI, DT, MaxRecurse))
1311 // And distributes over Xor. Try some generic simplifications based on this.
1312 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1313 TD, TLI, DT, MaxRecurse))
1316 // Or distributes over And. Try some generic simplifications based on this.
1317 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1318 TD, TLI, DT, MaxRecurse))
1321 // If the operation is with the result of a select instruction, check whether
1322 // operating on either branch of the select always yields the same value.
1323 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1324 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1328 // If the operation is with the result of a phi instruction, check whether
1329 // operating on all incoming values of the phi always yields the same value.
1330 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1331 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
1338 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1339 const TargetLibraryInfo *TLI,
1340 const DominatorTree *DT) {
1341 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1344 /// SimplifyOrInst - Given operands for an Or, see if we can
1345 /// fold the result. If not, this returns null.
1346 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1347 const TargetLibraryInfo *TLI,
1348 const DominatorTree *DT, unsigned MaxRecurse) {
1349 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1350 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1351 Constant *Ops[] = { CLHS, CRHS };
1352 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1356 // Canonicalize the constant to the RHS.
1357 std::swap(Op0, Op1);
1361 if (match(Op1, m_Undef()))
1362 return Constant::getAllOnesValue(Op0->getType());
1369 if (match(Op1, m_Zero()))
1373 if (match(Op1, m_AllOnes()))
1376 // A | ~A = ~A | A = -1
1377 if (match(Op0, m_Not(m_Specific(Op1))) ||
1378 match(Op1, m_Not(m_Specific(Op0))))
1379 return Constant::getAllOnesValue(Op0->getType());
1382 Value *A = 0, *B = 0;
1383 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1384 (A == Op1 || B == Op1))
1388 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1389 (A == Op0 || B == Op0))
1392 // ~(A & ?) | A = -1
1393 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1394 (A == Op1 || B == Op1))
1395 return Constant::getAllOnesValue(Op1->getType());
1397 // A | ~(A & ?) = -1
1398 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1399 (A == Op0 || B == Op0))
1400 return Constant::getAllOnesValue(Op0->getType());
1402 // Try some generic simplifications for associative operations.
1403 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1407 // Or distributes over And. Try some generic simplifications based on this.
1408 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1409 TLI, DT, MaxRecurse))
1412 // And distributes over Or. Try some generic simplifications based on this.
1413 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1414 TD, TLI, DT, MaxRecurse))
1417 // If the operation is with the result of a select instruction, check whether
1418 // operating on either branch of the select always yields the same value.
1419 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1420 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
1424 // If the operation is with the result of a phi instruction, check whether
1425 // operating on all incoming values of the phi always yields the same value.
1426 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1427 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
1434 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1435 const TargetLibraryInfo *TLI,
1436 const DominatorTree *DT) {
1437 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1440 /// SimplifyXorInst - Given operands for a Xor, see if we can
1441 /// fold the result. If not, this returns null.
1442 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1443 const TargetLibraryInfo *TLI,
1444 const DominatorTree *DT, unsigned MaxRecurse) {
1445 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1446 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1447 Constant *Ops[] = { CLHS, CRHS };
1448 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1452 // Canonicalize the constant to the RHS.
1453 std::swap(Op0, Op1);
1456 // A ^ undef -> undef
1457 if (match(Op1, m_Undef()))
1461 if (match(Op1, m_Zero()))
1466 return Constant::getNullValue(Op0->getType());
1468 // A ^ ~A = ~A ^ A = -1
1469 if (match(Op0, m_Not(m_Specific(Op1))) ||
1470 match(Op1, m_Not(m_Specific(Op0))))
1471 return Constant::getAllOnesValue(Op0->getType());
1473 // Try some generic simplifications for associative operations.
1474 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1478 // And distributes over Xor. Try some generic simplifications based on this.
1479 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1480 TD, TLI, DT, MaxRecurse))
1483 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1484 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1485 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1486 // only if B and C are equal. If B and C are equal then (since we assume
1487 // that operands have already been simplified) "select(cond, B, C)" should
1488 // have been simplified to the common value of B and C already. Analysing
1489 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1490 // for threading over phi nodes.
1495 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1496 const TargetLibraryInfo *TLI,
1497 const DominatorTree *DT) {
1498 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1501 static Type *GetCompareTy(Value *Op) {
1502 return CmpInst::makeCmpResultType(Op->getType());
1505 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1506 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1507 /// otherwise return null. Helper function for analyzing max/min idioms.
1508 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1509 Value *LHS, Value *RHS) {
1510 SelectInst *SI = dyn_cast<SelectInst>(V);
1513 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1516 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1517 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1519 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1520 LHS == CmpRHS && RHS == CmpLHS)
1525 /// stripPointerAdjustments - This is like Value::stripPointerCasts, but also
1526 /// removes inbounds gep operations, regardless of their indices.
1527 static Value *stripPointerAdjustmentsImpl(Value *V,
1528 SmallPtrSet<GEPOperator*, 8> &VisitedGEPs) {
1529 GEPOperator *GEP = dyn_cast<GEPOperator>(V);
1530 if (GEP == 0 || !GEP->isInBounds())
1533 // If we've already seen this GEP, we will end up infinitely looping. This
1534 // can happen in unreachable code.
1535 if (!VisitedGEPs.insert(GEP))
1538 return stripPointerAdjustmentsImpl(GEP->getOperand(0)->stripPointerCasts(),
1542 static Value *stripPointerAdjustments(Value *V) {
1543 SmallPtrSet<GEPOperator*, 8> VisitedGEPs;
1544 return stripPointerAdjustmentsImpl(V, VisitedGEPs);
1548 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1549 /// fold the result. If not, this returns null.
1550 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1551 const TargetData *TD,
1552 const TargetLibraryInfo *TLI,
1553 const DominatorTree *DT,
1554 unsigned MaxRecurse) {
1555 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1556 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1558 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1559 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1560 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
1562 // If we have a constant, make sure it is on the RHS.
1563 std::swap(LHS, RHS);
1564 Pred = CmpInst::getSwappedPredicate(Pred);
1567 Type *ITy = GetCompareTy(LHS); // The return type.
1568 Type *OpTy = LHS->getType(); // The operand type.
1570 // icmp X, X -> true/false
1571 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1572 // because X could be 0.
1573 if (LHS == RHS || isa<UndefValue>(RHS))
1574 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1576 // Special case logic when the operands have i1 type.
1577 if (OpTy->getScalarType()->isIntegerTy(1)) {
1580 case ICmpInst::ICMP_EQ:
1582 if (match(RHS, m_One()))
1585 case ICmpInst::ICMP_NE:
1587 if (match(RHS, m_Zero()))
1590 case ICmpInst::ICMP_UGT:
1592 if (match(RHS, m_Zero()))
1595 case ICmpInst::ICMP_UGE:
1597 if (match(RHS, m_One()))
1600 case ICmpInst::ICMP_SLT:
1602 if (match(RHS, m_Zero()))
1605 case ICmpInst::ICMP_SLE:
1607 if (match(RHS, m_One()))
1613 // icmp <object*>, <object*/null> - Different identified objects have
1614 // different addresses (unless null), and what's more the address of an
1615 // identified local is never equal to another argument (again, barring null).
1616 // Note that generalizing to the case where LHS is a global variable address
1617 // or null is pointless, since if both LHS and RHS are constants then we
1618 // already constant folded the compare, and if only one of them is then we
1619 // moved it to RHS already.
1620 Value *LHSPtr = LHS->stripPointerCasts();
1621 Value *RHSPtr = RHS->stripPointerCasts();
1622 if (LHSPtr == RHSPtr)
1623 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1625 // Be more aggressive about stripping pointer adjustments when checking a
1626 // comparison of an alloca address to another object. We can rip off all
1627 // inbounds GEP operations, even if they are variable.
1628 LHSPtr = stripPointerAdjustments(LHSPtr);
1629 if (llvm::isIdentifiedObject(LHSPtr)) {
1630 RHSPtr = stripPointerAdjustments(RHSPtr);
1631 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1632 // If both sides are different identified objects, they aren't equal
1633 // unless they're null.
1634 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr))
1635 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1637 // A local identified object (alloca or noalias call) can't equal any
1638 // incoming argument, unless they're both null.
1639 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr))
1640 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1643 // Assume that the constant null is on the right.
1644 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr))
1645 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1646 } else if (isa<Argument>(LHSPtr)) {
1647 RHSPtr = stripPointerAdjustments(RHSPtr);
1648 // An alloca can't be equal to an argument.
1649 if (isa<AllocaInst>(RHSPtr))
1650 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1653 // If we are comparing with zero then try hard since this is a common case.
1654 if (match(RHS, m_Zero())) {
1655 bool LHSKnownNonNegative, LHSKnownNegative;
1657 default: llvm_unreachable("Unknown ICmp predicate!");
1658 case ICmpInst::ICMP_ULT:
1659 return getFalse(ITy);
1660 case ICmpInst::ICMP_UGE:
1661 return getTrue(ITy);
1662 case ICmpInst::ICMP_EQ:
1663 case ICmpInst::ICMP_ULE:
1664 if (isKnownNonZero(LHS, TD))
1665 return getFalse(ITy);
1667 case ICmpInst::ICMP_NE:
1668 case ICmpInst::ICMP_UGT:
1669 if (isKnownNonZero(LHS, TD))
1670 return getTrue(ITy);
1672 case ICmpInst::ICMP_SLT:
1673 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1674 if (LHSKnownNegative)
1675 return getTrue(ITy);
1676 if (LHSKnownNonNegative)
1677 return getFalse(ITy);
1679 case ICmpInst::ICMP_SLE:
1680 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1681 if (LHSKnownNegative)
1682 return getTrue(ITy);
1683 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1684 return getFalse(ITy);
1686 case ICmpInst::ICMP_SGE:
1687 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1688 if (LHSKnownNegative)
1689 return getFalse(ITy);
1690 if (LHSKnownNonNegative)
1691 return getTrue(ITy);
1693 case ICmpInst::ICMP_SGT:
1694 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1695 if (LHSKnownNegative)
1696 return getFalse(ITy);
1697 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1698 return getTrue(ITy);
1703 // See if we are doing a comparison with a constant integer.
1704 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1705 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1706 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1707 if (RHS_CR.isEmptySet())
1708 return ConstantInt::getFalse(CI->getContext());
1709 if (RHS_CR.isFullSet())
1710 return ConstantInt::getTrue(CI->getContext());
1712 // Many binary operators with constant RHS have easy to compute constant
1713 // range. Use them to check whether the comparison is a tautology.
1714 uint32_t Width = CI->getBitWidth();
1715 APInt Lower = APInt(Width, 0);
1716 APInt Upper = APInt(Width, 0);
1718 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1719 // 'urem x, CI2' produces [0, CI2).
1720 Upper = CI2->getValue();
1721 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1722 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1723 Upper = CI2->getValue().abs();
1724 Lower = (-Upper) + 1;
1725 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1726 // 'udiv CI2, x' produces [0, CI2].
1727 Upper = CI2->getValue() + 1;
1728 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1729 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1730 APInt NegOne = APInt::getAllOnesValue(Width);
1732 Upper = NegOne.udiv(CI2->getValue()) + 1;
1733 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1734 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1735 APInt IntMin = APInt::getSignedMinValue(Width);
1736 APInt IntMax = APInt::getSignedMaxValue(Width);
1737 APInt Val = CI2->getValue().abs();
1738 if (!Val.isMinValue()) {
1739 Lower = IntMin.sdiv(Val);
1740 Upper = IntMax.sdiv(Val) + 1;
1742 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1743 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1744 APInt NegOne = APInt::getAllOnesValue(Width);
1745 if (CI2->getValue().ult(Width))
1746 Upper = NegOne.lshr(CI2->getValue()) + 1;
1747 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1748 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1749 APInt IntMin = APInt::getSignedMinValue(Width);
1750 APInt IntMax = APInt::getSignedMaxValue(Width);
1751 if (CI2->getValue().ult(Width)) {
1752 Lower = IntMin.ashr(CI2->getValue());
1753 Upper = IntMax.ashr(CI2->getValue()) + 1;
1755 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1756 // 'or x, CI2' produces [CI2, UINT_MAX].
1757 Lower = CI2->getValue();
1758 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1759 // 'and x, CI2' produces [0, CI2].
1760 Upper = CI2->getValue() + 1;
1762 if (Lower != Upper) {
1763 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1764 if (RHS_CR.contains(LHS_CR))
1765 return ConstantInt::getTrue(RHS->getContext());
1766 if (RHS_CR.inverse().contains(LHS_CR))
1767 return ConstantInt::getFalse(RHS->getContext());
1771 // Compare of cast, for example (zext X) != 0 -> X != 0
1772 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1773 Instruction *LI = cast<CastInst>(LHS);
1774 Value *SrcOp = LI->getOperand(0);
1775 Type *SrcTy = SrcOp->getType();
1776 Type *DstTy = LI->getType();
1778 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1779 // if the integer type is the same size as the pointer type.
1780 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1781 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1782 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1783 // Transfer the cast to the constant.
1784 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1785 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1786 TD, TLI, DT, MaxRecurse-1))
1788 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1789 if (RI->getOperand(0)->getType() == SrcTy)
1790 // Compare without the cast.
1791 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1792 TD, TLI, DT, MaxRecurse-1))
1797 if (isa<ZExtInst>(LHS)) {
1798 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1800 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1801 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1802 // Compare X and Y. Note that signed predicates become unsigned.
1803 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1804 SrcOp, RI->getOperand(0), TD, TLI, DT,
1808 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1809 // too. If not, then try to deduce the result of the comparison.
1810 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1811 // Compute the constant that would happen if we truncated to SrcTy then
1812 // reextended to DstTy.
1813 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1814 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1816 // If the re-extended constant didn't change then this is effectively
1817 // also a case of comparing two zero-extended values.
1818 if (RExt == CI && MaxRecurse)
1819 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1820 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
1823 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1824 // there. Use this to work out the result of the comparison.
1827 default: llvm_unreachable("Unknown ICmp predicate!");
1829 case ICmpInst::ICMP_EQ:
1830 case ICmpInst::ICMP_UGT:
1831 case ICmpInst::ICMP_UGE:
1832 return ConstantInt::getFalse(CI->getContext());
1834 case ICmpInst::ICMP_NE:
1835 case ICmpInst::ICMP_ULT:
1836 case ICmpInst::ICMP_ULE:
1837 return ConstantInt::getTrue(CI->getContext());
1839 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1840 // is non-negative then LHS <s RHS.
1841 case ICmpInst::ICMP_SGT:
1842 case ICmpInst::ICMP_SGE:
1843 return CI->getValue().isNegative() ?
1844 ConstantInt::getTrue(CI->getContext()) :
1845 ConstantInt::getFalse(CI->getContext());
1847 case ICmpInst::ICMP_SLT:
1848 case ICmpInst::ICMP_SLE:
1849 return CI->getValue().isNegative() ?
1850 ConstantInt::getFalse(CI->getContext()) :
1851 ConstantInt::getTrue(CI->getContext());
1857 if (isa<SExtInst>(LHS)) {
1858 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1860 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1861 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1862 // Compare X and Y. Note that the predicate does not change.
1863 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1864 TD, TLI, DT, MaxRecurse-1))
1867 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1868 // too. If not, then try to deduce the result of the comparison.
1869 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1870 // Compute the constant that would happen if we truncated to SrcTy then
1871 // reextended to DstTy.
1872 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1873 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1875 // If the re-extended constant didn't change then this is effectively
1876 // also a case of comparing two sign-extended values.
1877 if (RExt == CI && MaxRecurse)
1878 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
1882 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1883 // bits there. Use this to work out the result of the comparison.
1886 default: llvm_unreachable("Unknown ICmp predicate!");
1887 case ICmpInst::ICMP_EQ:
1888 return ConstantInt::getFalse(CI->getContext());
1889 case ICmpInst::ICMP_NE:
1890 return ConstantInt::getTrue(CI->getContext());
1892 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1894 case ICmpInst::ICMP_SGT:
1895 case ICmpInst::ICMP_SGE:
1896 return CI->getValue().isNegative() ?
1897 ConstantInt::getTrue(CI->getContext()) :
1898 ConstantInt::getFalse(CI->getContext());
1899 case ICmpInst::ICMP_SLT:
1900 case ICmpInst::ICMP_SLE:
1901 return CI->getValue().isNegative() ?
1902 ConstantInt::getFalse(CI->getContext()) :
1903 ConstantInt::getTrue(CI->getContext());
1905 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1907 case ICmpInst::ICMP_UGT:
1908 case ICmpInst::ICMP_UGE:
1909 // Comparison is true iff the LHS <s 0.
1911 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1912 Constant::getNullValue(SrcTy),
1913 TD, TLI, DT, MaxRecurse-1))
1916 case ICmpInst::ICMP_ULT:
1917 case ICmpInst::ICMP_ULE:
1918 // Comparison is true iff the LHS >=s 0.
1920 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1921 Constant::getNullValue(SrcTy),
1922 TD, TLI, DT, MaxRecurse-1))
1931 // Special logic for binary operators.
1932 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1933 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1934 if (MaxRecurse && (LBO || RBO)) {
1935 // Analyze the case when either LHS or RHS is an add instruction.
1936 Value *A = 0, *B = 0, *C = 0, *D = 0;
1937 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1938 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1939 if (LBO && LBO->getOpcode() == Instruction::Add) {
1940 A = LBO->getOperand(0); B = LBO->getOperand(1);
1941 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1942 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1943 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1945 if (RBO && RBO->getOpcode() == Instruction::Add) {
1946 C = RBO->getOperand(0); D = RBO->getOperand(1);
1947 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1948 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1949 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1952 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1953 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1954 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1955 Constant::getNullValue(RHS->getType()),
1956 TD, TLI, DT, MaxRecurse-1))
1959 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1960 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1961 if (Value *V = SimplifyICmpInst(Pred,
1962 Constant::getNullValue(LHS->getType()),
1963 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
1966 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1967 if (A && C && (A == C || A == D || B == C || B == D) &&
1968 NoLHSWrapProblem && NoRHSWrapProblem) {
1969 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1970 Value *Y = (A == C || A == D) ? B : A;
1971 Value *Z = (C == A || C == B) ? D : C;
1972 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
1977 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1978 bool KnownNonNegative, KnownNegative;
1982 case ICmpInst::ICMP_SGT:
1983 case ICmpInst::ICMP_SGE:
1984 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1985 if (!KnownNonNegative)
1988 case ICmpInst::ICMP_EQ:
1989 case ICmpInst::ICMP_UGT:
1990 case ICmpInst::ICMP_UGE:
1991 return getFalse(ITy);
1992 case ICmpInst::ICMP_SLT:
1993 case ICmpInst::ICMP_SLE:
1994 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1995 if (!KnownNonNegative)
1998 case ICmpInst::ICMP_NE:
1999 case ICmpInst::ICMP_ULT:
2000 case ICmpInst::ICMP_ULE:
2001 return getTrue(ITy);
2004 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2005 bool KnownNonNegative, KnownNegative;
2009 case ICmpInst::ICMP_SGT:
2010 case ICmpInst::ICMP_SGE:
2011 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2012 if (!KnownNonNegative)
2015 case ICmpInst::ICMP_NE:
2016 case ICmpInst::ICMP_UGT:
2017 case ICmpInst::ICMP_UGE:
2018 return getTrue(ITy);
2019 case ICmpInst::ICMP_SLT:
2020 case ICmpInst::ICMP_SLE:
2021 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2022 if (!KnownNonNegative)
2025 case ICmpInst::ICMP_EQ:
2026 case ICmpInst::ICMP_ULT:
2027 case ICmpInst::ICMP_ULE:
2028 return getFalse(ITy);
2033 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2034 // icmp pred (X /u Y), X
2035 if (Pred == ICmpInst::ICMP_UGT)
2036 return getFalse(ITy);
2037 if (Pred == ICmpInst::ICMP_ULE)
2038 return getTrue(ITy);
2041 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2042 LBO->getOperand(1) == RBO->getOperand(1)) {
2043 switch (LBO->getOpcode()) {
2045 case Instruction::UDiv:
2046 case Instruction::LShr:
2047 if (ICmpInst::isSigned(Pred))
2050 case Instruction::SDiv:
2051 case Instruction::AShr:
2052 if (!LBO->isExact() || !RBO->isExact())
2054 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2055 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2058 case Instruction::Shl: {
2059 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2060 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2063 if (!NSW && ICmpInst::isSigned(Pred))
2065 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2066 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2073 // Simplify comparisons involving max/min.
2075 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2076 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2078 // Signed variants on "max(a,b)>=a -> true".
2079 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2080 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2081 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2082 // We analyze this as smax(A, B) pred A.
2084 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2085 (A == LHS || B == LHS)) {
2086 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2087 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2088 // We analyze this as smax(A, B) swapped-pred A.
2089 P = CmpInst::getSwappedPredicate(Pred);
2090 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2091 (A == RHS || B == RHS)) {
2092 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2093 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2094 // We analyze this as smax(-A, -B) swapped-pred -A.
2095 // Note that we do not need to actually form -A or -B thanks to EqP.
2096 P = CmpInst::getSwappedPredicate(Pred);
2097 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2098 (A == LHS || B == LHS)) {
2099 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2100 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2101 // We analyze this as smax(-A, -B) pred -A.
2102 // Note that we do not need to actually form -A or -B thanks to EqP.
2105 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2106 // Cases correspond to "max(A, B) p A".
2110 case CmpInst::ICMP_EQ:
2111 case CmpInst::ICMP_SLE:
2112 // Equivalent to "A EqP B". This may be the same as the condition tested
2113 // in the max/min; if so, we can just return that.
2114 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2116 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2118 // Otherwise, see if "A EqP B" simplifies.
2120 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2123 case CmpInst::ICMP_NE:
2124 case CmpInst::ICMP_SGT: {
2125 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2126 // Equivalent to "A InvEqP B". This may be the same as the condition
2127 // tested in the max/min; if so, we can just return that.
2128 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2130 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2132 // Otherwise, see if "A InvEqP B" simplifies.
2134 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2138 case CmpInst::ICMP_SGE:
2140 return getTrue(ITy);
2141 case CmpInst::ICMP_SLT:
2143 return getFalse(ITy);
2147 // Unsigned variants on "max(a,b)>=a -> true".
2148 P = CmpInst::BAD_ICMP_PREDICATE;
2149 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2150 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2151 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2152 // We analyze this as umax(A, B) pred A.
2154 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2155 (A == LHS || B == LHS)) {
2156 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2157 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2158 // We analyze this as umax(A, B) swapped-pred A.
2159 P = CmpInst::getSwappedPredicate(Pred);
2160 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2161 (A == RHS || B == RHS)) {
2162 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2163 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2164 // We analyze this as umax(-A, -B) swapped-pred -A.
2165 // Note that we do not need to actually form -A or -B thanks to EqP.
2166 P = CmpInst::getSwappedPredicate(Pred);
2167 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2168 (A == LHS || B == LHS)) {
2169 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2170 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2171 // We analyze this as umax(-A, -B) pred -A.
2172 // Note that we do not need to actually form -A or -B thanks to EqP.
2175 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2176 // Cases correspond to "max(A, B) p A".
2180 case CmpInst::ICMP_EQ:
2181 case CmpInst::ICMP_ULE:
2182 // Equivalent to "A EqP B". This may be the same as the condition tested
2183 // in the max/min; if so, we can just return that.
2184 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2186 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2188 // Otherwise, see if "A EqP B" simplifies.
2190 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2193 case CmpInst::ICMP_NE:
2194 case CmpInst::ICMP_UGT: {
2195 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2196 // Equivalent to "A InvEqP B". This may be the same as the condition
2197 // tested in the max/min; if so, we can just return that.
2198 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2200 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2202 // Otherwise, see if "A InvEqP B" simplifies.
2204 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2208 case CmpInst::ICMP_UGE:
2210 return getTrue(ITy);
2211 case CmpInst::ICMP_ULT:
2213 return getFalse(ITy);
2217 // Variants on "max(x,y) >= min(x,z)".
2219 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2220 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2221 (A == C || A == D || B == C || B == D)) {
2222 // max(x, ?) pred min(x, ?).
2223 if (Pred == CmpInst::ICMP_SGE)
2225 return getTrue(ITy);
2226 if (Pred == CmpInst::ICMP_SLT)
2228 return getFalse(ITy);
2229 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2230 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2231 (A == C || A == D || B == C || B == D)) {
2232 // min(x, ?) pred max(x, ?).
2233 if (Pred == CmpInst::ICMP_SLE)
2235 return getTrue(ITy);
2236 if (Pred == CmpInst::ICMP_SGT)
2238 return getFalse(ITy);
2239 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2240 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2241 (A == C || A == D || B == C || B == D)) {
2242 // max(x, ?) pred min(x, ?).
2243 if (Pred == CmpInst::ICMP_UGE)
2245 return getTrue(ITy);
2246 if (Pred == CmpInst::ICMP_ULT)
2248 return getFalse(ITy);
2249 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2250 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2251 (A == C || A == D || B == C || B == D)) {
2252 // min(x, ?) pred max(x, ?).
2253 if (Pred == CmpInst::ICMP_ULE)
2255 return getTrue(ITy);
2256 if (Pred == CmpInst::ICMP_UGT)
2258 return getFalse(ITy);
2261 // Simplify comparisons of GEPs.
2262 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2263 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2264 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2265 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2266 (ICmpInst::isEquality(Pred) ||
2267 (GLHS->isInBounds() && GRHS->isInBounds() &&
2268 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2269 // The bases are equal and the indices are constant. Build a constant
2270 // expression GEP with the same indices and a null base pointer to see
2271 // what constant folding can make out of it.
2272 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2273 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2274 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2276 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2277 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2278 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2283 // If the comparison is with the result of a select instruction, check whether
2284 // comparing with either branch of the select always yields the same value.
2285 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2286 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2289 // If the comparison is with the result of a phi instruction, check whether
2290 // doing the compare with each incoming phi value yields a common result.
2291 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2292 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2298 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2299 const TargetData *TD,
2300 const TargetLibraryInfo *TLI,
2301 const DominatorTree *DT) {
2302 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2305 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2306 /// fold the result. If not, this returns null.
2307 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2308 const TargetData *TD,
2309 const TargetLibraryInfo *TLI,
2310 const DominatorTree *DT,
2311 unsigned MaxRecurse) {
2312 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2313 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2315 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2316 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2317 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
2319 // If we have a constant, make sure it is on the RHS.
2320 std::swap(LHS, RHS);
2321 Pred = CmpInst::getSwappedPredicate(Pred);
2324 // Fold trivial predicates.
2325 if (Pred == FCmpInst::FCMP_FALSE)
2326 return ConstantInt::get(GetCompareTy(LHS), 0);
2327 if (Pred == FCmpInst::FCMP_TRUE)
2328 return ConstantInt::get(GetCompareTy(LHS), 1);
2330 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2331 return UndefValue::get(GetCompareTy(LHS));
2333 // fcmp x,x -> true/false. Not all compares are foldable.
2335 if (CmpInst::isTrueWhenEqual(Pred))
2336 return ConstantInt::get(GetCompareTy(LHS), 1);
2337 if (CmpInst::isFalseWhenEqual(Pred))
2338 return ConstantInt::get(GetCompareTy(LHS), 0);
2341 // Handle fcmp with constant RHS
2342 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2343 // If the constant is a nan, see if we can fold the comparison based on it.
2344 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2345 if (CFP->getValueAPF().isNaN()) {
2346 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2347 return ConstantInt::getFalse(CFP->getContext());
2348 assert(FCmpInst::isUnordered(Pred) &&
2349 "Comparison must be either ordered or unordered!");
2350 // True if unordered.
2351 return ConstantInt::getTrue(CFP->getContext());
2353 // Check whether the constant is an infinity.
2354 if (CFP->getValueAPF().isInfinity()) {
2355 if (CFP->getValueAPF().isNegative()) {
2357 case FCmpInst::FCMP_OLT:
2358 // No value is ordered and less than negative infinity.
2359 return ConstantInt::getFalse(CFP->getContext());
2360 case FCmpInst::FCMP_UGE:
2361 // All values are unordered with or at least negative infinity.
2362 return ConstantInt::getTrue(CFP->getContext());
2368 case FCmpInst::FCMP_OGT:
2369 // No value is ordered and greater than infinity.
2370 return ConstantInt::getFalse(CFP->getContext());
2371 case FCmpInst::FCMP_ULE:
2372 // All values are unordered with and at most infinity.
2373 return ConstantInt::getTrue(CFP->getContext());
2382 // If the comparison is with the result of a select instruction, check whether
2383 // comparing with either branch of the select always yields the same value.
2384 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2385 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2388 // If the comparison is with the result of a phi instruction, check whether
2389 // doing the compare with each incoming phi value yields a common result.
2390 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2391 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2397 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2398 const TargetData *TD,
2399 const TargetLibraryInfo *TLI,
2400 const DominatorTree *DT) {
2401 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2404 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2405 /// the result. If not, this returns null.
2406 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2407 const TargetData *TD, const DominatorTree *) {
2408 // select true, X, Y -> X
2409 // select false, X, Y -> Y
2410 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2411 return CB->getZExtValue() ? TrueVal : FalseVal;
2413 // select C, X, X -> X
2414 if (TrueVal == FalseVal)
2417 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2418 if (isa<Constant>(TrueVal))
2422 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2424 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2430 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2431 /// fold the result. If not, this returns null.
2432 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2433 const DominatorTree *) {
2434 // The type of the GEP pointer operand.
2435 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2436 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2440 // getelementptr P -> P.
2441 if (Ops.size() == 1)
2444 if (isa<UndefValue>(Ops[0])) {
2445 // Compute the (pointer) type returned by the GEP instruction.
2446 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2447 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2448 return UndefValue::get(GEPTy);
2451 if (Ops.size() == 2) {
2452 // getelementptr P, 0 -> P.
2453 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2456 // getelementptr P, N -> P if P points to a type of zero size.
2458 Type *Ty = PtrTy->getElementType();
2459 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2464 // Check to see if this is constant foldable.
2465 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2466 if (!isa<Constant>(Ops[i]))
2469 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2472 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2473 /// can fold the result. If not, this returns null.
2474 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2475 ArrayRef<unsigned> Idxs,
2477 const DominatorTree *) {
2478 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2479 if (Constant *CVal = dyn_cast<Constant>(Val))
2480 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2482 // insertvalue x, undef, n -> x
2483 if (match(Val, m_Undef()))
2486 // insertvalue x, (extractvalue y, n), n
2487 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2488 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2489 EV->getIndices() == Idxs) {
2490 // insertvalue undef, (extractvalue y, n), n -> y
2491 if (match(Agg, m_Undef()))
2492 return EV->getAggregateOperand();
2494 // insertvalue y, (extractvalue y, n), n -> y
2495 if (Agg == EV->getAggregateOperand())
2502 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2503 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2504 // If all of the PHI's incoming values are the same then replace the PHI node
2505 // with the common value.
2506 Value *CommonValue = 0;
2507 bool HasUndefInput = false;
2508 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2509 Value *Incoming = PN->getIncomingValue(i);
2510 // If the incoming value is the phi node itself, it can safely be skipped.
2511 if (Incoming == PN) continue;
2512 if (isa<UndefValue>(Incoming)) {
2513 // Remember that we saw an undef value, but otherwise ignore them.
2514 HasUndefInput = true;
2517 if (CommonValue && Incoming != CommonValue)
2518 return 0; // Not the same, bail out.
2519 CommonValue = Incoming;
2522 // If CommonValue is null then all of the incoming values were either undef or
2523 // equal to the phi node itself.
2525 return UndefValue::get(PN->getType());
2527 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2528 // instruction, we cannot return X as the result of the PHI node unless it
2529 // dominates the PHI block.
2531 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2536 //=== Helper functions for higher up the class hierarchy.
2538 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2539 /// fold the result. If not, this returns null.
2540 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2541 const TargetData *TD,
2542 const TargetLibraryInfo *TLI,
2543 const DominatorTree *DT,
2544 unsigned MaxRecurse) {
2546 case Instruction::Add:
2547 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2548 TD, TLI, DT, MaxRecurse);
2549 case Instruction::Sub:
2550 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2551 TD, TLI, DT, MaxRecurse);
2552 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2554 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2556 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2558 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2560 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2562 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2564 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2566 case Instruction::Shl:
2567 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2568 TD, TLI, DT, MaxRecurse);
2569 case Instruction::LShr:
2570 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2572 case Instruction::AShr:
2573 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2575 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2577 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2579 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2582 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2583 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2584 Constant *COps[] = {CLHS, CRHS};
2585 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
2588 // If the operation is associative, try some generic simplifications.
2589 if (Instruction::isAssociative(Opcode))
2590 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
2594 // If the operation is with the result of a select instruction, check whether
2595 // operating on either branch of the select always yields the same value.
2596 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2597 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
2601 // If the operation is with the result of a phi instruction, check whether
2602 // operating on all incoming values of the phi always yields the same value.
2603 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2604 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2612 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2613 const TargetData *TD, const TargetLibraryInfo *TLI,
2614 const DominatorTree *DT) {
2615 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
2618 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2619 /// fold the result.
2620 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2621 const TargetData *TD,
2622 const TargetLibraryInfo *TLI,
2623 const DominatorTree *DT,
2624 unsigned MaxRecurse) {
2625 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2626 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2627 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2630 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2631 const TargetData *TD, const TargetLibraryInfo *TLI,
2632 const DominatorTree *DT) {
2633 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2636 static Value *SimplifyCallInst(CallInst *CI) {
2637 // call undef -> undef
2638 if (isa<UndefValue>(CI->getCalledValue()))
2639 return UndefValue::get(CI->getType());
2644 /// SimplifyInstruction - See if we can compute a simplified version of this
2645 /// instruction. If not, this returns null.
2646 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2647 const TargetLibraryInfo *TLI,
2648 const DominatorTree *DT) {
2651 switch (I->getOpcode()) {
2653 Result = ConstantFoldInstruction(I, TD, TLI);
2655 case Instruction::Add:
2656 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2657 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2658 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2661 case Instruction::Sub:
2662 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2663 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2664 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2667 case Instruction::Mul:
2668 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2670 case Instruction::SDiv:
2671 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2673 case Instruction::UDiv:
2674 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2676 case Instruction::FDiv:
2677 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2679 case Instruction::SRem:
2680 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2682 case Instruction::URem:
2683 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2685 case Instruction::FRem:
2686 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2688 case Instruction::Shl:
2689 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2690 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2691 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2694 case Instruction::LShr:
2695 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2696 cast<BinaryOperator>(I)->isExact(),
2699 case Instruction::AShr:
2700 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2701 cast<BinaryOperator>(I)->isExact(),
2704 case Instruction::And:
2705 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2707 case Instruction::Or:
2708 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2710 case Instruction::Xor:
2711 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2713 case Instruction::ICmp:
2714 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2715 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2717 case Instruction::FCmp:
2718 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2719 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2721 case Instruction::Select:
2722 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2723 I->getOperand(2), TD, DT);
2725 case Instruction::GetElementPtr: {
2726 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2727 Result = SimplifyGEPInst(Ops, TD, DT);
2730 case Instruction::InsertValue: {
2731 InsertValueInst *IV = cast<InsertValueInst>(I);
2732 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2733 IV->getInsertedValueOperand(),
2734 IV->getIndices(), TD, DT);
2737 case Instruction::PHI:
2738 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2740 case Instruction::Call:
2741 Result = SimplifyCallInst(cast<CallInst>(I));
2745 /// If called on unreachable code, the above logic may report that the
2746 /// instruction simplified to itself. Make life easier for users by
2747 /// detecting that case here, returning a safe value instead.
2748 return Result == I ? UndefValue::get(I->getType()) : Result;
2751 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2752 /// delete the From instruction. In addition to a basic RAUW, this does a
2753 /// recursive simplification of the newly formed instructions. This catches
2754 /// things where one simplification exposes other opportunities. This only
2755 /// simplifies and deletes scalar operations, it does not change the CFG.
2757 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2758 const TargetData *TD,
2759 const TargetLibraryInfo *TLI,
2760 const DominatorTree *DT) {
2761 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2763 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2764 // we can know if it gets deleted out from under us or replaced in a
2765 // recursive simplification.
2766 WeakVH FromHandle(From);
2767 WeakVH ToHandle(To);
2769 while (!From->use_empty()) {
2770 // Update the instruction to use the new value.
2771 Use &TheUse = From->use_begin().getUse();
2772 Instruction *User = cast<Instruction>(TheUse.getUser());
2775 // Check to see if the instruction can be folded due to the operand
2776 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2777 // the 'or' with -1.
2778 Value *SimplifiedVal;
2780 // Sanity check to make sure 'User' doesn't dangle across
2781 // SimplifyInstruction.
2782 AssertingVH<> UserHandle(User);
2784 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
2785 if (SimplifiedVal == 0) continue;
2788 // Recursively simplify this user to the new value.
2789 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
2790 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2793 assert(ToHandle && "To value deleted by recursive simplification?");
2795 // If the recursive simplification ended up revisiting and deleting
2796 // 'From' then we're done.
2801 // If 'From' has value handles referring to it, do a real RAUW to update them.
2802 From->replaceAllUsesWith(To);
2804 From->eraseFromParent();