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/GlobalAlias.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Support/ConstantRange.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/PatternMatch.h"
32 #include "llvm/Support/ValueHandle.h"
33 #include "llvm/Target/TargetData.h"
35 using namespace llvm::PatternMatch;
37 enum { RecursionLimit = 3 };
39 STATISTIC(NumExpand, "Number of expansions");
40 STATISTIC(NumFactor , "Number of factorizations");
41 STATISTIC(NumReassoc, "Number of reassociations");
43 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
44 const TargetLibraryInfo *, const DominatorTree *,
46 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
47 const TargetLibraryInfo *, const DominatorTree *,
49 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
50 const TargetLibraryInfo *, const DominatorTree *,
52 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
53 const TargetLibraryInfo *, const DominatorTree *,
55 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
56 const TargetLibraryInfo *, const DominatorTree *,
59 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
60 /// a vector with every element false, as appropriate for the type.
61 static Constant *getFalse(Type *Ty) {
62 assert(Ty->getScalarType()->isIntegerTy(1) &&
63 "Expected i1 type or a vector of i1!");
64 return Constant::getNullValue(Ty);
67 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
68 /// a vector with every element true, as appropriate for the type.
69 static Constant *getTrue(Type *Ty) {
70 assert(Ty->getScalarType()->isIntegerTy(1) &&
71 "Expected i1 type or a vector of i1!");
72 return Constant::getAllOnesValue(Ty);
75 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
76 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
78 CmpInst *Cmp = dyn_cast<CmpInst>(V);
81 CmpInst::Predicate CPred = Cmp->getPredicate();
82 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
83 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
85 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
90 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
91 Instruction *I = dyn_cast<Instruction>(V);
93 // Arguments and constants dominate all instructions.
96 // If we have a DominatorTree then do a precise test.
98 if (!DT->isReachableFromEntry(P->getParent()))
100 if (!DT->isReachableFromEntry(I->getParent()))
102 return DT->dominates(I, P);
105 // Otherwise, if the instruction is in the entry block, and is not an invoke,
106 // then it obviously dominates all phi nodes.
107 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
114 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
115 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
116 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
117 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
118 /// Returns the simplified value, or null if no simplification was performed.
119 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
120 unsigned OpcToExpand, const TargetData *TD,
121 const TargetLibraryInfo *TLI, const DominatorTree *DT,
122 unsigned MaxRecurse) {
123 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
124 // Recursion is always used, so bail out at once if we already hit the limit.
128 // Check whether the expression has the form "(A op' B) op C".
129 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
130 if (Op0->getOpcode() == OpcodeToExpand) {
131 // It does! Try turning it into "(A op C) op' (B op C)".
132 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
133 // Do "A op C" and "B op C" both simplify?
134 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
135 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
136 // They do! Return "L op' R" if it simplifies or is already available.
137 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
138 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
139 && L == B && R == A)) {
143 // Otherwise return "L op' R" if it simplifies.
144 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
152 // Check whether the expression has the form "A op (B op' C)".
153 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
154 if (Op1->getOpcode() == OpcodeToExpand) {
155 // It does! Try turning it into "(A op B) op' (A op C)".
156 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
157 // Do "A op B" and "A op C" both simplify?
158 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
159 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
160 // They do! Return "L op' R" if it simplifies or is already available.
161 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
162 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
163 && L == C && R == B)) {
167 // Otherwise return "L op' R" if it simplifies.
168 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
179 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
180 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
181 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
182 /// Returns the simplified value, or null if no simplification was performed.
183 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
184 unsigned OpcToExtract, const TargetData *TD,
185 const TargetLibraryInfo *TLI,
186 const DominatorTree *DT,
187 unsigned MaxRecurse) {
188 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
189 // Recursion is always used, so bail out at once if we already hit the limit.
193 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
194 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
196 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
197 !Op1 || Op1->getOpcode() != OpcodeToExtract)
200 // The expression has the form "(A op' B) op (C op' D)".
201 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
202 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
204 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
205 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
206 // commutative case, "(A op' B) op (C op' A)"?
207 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
208 Value *DD = A == C ? D : C;
209 // Form "A op' (B op DD)" if it simplifies completely.
210 // Does "B op DD" simplify?
211 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
212 // It does! Return "A op' V" if it simplifies or is already available.
213 // If V equals B then "A op' V" is just the LHS. If V equals DD then
214 // "A op' V" is just the RHS.
215 if (V == B || V == DD) {
217 return V == B ? LHS : RHS;
219 // Otherwise return "A op' V" if it simplifies.
220 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
228 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
229 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
230 // commutative case, "(A op' B) op (B op' D)"?
231 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
232 Value *CC = B == D ? C : D;
233 // Form "(A op CC) op' B" if it simplifies completely..
234 // Does "A op CC" simplify?
235 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
236 // It does! Return "V op' B" if it simplifies or is already available.
237 // If V equals A then "V op' B" is just the LHS. If V equals CC then
238 // "V op' B" is just the RHS.
239 if (V == A || V == CC) {
241 return V == A ? LHS : RHS;
243 // Otherwise return "V op' B" if it simplifies.
244 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
255 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
256 /// operations. Returns the simpler value, or null if none was found.
257 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
258 const TargetData *TD,
259 const TargetLibraryInfo *TLI,
260 const DominatorTree *DT,
261 unsigned MaxRecurse) {
262 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
263 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
265 // Recursion is always used, so bail out at once if we already hit the limit.
269 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
270 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
272 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
273 if (Op0 && Op0->getOpcode() == Opcode) {
274 Value *A = Op0->getOperand(0);
275 Value *B = Op0->getOperand(1);
278 // Does "B op C" simplify?
279 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
280 // It does! Return "A op V" if it simplifies or is already available.
281 // If V equals B then "A op V" is just the LHS.
282 if (V == B) return LHS;
283 // Otherwise return "A op V" if it simplifies.
284 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
291 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
292 if (Op1 && Op1->getOpcode() == Opcode) {
294 Value *B = Op1->getOperand(0);
295 Value *C = Op1->getOperand(1);
297 // Does "A op B" simplify?
298 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
299 // It does! Return "V op C" if it simplifies or is already available.
300 // If V equals B then "V op C" is just the RHS.
301 if (V == B) return RHS;
302 // Otherwise return "V op C" if it simplifies.
303 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
310 // The remaining transforms require commutativity as well as associativity.
311 if (!Instruction::isCommutative(Opcode))
314 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
315 if (Op0 && Op0->getOpcode() == Opcode) {
316 Value *A = Op0->getOperand(0);
317 Value *B = Op0->getOperand(1);
320 // Does "C op A" simplify?
321 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
322 // It does! Return "V op B" if it simplifies or is already available.
323 // If V equals A then "V op B" is just the LHS.
324 if (V == A) return LHS;
325 // Otherwise return "V op B" if it simplifies.
326 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
333 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
334 if (Op1 && Op1->getOpcode() == Opcode) {
336 Value *B = Op1->getOperand(0);
337 Value *C = Op1->getOperand(1);
339 // Does "C op A" simplify?
340 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
341 // It does! Return "B op V" if it simplifies or is already available.
342 // If V equals C then "B op V" is just the RHS.
343 if (V == C) return RHS;
344 // Otherwise return "B op V" if it simplifies.
345 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
355 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
356 /// instruction as an operand, try to simplify the binop by seeing whether
357 /// evaluating it on both branches of the select results in the same value.
358 /// Returns the common value if so, otherwise returns null.
359 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
360 const TargetData *TD,
361 const TargetLibraryInfo *TLI,
362 const DominatorTree *DT,
363 unsigned MaxRecurse) {
364 // Recursion is always used, so bail out at once if we already hit the limit.
369 if (isa<SelectInst>(LHS)) {
370 SI = cast<SelectInst>(LHS);
372 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
373 SI = cast<SelectInst>(RHS);
376 // Evaluate the BinOp on the true and false branches of the select.
380 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
381 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
383 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
384 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
387 // If they simplified to the same value, then return the common value.
388 // If they both failed to simplify then return null.
392 // If one branch simplified to undef, return the other one.
393 if (TV && isa<UndefValue>(TV))
395 if (FV && isa<UndefValue>(FV))
398 // If applying the operation did not change the true and false select values,
399 // then the result of the binop is the select itself.
400 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
403 // If one branch simplified and the other did not, and the simplified
404 // value is equal to the unsimplified one, return the simplified value.
405 // For example, select (cond, X, X & Z) & Z -> X & Z.
406 if ((FV && !TV) || (TV && !FV)) {
407 // Check that the simplified value has the form "X op Y" where "op" is the
408 // same as the original operation.
409 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
410 if (Simplified && Simplified->getOpcode() == Opcode) {
411 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
412 // We already know that "op" is the same as for the simplified value. See
413 // if the operands match too. If so, return the simplified value.
414 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
415 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
416 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
417 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
418 Simplified->getOperand(1) == UnsimplifiedRHS)
420 if (Simplified->isCommutative() &&
421 Simplified->getOperand(1) == UnsimplifiedLHS &&
422 Simplified->getOperand(0) == UnsimplifiedRHS)
430 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
431 /// try to simplify the comparison by seeing whether both branches of the select
432 /// result in the same value. Returns the common value if so, otherwise returns
434 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
435 Value *RHS, const TargetData *TD,
436 const TargetLibraryInfo *TLI,
437 const DominatorTree *DT,
438 unsigned MaxRecurse) {
439 // Recursion is always used, so bail out at once if we already hit the limit.
443 // Make sure the select is on the LHS.
444 if (!isa<SelectInst>(LHS)) {
446 Pred = CmpInst::getSwappedPredicate(Pred);
448 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
449 SelectInst *SI = cast<SelectInst>(LHS);
450 Value *Cond = SI->getCondition();
451 Value *TV = SI->getTrueValue();
452 Value *FV = SI->getFalseValue();
454 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
455 // Does "cmp TV, RHS" simplify?
456 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
458 // It not only simplified, it simplified to the select condition. Replace
460 TCmp = getTrue(Cond->getType());
462 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
463 // condition then we can replace it with 'true'. Otherwise give up.
464 if (!isSameCompare(Cond, Pred, TV, RHS))
466 TCmp = getTrue(Cond->getType());
469 // Does "cmp FV, RHS" simplify?
470 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
472 // It not only simplified, it simplified to the select condition. Replace
474 FCmp = getFalse(Cond->getType());
476 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
477 // condition then we can replace it with 'false'. Otherwise give up.
478 if (!isSameCompare(Cond, Pred, FV, RHS))
480 FCmp = getFalse(Cond->getType());
483 // If both sides simplified to the same value, then use it as the result of
484 // the original comparison.
488 // The remaining cases only make sense if the select condition has the same
489 // type as the result of the comparison, so bail out if this is not so.
490 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
492 // If the false value simplified to false, then the result of the compare
493 // is equal to "Cond && TCmp". This also catches the case when the false
494 // value simplified to false and the true value to true, returning "Cond".
495 if (match(FCmp, m_Zero()))
496 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
498 // If the true value simplified to true, then the result of the compare
499 // is equal to "Cond || FCmp".
500 if (match(TCmp, m_One()))
501 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
503 // Finally, if the false value simplified to true and the true value to
504 // false, then the result of the compare is equal to "!Cond".
505 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
507 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
508 TD, TLI, DT, MaxRecurse))
514 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
515 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
516 /// it on the incoming phi values yields the same result for every value. If so
517 /// returns the common value, otherwise returns null.
518 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
519 const TargetData *TD,
520 const TargetLibraryInfo *TLI,
521 const DominatorTree *DT,
522 unsigned MaxRecurse) {
523 // Recursion is always used, so bail out at once if we already hit the limit.
528 if (isa<PHINode>(LHS)) {
529 PI = cast<PHINode>(LHS);
530 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
531 if (!ValueDominatesPHI(RHS, PI, DT))
534 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
535 PI = cast<PHINode>(RHS);
536 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
537 if (!ValueDominatesPHI(LHS, PI, DT))
541 // Evaluate the BinOp on the incoming phi values.
542 Value *CommonValue = 0;
543 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
544 Value *Incoming = PI->getIncomingValue(i);
545 // If the incoming value is the phi node itself, it can safely be skipped.
546 if (Incoming == PI) continue;
547 Value *V = PI == LHS ?
548 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
549 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
550 // If the operation failed to simplify, or simplified to a different value
551 // to previously, then give up.
552 if (!V || (CommonValue && V != CommonValue))
560 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
561 /// try to simplify the comparison by seeing whether comparing with all of the
562 /// incoming phi values yields the same result every time. If so returns the
563 /// common result, otherwise returns null.
564 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
565 const TargetData *TD,
566 const TargetLibraryInfo *TLI,
567 const DominatorTree *DT,
568 unsigned MaxRecurse) {
569 // Recursion is always used, so bail out at once if we already hit the limit.
573 // Make sure the phi is on the LHS.
574 if (!isa<PHINode>(LHS)) {
576 Pred = CmpInst::getSwappedPredicate(Pred);
578 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
579 PHINode *PI = cast<PHINode>(LHS);
581 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
582 if (!ValueDominatesPHI(RHS, PI, DT))
585 // Evaluate the BinOp on the incoming phi values.
586 Value *CommonValue = 0;
587 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
588 Value *Incoming = PI->getIncomingValue(i);
589 // If the incoming value is the phi node itself, it can safely be skipped.
590 if (Incoming == PI) continue;
591 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
592 // If the operation failed to simplify, or simplified to a different value
593 // to previously, then give up.
594 if (!V || (CommonValue && V != CommonValue))
602 /// SimplifyAddInst - Given operands for an Add, see if we can
603 /// fold the result. If not, this returns null.
604 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
605 const TargetData *TD,
606 const TargetLibraryInfo *TLI,
607 const DominatorTree *DT,
608 unsigned MaxRecurse) {
609 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
610 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
611 Constant *Ops[] = { CLHS, CRHS };
612 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
616 // Canonicalize the constant to the RHS.
620 // X + undef -> undef
621 if (match(Op1, m_Undef()))
625 if (match(Op1, m_Zero()))
632 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
633 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
636 // X + ~X -> -1 since ~X = -X-1
637 if (match(Op0, m_Not(m_Specific(Op1))) ||
638 match(Op1, m_Not(m_Specific(Op0))))
639 return Constant::getAllOnesValue(Op0->getType());
642 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
643 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
646 // Try some generic simplifications for associative operations.
647 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
651 // Mul distributes over Add. Try some generic simplifications based on this.
652 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
653 TD, TLI, DT, MaxRecurse))
656 // Threading Add over selects and phi nodes is pointless, so don't bother.
657 // Threading over the select in "A + select(cond, B, C)" means evaluating
658 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
659 // only if B and C are equal. If B and C are equal then (since we assume
660 // that operands have already been simplified) "select(cond, B, C)" should
661 // have been simplified to the common value of B and C already. Analysing
662 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
663 // for threading over phi nodes.
668 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
669 const TargetData *TD, const TargetLibraryInfo *TLI,
670 const DominatorTree *DT) {
671 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
674 /// \brief Accumulate the constant integer offset a GEP represents.
676 /// Given a getelementptr instruction/constantexpr, accumulate the constant
677 /// offset from the base pointer into the provided APInt 'Offset'. Returns true
678 /// if the GEP has all-constant indices. Returns false if any non-constant
679 /// index is encountered leaving the 'Offset' in an undefined state. The
680 /// 'Offset' APInt must be the bitwidth of the target's pointer size.
681 static bool accumulateGEPOffset(const TargetData &TD, GEPOperator *GEP,
683 unsigned IntPtrWidth = TD.getPointerSizeInBits();
684 assert(IntPtrWidth == Offset.getBitWidth());
686 gep_type_iterator GTI = gep_type_begin(GEP);
687 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
689 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
690 if (!OpC) return false;
691 if (OpC->isZero()) continue;
693 // Handle a struct index, which adds its field offset to the pointer.
694 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
695 unsigned ElementIdx = OpC->getZExtValue();
696 const StructLayout *SL = TD.getStructLayout(STy);
697 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx),
702 APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()),
704 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
709 /// \brief Compute the base pointer and cumulative constant offsets for V.
711 /// This strips all constant offsets off of V, leaving it the base pointer, and
712 /// accumulates the total constant offset applied in the returned constant. It
713 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
714 /// no constant offsets applied.
715 static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
717 if (!V->getType()->isPointerTy())
720 unsigned IntPtrWidth = TD.getPointerSizeInBits();
721 APInt Offset = APInt::getNullValue(IntPtrWidth);
723 // Even though we don't look through PHI nodes, we could be called on an
724 // instruction in an unreachable block, which may be on a cycle.
725 SmallPtrSet<Value *, 4> Visited;
728 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
729 if (!accumulateGEPOffset(TD, GEP, Offset))
731 V = GEP->getPointerOperand();
732 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
733 V = cast<Operator>(V)->getOperand(0);
734 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
735 if (GA->mayBeOverridden())
737 V = GA->getAliasee();
741 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
742 } while (Visited.insert(V));
744 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
745 return ConstantInt::get(IntPtrTy, Offset);
748 /// \brief Compute the constant difference between two pointer values.
749 /// If the difference is not a constant, returns zero.
750 static Constant *computePointerDifference(const TargetData &TD,
751 Value *LHS, Value *RHS) {
752 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
755 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
759 // If LHS and RHS are not related via constant offsets to the same base
760 // value, there is nothing we can do here.
764 // Otherwise, the difference of LHS - RHS can be computed as:
766 // = (LHSOffset + Base) - (RHSOffset + Base)
767 // = LHSOffset - RHSOffset
768 return ConstantExpr::getSub(LHSOffset, RHSOffset);
771 /// SimplifySubInst - Given operands for a Sub, see if we can
772 /// fold the result. If not, this returns null.
773 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
774 const TargetData *TD,
775 const TargetLibraryInfo *TLI,
776 const DominatorTree *DT,
777 unsigned MaxRecurse) {
778 if (Constant *CLHS = dyn_cast<Constant>(Op0))
779 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
780 Constant *Ops[] = { CLHS, CRHS };
781 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
785 // X - undef -> undef
786 // undef - X -> undef
787 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
788 return UndefValue::get(Op0->getType());
791 if (match(Op1, m_Zero()))
796 return Constant::getNullValue(Op0->getType());
801 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
802 match(Op0, m_Shl(m_Specific(Op1), m_One())))
806 Value *LHSOp, *RHSOp;
807 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
808 match(Op1, m_PtrToInt(m_Value(RHSOp))))
809 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
810 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
812 // trunc(p)-trunc(q) -> trunc(p-q)
813 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
814 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
815 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
816 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
819 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
820 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
821 Value *Y = 0, *Z = Op1;
822 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
823 // See if "V === Y - Z" simplifies.
824 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
825 // It does! Now see if "X + V" simplifies.
826 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
828 // It does, we successfully reassociated!
832 // See if "V === X - Z" simplifies.
833 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
834 // It does! Now see if "Y + V" simplifies.
835 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
837 // It does, we successfully reassociated!
843 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
844 // For example, X - (X + 1) -> -1
846 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
847 // See if "V === X - Y" simplifies.
848 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
849 // It does! Now see if "V - Z" simplifies.
850 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
852 // It does, we successfully reassociated!
856 // See if "V === X - Z" simplifies.
857 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
858 // It does! Now see if "V - Y" simplifies.
859 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
861 // It does, we successfully reassociated!
867 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
868 // For example, X - (X - Y) -> Y.
870 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
871 // See if "V === Z - X" simplifies.
872 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
873 // It does! Now see if "V + Y" simplifies.
874 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
876 // It does, we successfully reassociated!
881 // Mul distributes over Sub. Try some generic simplifications based on this.
882 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
883 TD, TLI, DT, MaxRecurse))
887 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
888 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
891 // Threading Sub over selects and phi nodes is pointless, so don't bother.
892 // Threading over the select in "A - select(cond, B, C)" means evaluating
893 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
894 // only if B and C are equal. If B and C are equal then (since we assume
895 // that operands have already been simplified) "select(cond, B, C)" should
896 // have been simplified to the common value of B and C already. Analysing
897 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
898 // for threading over phi nodes.
903 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
904 const TargetData *TD,
905 const TargetLibraryInfo *TLI,
906 const DominatorTree *DT) {
907 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
910 /// SimplifyMulInst - Given operands for a Mul, see if we can
911 /// fold the result. If not, this returns null.
912 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
913 const TargetLibraryInfo *TLI,
914 const DominatorTree *DT, unsigned MaxRecurse) {
915 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
916 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
917 Constant *Ops[] = { CLHS, CRHS };
918 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
922 // Canonicalize the constant to the RHS.
927 if (match(Op1, m_Undef()))
928 return Constant::getNullValue(Op0->getType());
931 if (match(Op1, m_Zero()))
935 if (match(Op1, m_One()))
938 // (X / Y) * Y -> X if the division is exact.
940 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
941 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
945 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
946 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
949 // Try some generic simplifications for associative operations.
950 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
954 // Mul distributes over Add. Try some generic simplifications based on this.
955 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
956 TD, TLI, DT, MaxRecurse))
959 // If the operation is with the result of a select instruction, check whether
960 // operating on either branch of the select always yields the same value.
961 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
962 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
966 // If the operation is with the result of a phi instruction, check whether
967 // operating on all incoming values of the phi always yields the same value.
968 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
969 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
976 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
977 const TargetLibraryInfo *TLI,
978 const DominatorTree *DT) {
979 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
982 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
983 /// fold the result. If not, this returns null.
984 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
985 const TargetData *TD, const TargetLibraryInfo *TLI,
986 const DominatorTree *DT, unsigned MaxRecurse) {
987 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
988 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
989 Constant *Ops[] = { C0, C1 };
990 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
994 bool isSigned = Opcode == Instruction::SDiv;
996 // X / undef -> undef
997 if (match(Op1, m_Undef()))
1001 if (match(Op0, m_Undef()))
1002 return Constant::getNullValue(Op0->getType());
1004 // 0 / X -> 0, we don't need to preserve faults!
1005 if (match(Op0, m_Zero()))
1009 if (match(Op1, m_One()))
1012 if (Op0->getType()->isIntegerTy(1))
1013 // It can't be division by zero, hence it must be division by one.
1018 return ConstantInt::get(Op0->getType(), 1);
1020 // (X * Y) / Y -> X if the multiplication does not overflow.
1021 Value *X = 0, *Y = 0;
1022 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1023 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1024 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1025 // If the Mul knows it does not overflow, then we are good to go.
1026 if ((isSigned && Mul->hasNoSignedWrap()) ||
1027 (!isSigned && Mul->hasNoUnsignedWrap()))
1029 // If X has the form X = A / Y then X * Y cannot overflow.
1030 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1031 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1035 // (X rem Y) / Y -> 0
1036 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1037 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1038 return Constant::getNullValue(Op0->getType());
1040 // If the operation is with the result of a select instruction, check whether
1041 // operating on either branch of the select always yields the same value.
1042 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1043 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
1047 // If the operation is with the result of a phi instruction, check whether
1048 // operating on all incoming values of the phi always yields the same value.
1049 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1050 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
1057 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1058 /// fold the result. If not, this returns null.
1059 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1060 const TargetLibraryInfo *TLI,
1061 const DominatorTree *DT, unsigned MaxRecurse) {
1062 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
1069 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1070 const TargetLibraryInfo *TLI,
1071 const DominatorTree *DT) {
1072 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1075 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1076 /// fold the result. If not, this returns null.
1077 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1078 const TargetLibraryInfo *TLI,
1079 const DominatorTree *DT, unsigned MaxRecurse) {
1080 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
1087 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1088 const TargetLibraryInfo *TLI,
1089 const DominatorTree *DT) {
1090 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1093 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
1094 const TargetLibraryInfo *,
1095 const DominatorTree *, unsigned) {
1096 // undef / X -> undef (the undef could be a snan).
1097 if (match(Op0, m_Undef()))
1100 // X / undef -> undef
1101 if (match(Op1, m_Undef()))
1107 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1108 const TargetLibraryInfo *TLI,
1109 const DominatorTree *DT) {
1110 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1113 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1114 /// fold the result. If not, this returns null.
1115 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1116 const TargetData *TD, const TargetLibraryInfo *TLI,
1117 const DominatorTree *DT, unsigned MaxRecurse) {
1118 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1119 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1120 Constant *Ops[] = { C0, C1 };
1121 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1125 // X % undef -> undef
1126 if (match(Op1, m_Undef()))
1130 if (match(Op0, m_Undef()))
1131 return Constant::getNullValue(Op0->getType());
1133 // 0 % X -> 0, we don't need to preserve faults!
1134 if (match(Op0, m_Zero()))
1137 // X % 0 -> undef, we don't need to preserve faults!
1138 if (match(Op1, m_Zero()))
1139 return UndefValue::get(Op0->getType());
1142 if (match(Op1, m_One()))
1143 return Constant::getNullValue(Op0->getType());
1145 if (Op0->getType()->isIntegerTy(1))
1146 // It can't be remainder by zero, hence it must be remainder by one.
1147 return Constant::getNullValue(Op0->getType());
1151 return Constant::getNullValue(Op0->getType());
1153 // If the operation is with the result of a select instruction, check whether
1154 // operating on either branch of the select always yields the same value.
1155 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1156 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1159 // If the operation is with the result of a phi instruction, check whether
1160 // operating on all incoming values of the phi always yields the same value.
1161 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1162 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1168 /// SimplifySRemInst - Given operands for an SRem, see if we can
1169 /// fold the result. If not, this returns null.
1170 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1171 const TargetLibraryInfo *TLI,
1172 const DominatorTree *DT,
1173 unsigned MaxRecurse) {
1174 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1180 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1181 const TargetLibraryInfo *TLI,
1182 const DominatorTree *DT) {
1183 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1186 /// SimplifyURemInst - Given operands for a URem, see if we can
1187 /// fold the result. If not, this returns null.
1188 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1189 const TargetLibraryInfo *TLI,
1190 const DominatorTree *DT,
1191 unsigned MaxRecurse) {
1192 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1198 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1199 const TargetLibraryInfo *TLI,
1200 const DominatorTree *DT) {
1201 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1204 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1205 const TargetLibraryInfo *,
1206 const DominatorTree *,
1208 // undef % X -> undef (the undef could be a snan).
1209 if (match(Op0, m_Undef()))
1212 // X % undef -> undef
1213 if (match(Op1, m_Undef()))
1219 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1220 const TargetLibraryInfo *TLI,
1221 const DominatorTree *DT) {
1222 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1225 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1226 /// fold the result. If not, this returns null.
1227 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1228 const TargetData *TD, const TargetLibraryInfo *TLI,
1229 const DominatorTree *DT, unsigned MaxRecurse) {
1230 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1231 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1232 Constant *Ops[] = { C0, C1 };
1233 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1237 // 0 shift by X -> 0
1238 if (match(Op0, m_Zero()))
1241 // X shift by 0 -> X
1242 if (match(Op1, m_Zero()))
1245 // X shift by undef -> undef because it may shift by the bitwidth.
1246 if (match(Op1, m_Undef()))
1249 // Shifting by the bitwidth or more is undefined.
1250 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1251 if (CI->getValue().getLimitedValue() >=
1252 Op0->getType()->getScalarSizeInBits())
1253 return UndefValue::get(Op0->getType());
1255 // If the operation is with the result of a select instruction, check whether
1256 // operating on either branch of the select always yields the same value.
1257 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1258 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1261 // If the operation is with the result of a phi instruction, check whether
1262 // operating on all incoming values of the phi always yields the same value.
1263 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1264 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1270 /// SimplifyShlInst - Given operands for an Shl, see if we can
1271 /// fold the result. If not, this returns null.
1272 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1273 const TargetData *TD,
1274 const TargetLibraryInfo *TLI,
1275 const DominatorTree *DT, unsigned MaxRecurse) {
1276 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
1280 if (match(Op0, m_Undef()))
1281 return Constant::getNullValue(Op0->getType());
1283 // (X >> A) << A -> X
1285 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1290 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1291 const TargetData *TD, const TargetLibraryInfo *TLI,
1292 const DominatorTree *DT) {
1293 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
1296 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1297 /// fold the result. If not, this returns null.
1298 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1299 const TargetData *TD,
1300 const TargetLibraryInfo *TLI,
1301 const DominatorTree *DT,
1302 unsigned MaxRecurse) {
1303 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1307 if (match(Op0, m_Undef()))
1308 return Constant::getNullValue(Op0->getType());
1310 // (X << A) >> A -> X
1312 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1313 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1319 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1320 const TargetData *TD,
1321 const TargetLibraryInfo *TLI,
1322 const DominatorTree *DT) {
1323 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1326 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1327 /// fold the result. If not, this returns null.
1328 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1329 const TargetData *TD,
1330 const TargetLibraryInfo *TLI,
1331 const DominatorTree *DT,
1332 unsigned MaxRecurse) {
1333 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1336 // all ones >>a X -> all ones
1337 if (match(Op0, m_AllOnes()))
1340 // undef >>a X -> all ones
1341 if (match(Op0, m_Undef()))
1342 return Constant::getAllOnesValue(Op0->getType());
1344 // (X << A) >> A -> X
1346 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1347 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1353 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1354 const TargetData *TD,
1355 const TargetLibraryInfo *TLI,
1356 const DominatorTree *DT) {
1357 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1360 /// SimplifyAndInst - Given operands for an And, see if we can
1361 /// fold the result. If not, this returns null.
1362 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1363 const TargetLibraryInfo *TLI,
1364 const DominatorTree *DT,
1365 unsigned MaxRecurse) {
1366 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1367 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1368 Constant *Ops[] = { CLHS, CRHS };
1369 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1373 // Canonicalize the constant to the RHS.
1374 std::swap(Op0, Op1);
1378 if (match(Op1, m_Undef()))
1379 return Constant::getNullValue(Op0->getType());
1386 if (match(Op1, m_Zero()))
1390 if (match(Op1, m_AllOnes()))
1393 // A & ~A = ~A & A = 0
1394 if (match(Op0, m_Not(m_Specific(Op1))) ||
1395 match(Op1, m_Not(m_Specific(Op0))))
1396 return Constant::getNullValue(Op0->getType());
1399 Value *A = 0, *B = 0;
1400 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1401 (A == Op1 || B == Op1))
1405 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1406 (A == Op0 || B == Op0))
1409 // A & (-A) = A if A is a power of two or zero.
1410 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1411 match(Op1, m_Neg(m_Specific(Op0)))) {
1412 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1414 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1418 // Try some generic simplifications for associative operations.
1419 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1423 // And distributes over Or. Try some generic simplifications based on this.
1424 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1425 TD, TLI, DT, MaxRecurse))
1428 // And distributes over Xor. Try some generic simplifications based on this.
1429 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1430 TD, TLI, DT, MaxRecurse))
1433 // Or distributes over And. Try some generic simplifications based on this.
1434 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1435 TD, TLI, DT, MaxRecurse))
1438 // If the operation is with the result of a select instruction, check whether
1439 // operating on either branch of the select always yields the same value.
1440 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1441 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1445 // If the operation is with the result of a phi instruction, check whether
1446 // operating on all incoming values of the phi always yields the same value.
1447 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1448 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
1455 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1456 const TargetLibraryInfo *TLI,
1457 const DominatorTree *DT) {
1458 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1461 /// SimplifyOrInst - Given operands for an Or, see if we can
1462 /// fold the result. If not, this returns null.
1463 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1464 const TargetLibraryInfo *TLI,
1465 const DominatorTree *DT, unsigned MaxRecurse) {
1466 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1467 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1468 Constant *Ops[] = { CLHS, CRHS };
1469 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1473 // Canonicalize the constant to the RHS.
1474 std::swap(Op0, Op1);
1478 if (match(Op1, m_Undef()))
1479 return Constant::getAllOnesValue(Op0->getType());
1486 if (match(Op1, m_Zero()))
1490 if (match(Op1, m_AllOnes()))
1493 // A | ~A = ~A | A = -1
1494 if (match(Op0, m_Not(m_Specific(Op1))) ||
1495 match(Op1, m_Not(m_Specific(Op0))))
1496 return Constant::getAllOnesValue(Op0->getType());
1499 Value *A = 0, *B = 0;
1500 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1501 (A == Op1 || B == Op1))
1505 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1506 (A == Op0 || B == Op0))
1509 // ~(A & ?) | A = -1
1510 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1511 (A == Op1 || B == Op1))
1512 return Constant::getAllOnesValue(Op1->getType());
1514 // A | ~(A & ?) = -1
1515 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1516 (A == Op0 || B == Op0))
1517 return Constant::getAllOnesValue(Op0->getType());
1519 // Try some generic simplifications for associative operations.
1520 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1524 // Or distributes over And. Try some generic simplifications based on this.
1525 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1526 TLI, DT, MaxRecurse))
1529 // And distributes over Or. Try some generic simplifications based on this.
1530 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1531 TD, TLI, DT, MaxRecurse))
1534 // If the operation is with the result of a select instruction, check whether
1535 // operating on either branch of the select always yields the same value.
1536 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1537 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
1541 // If the operation is with the result of a phi instruction, check whether
1542 // operating on all incoming values of the phi always yields the same value.
1543 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1544 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
1551 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1552 const TargetLibraryInfo *TLI,
1553 const DominatorTree *DT) {
1554 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1557 /// SimplifyXorInst - Given operands for a Xor, see if we can
1558 /// fold the result. If not, this returns null.
1559 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1560 const TargetLibraryInfo *TLI,
1561 const DominatorTree *DT, unsigned MaxRecurse) {
1562 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1563 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1564 Constant *Ops[] = { CLHS, CRHS };
1565 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1569 // Canonicalize the constant to the RHS.
1570 std::swap(Op0, Op1);
1573 // A ^ undef -> undef
1574 if (match(Op1, m_Undef()))
1578 if (match(Op1, m_Zero()))
1583 return Constant::getNullValue(Op0->getType());
1585 // A ^ ~A = ~A ^ A = -1
1586 if (match(Op0, m_Not(m_Specific(Op1))) ||
1587 match(Op1, m_Not(m_Specific(Op0))))
1588 return Constant::getAllOnesValue(Op0->getType());
1590 // Try some generic simplifications for associative operations.
1591 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1595 // And distributes over Xor. Try some generic simplifications based on this.
1596 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1597 TD, TLI, DT, MaxRecurse))
1600 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1601 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1602 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1603 // only if B and C are equal. If B and C are equal then (since we assume
1604 // that operands have already been simplified) "select(cond, B, C)" should
1605 // have been simplified to the common value of B and C already. Analysing
1606 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1607 // for threading over phi nodes.
1612 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1613 const TargetLibraryInfo *TLI,
1614 const DominatorTree *DT) {
1615 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1618 static Type *GetCompareTy(Value *Op) {
1619 return CmpInst::makeCmpResultType(Op->getType());
1622 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1623 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1624 /// otherwise return null. Helper function for analyzing max/min idioms.
1625 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1626 Value *LHS, Value *RHS) {
1627 SelectInst *SI = dyn_cast<SelectInst>(V);
1630 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1633 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1634 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1636 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1637 LHS == CmpRHS && RHS == CmpLHS)
1643 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1644 /// fold the result. If not, this returns null.
1645 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1646 const TargetData *TD,
1647 const TargetLibraryInfo *TLI,
1648 const DominatorTree *DT,
1649 unsigned MaxRecurse) {
1650 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1651 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1653 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1654 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1655 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
1657 // If we have a constant, make sure it is on the RHS.
1658 std::swap(LHS, RHS);
1659 Pred = CmpInst::getSwappedPredicate(Pred);
1662 Type *ITy = GetCompareTy(LHS); // The return type.
1663 Type *OpTy = LHS->getType(); // The operand type.
1665 // icmp X, X -> true/false
1666 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1667 // because X could be 0.
1668 if (LHS == RHS || isa<UndefValue>(RHS))
1669 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1671 // Special case logic when the operands have i1 type.
1672 if (OpTy->getScalarType()->isIntegerTy(1)) {
1675 case ICmpInst::ICMP_EQ:
1677 if (match(RHS, m_One()))
1680 case ICmpInst::ICMP_NE:
1682 if (match(RHS, m_Zero()))
1685 case ICmpInst::ICMP_UGT:
1687 if (match(RHS, m_Zero()))
1690 case ICmpInst::ICMP_UGE:
1692 if (match(RHS, m_One()))
1695 case ICmpInst::ICMP_SLT:
1697 if (match(RHS, m_Zero()))
1700 case ICmpInst::ICMP_SLE:
1702 if (match(RHS, m_One()))
1708 // icmp <object*>, <object*/null> - Different identified objects have
1709 // different addresses (unless null), and what's more the address of an
1710 // identified local is never equal to another argument (again, barring null).
1711 // Note that generalizing to the case where LHS is a global variable address
1712 // or null is pointless, since if both LHS and RHS are constants then we
1713 // already constant folded the compare, and if only one of them is then we
1714 // moved it to RHS already.
1715 Value *LHSPtr = LHS->stripPointerCasts();
1716 Value *RHSPtr = RHS->stripPointerCasts();
1717 if (LHSPtr == RHSPtr)
1718 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1720 // Be more aggressive about stripping pointer adjustments when checking a
1721 // comparison of an alloca address to another object. We can rip off all
1722 // inbounds GEP operations, even if they are variable.
1723 LHSPtr = LHSPtr->stripInBoundsOffsets();
1724 if (llvm::isIdentifiedObject(LHSPtr)) {
1725 RHSPtr = RHSPtr->stripInBoundsOffsets();
1726 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1727 // If both sides are different identified objects, they aren't equal
1728 // unless they're null.
1729 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
1730 Pred == CmpInst::ICMP_EQ)
1731 return ConstantInt::get(ITy, false);
1733 // A local identified object (alloca or noalias call) can't equal any
1734 // incoming argument, unless they're both null.
1735 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
1736 Pred == CmpInst::ICMP_EQ)
1737 return ConstantInt::get(ITy, false);
1740 // Assume that the constant null is on the right.
1741 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
1742 if (Pred == CmpInst::ICMP_EQ)
1743 return ConstantInt::get(ITy, false);
1744 else if (Pred == CmpInst::ICMP_NE)
1745 return ConstantInt::get(ITy, true);
1747 } else if (isa<Argument>(LHSPtr)) {
1748 RHSPtr = RHSPtr->stripInBoundsOffsets();
1749 // An alloca can't be equal to an argument.
1750 if (isa<AllocaInst>(RHSPtr)) {
1751 if (Pred == CmpInst::ICMP_EQ)
1752 return ConstantInt::get(ITy, false);
1753 else if (Pred == CmpInst::ICMP_NE)
1754 return ConstantInt::get(ITy, true);
1758 // If we are comparing with zero then try hard since this is a common case.
1759 if (match(RHS, m_Zero())) {
1760 bool LHSKnownNonNegative, LHSKnownNegative;
1762 default: llvm_unreachable("Unknown ICmp predicate!");
1763 case ICmpInst::ICMP_ULT:
1764 return getFalse(ITy);
1765 case ICmpInst::ICMP_UGE:
1766 return getTrue(ITy);
1767 case ICmpInst::ICMP_EQ:
1768 case ICmpInst::ICMP_ULE:
1769 if (isKnownNonZero(LHS, TD))
1770 return getFalse(ITy);
1772 case ICmpInst::ICMP_NE:
1773 case ICmpInst::ICMP_UGT:
1774 if (isKnownNonZero(LHS, TD))
1775 return getTrue(ITy);
1777 case ICmpInst::ICMP_SLT:
1778 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1779 if (LHSKnownNegative)
1780 return getTrue(ITy);
1781 if (LHSKnownNonNegative)
1782 return getFalse(ITy);
1784 case ICmpInst::ICMP_SLE:
1785 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1786 if (LHSKnownNegative)
1787 return getTrue(ITy);
1788 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1789 return getFalse(ITy);
1791 case ICmpInst::ICMP_SGE:
1792 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1793 if (LHSKnownNegative)
1794 return getFalse(ITy);
1795 if (LHSKnownNonNegative)
1796 return getTrue(ITy);
1798 case ICmpInst::ICMP_SGT:
1799 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1800 if (LHSKnownNegative)
1801 return getFalse(ITy);
1802 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1803 return getTrue(ITy);
1808 // See if we are doing a comparison with a constant integer.
1809 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1810 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1811 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1812 if (RHS_CR.isEmptySet())
1813 return ConstantInt::getFalse(CI->getContext());
1814 if (RHS_CR.isFullSet())
1815 return ConstantInt::getTrue(CI->getContext());
1817 // Many binary operators with constant RHS have easy to compute constant
1818 // range. Use them to check whether the comparison is a tautology.
1819 uint32_t Width = CI->getBitWidth();
1820 APInt Lower = APInt(Width, 0);
1821 APInt Upper = APInt(Width, 0);
1823 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1824 // 'urem x, CI2' produces [0, CI2).
1825 Upper = CI2->getValue();
1826 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1827 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1828 Upper = CI2->getValue().abs();
1829 Lower = (-Upper) + 1;
1830 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1831 // 'udiv CI2, x' produces [0, CI2].
1832 Upper = CI2->getValue() + 1;
1833 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1834 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1835 APInt NegOne = APInt::getAllOnesValue(Width);
1837 Upper = NegOne.udiv(CI2->getValue()) + 1;
1838 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1839 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1840 APInt IntMin = APInt::getSignedMinValue(Width);
1841 APInt IntMax = APInt::getSignedMaxValue(Width);
1842 APInt Val = CI2->getValue().abs();
1843 if (!Val.isMinValue()) {
1844 Lower = IntMin.sdiv(Val);
1845 Upper = IntMax.sdiv(Val) + 1;
1847 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1848 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1849 APInt NegOne = APInt::getAllOnesValue(Width);
1850 if (CI2->getValue().ult(Width))
1851 Upper = NegOne.lshr(CI2->getValue()) + 1;
1852 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1853 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1854 APInt IntMin = APInt::getSignedMinValue(Width);
1855 APInt IntMax = APInt::getSignedMaxValue(Width);
1856 if (CI2->getValue().ult(Width)) {
1857 Lower = IntMin.ashr(CI2->getValue());
1858 Upper = IntMax.ashr(CI2->getValue()) + 1;
1860 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1861 // 'or x, CI2' produces [CI2, UINT_MAX].
1862 Lower = CI2->getValue();
1863 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1864 // 'and x, CI2' produces [0, CI2].
1865 Upper = CI2->getValue() + 1;
1867 if (Lower != Upper) {
1868 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1869 if (RHS_CR.contains(LHS_CR))
1870 return ConstantInt::getTrue(RHS->getContext());
1871 if (RHS_CR.inverse().contains(LHS_CR))
1872 return ConstantInt::getFalse(RHS->getContext());
1876 // Compare of cast, for example (zext X) != 0 -> X != 0
1877 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1878 Instruction *LI = cast<CastInst>(LHS);
1879 Value *SrcOp = LI->getOperand(0);
1880 Type *SrcTy = SrcOp->getType();
1881 Type *DstTy = LI->getType();
1883 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1884 // if the integer type is the same size as the pointer type.
1885 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1886 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1887 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1888 // Transfer the cast to the constant.
1889 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1890 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1891 TD, TLI, DT, MaxRecurse-1))
1893 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1894 if (RI->getOperand(0)->getType() == SrcTy)
1895 // Compare without the cast.
1896 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1897 TD, TLI, DT, MaxRecurse-1))
1902 if (isa<ZExtInst>(LHS)) {
1903 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1905 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1906 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1907 // Compare X and Y. Note that signed predicates become unsigned.
1908 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1909 SrcOp, RI->getOperand(0), TD, TLI, DT,
1913 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1914 // too. If not, then try to deduce the result of the comparison.
1915 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1916 // Compute the constant that would happen if we truncated to SrcTy then
1917 // reextended to DstTy.
1918 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1919 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1921 // If the re-extended constant didn't change then this is effectively
1922 // also a case of comparing two zero-extended values.
1923 if (RExt == CI && MaxRecurse)
1924 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1925 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
1928 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1929 // there. Use this to work out the result of the comparison.
1932 default: llvm_unreachable("Unknown ICmp predicate!");
1934 case ICmpInst::ICMP_EQ:
1935 case ICmpInst::ICMP_UGT:
1936 case ICmpInst::ICMP_UGE:
1937 return ConstantInt::getFalse(CI->getContext());
1939 case ICmpInst::ICMP_NE:
1940 case ICmpInst::ICMP_ULT:
1941 case ICmpInst::ICMP_ULE:
1942 return ConstantInt::getTrue(CI->getContext());
1944 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1945 // is non-negative then LHS <s RHS.
1946 case ICmpInst::ICMP_SGT:
1947 case ICmpInst::ICMP_SGE:
1948 return CI->getValue().isNegative() ?
1949 ConstantInt::getTrue(CI->getContext()) :
1950 ConstantInt::getFalse(CI->getContext());
1952 case ICmpInst::ICMP_SLT:
1953 case ICmpInst::ICMP_SLE:
1954 return CI->getValue().isNegative() ?
1955 ConstantInt::getFalse(CI->getContext()) :
1956 ConstantInt::getTrue(CI->getContext());
1962 if (isa<SExtInst>(LHS)) {
1963 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1965 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1966 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1967 // Compare X and Y. Note that the predicate does not change.
1968 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1969 TD, TLI, DT, MaxRecurse-1))
1972 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1973 // too. If not, then try to deduce the result of the comparison.
1974 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1975 // Compute the constant that would happen if we truncated to SrcTy then
1976 // reextended to DstTy.
1977 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1978 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1980 // If the re-extended constant didn't change then this is effectively
1981 // also a case of comparing two sign-extended values.
1982 if (RExt == CI && MaxRecurse)
1983 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
1987 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1988 // bits there. Use this to work out the result of the comparison.
1991 default: llvm_unreachable("Unknown ICmp predicate!");
1992 case ICmpInst::ICMP_EQ:
1993 return ConstantInt::getFalse(CI->getContext());
1994 case ICmpInst::ICMP_NE:
1995 return ConstantInt::getTrue(CI->getContext());
1997 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1999 case ICmpInst::ICMP_SGT:
2000 case ICmpInst::ICMP_SGE:
2001 return CI->getValue().isNegative() ?
2002 ConstantInt::getTrue(CI->getContext()) :
2003 ConstantInt::getFalse(CI->getContext());
2004 case ICmpInst::ICMP_SLT:
2005 case ICmpInst::ICMP_SLE:
2006 return CI->getValue().isNegative() ?
2007 ConstantInt::getFalse(CI->getContext()) :
2008 ConstantInt::getTrue(CI->getContext());
2010 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2012 case ICmpInst::ICMP_UGT:
2013 case ICmpInst::ICMP_UGE:
2014 // Comparison is true iff the LHS <s 0.
2016 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2017 Constant::getNullValue(SrcTy),
2018 TD, TLI, DT, MaxRecurse-1))
2021 case ICmpInst::ICMP_ULT:
2022 case ICmpInst::ICMP_ULE:
2023 // Comparison is true iff the LHS >=s 0.
2025 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2026 Constant::getNullValue(SrcTy),
2027 TD, TLI, DT, MaxRecurse-1))
2036 // Special logic for binary operators.
2037 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2038 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2039 if (MaxRecurse && (LBO || RBO)) {
2040 // Analyze the case when either LHS or RHS is an add instruction.
2041 Value *A = 0, *B = 0, *C = 0, *D = 0;
2042 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2043 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2044 if (LBO && LBO->getOpcode() == Instruction::Add) {
2045 A = LBO->getOperand(0); B = LBO->getOperand(1);
2046 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2047 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2048 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2050 if (RBO && RBO->getOpcode() == Instruction::Add) {
2051 C = RBO->getOperand(0); D = RBO->getOperand(1);
2052 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2053 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2054 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2057 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2058 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2059 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2060 Constant::getNullValue(RHS->getType()),
2061 TD, TLI, DT, MaxRecurse-1))
2064 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2065 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2066 if (Value *V = SimplifyICmpInst(Pred,
2067 Constant::getNullValue(LHS->getType()),
2068 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
2071 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2072 if (A && C && (A == C || A == D || B == C || B == D) &&
2073 NoLHSWrapProblem && NoRHSWrapProblem) {
2074 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2075 Value *Y = (A == C || A == D) ? B : A;
2076 Value *Z = (C == A || C == B) ? D : C;
2077 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
2082 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2083 bool KnownNonNegative, KnownNegative;
2087 case ICmpInst::ICMP_SGT:
2088 case ICmpInst::ICMP_SGE:
2089 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2090 if (!KnownNonNegative)
2093 case ICmpInst::ICMP_EQ:
2094 case ICmpInst::ICMP_UGT:
2095 case ICmpInst::ICMP_UGE:
2096 return getFalse(ITy);
2097 case ICmpInst::ICMP_SLT:
2098 case ICmpInst::ICMP_SLE:
2099 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2100 if (!KnownNonNegative)
2103 case ICmpInst::ICMP_NE:
2104 case ICmpInst::ICMP_ULT:
2105 case ICmpInst::ICMP_ULE:
2106 return getTrue(ITy);
2109 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2110 bool KnownNonNegative, KnownNegative;
2114 case ICmpInst::ICMP_SGT:
2115 case ICmpInst::ICMP_SGE:
2116 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2117 if (!KnownNonNegative)
2120 case ICmpInst::ICMP_NE:
2121 case ICmpInst::ICMP_UGT:
2122 case ICmpInst::ICMP_UGE:
2123 return getTrue(ITy);
2124 case ICmpInst::ICMP_SLT:
2125 case ICmpInst::ICMP_SLE:
2126 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2127 if (!KnownNonNegative)
2130 case ICmpInst::ICMP_EQ:
2131 case ICmpInst::ICMP_ULT:
2132 case ICmpInst::ICMP_ULE:
2133 return getFalse(ITy);
2138 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2139 // icmp pred (X /u Y), X
2140 if (Pred == ICmpInst::ICMP_UGT)
2141 return getFalse(ITy);
2142 if (Pred == ICmpInst::ICMP_ULE)
2143 return getTrue(ITy);
2146 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2147 LBO->getOperand(1) == RBO->getOperand(1)) {
2148 switch (LBO->getOpcode()) {
2150 case Instruction::UDiv:
2151 case Instruction::LShr:
2152 if (ICmpInst::isSigned(Pred))
2155 case Instruction::SDiv:
2156 case Instruction::AShr:
2157 if (!LBO->isExact() || !RBO->isExact())
2159 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2160 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2163 case Instruction::Shl: {
2164 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2165 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2168 if (!NSW && ICmpInst::isSigned(Pred))
2170 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2171 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2178 // Simplify comparisons involving max/min.
2180 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2181 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2183 // Signed variants on "max(a,b)>=a -> true".
2184 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2185 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2186 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2187 // We analyze this as smax(A, B) pred A.
2189 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2190 (A == LHS || B == LHS)) {
2191 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2192 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2193 // We analyze this as smax(A, B) swapped-pred A.
2194 P = CmpInst::getSwappedPredicate(Pred);
2195 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2196 (A == RHS || B == RHS)) {
2197 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2198 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2199 // We analyze this as smax(-A, -B) swapped-pred -A.
2200 // Note that we do not need to actually form -A or -B thanks to EqP.
2201 P = CmpInst::getSwappedPredicate(Pred);
2202 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2203 (A == LHS || B == LHS)) {
2204 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2205 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2206 // We analyze this as smax(-A, -B) pred -A.
2207 // Note that we do not need to actually form -A or -B thanks to EqP.
2210 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2211 // Cases correspond to "max(A, B) p A".
2215 case CmpInst::ICMP_EQ:
2216 case CmpInst::ICMP_SLE:
2217 // Equivalent to "A EqP B". This may be the same as the condition tested
2218 // in the max/min; if so, we can just return that.
2219 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2221 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2223 // Otherwise, see if "A EqP B" simplifies.
2225 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2228 case CmpInst::ICMP_NE:
2229 case CmpInst::ICMP_SGT: {
2230 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2231 // Equivalent to "A InvEqP B". This may be the same as the condition
2232 // tested in the max/min; if so, we can just return that.
2233 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2235 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2237 // Otherwise, see if "A InvEqP B" simplifies.
2239 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2243 case CmpInst::ICMP_SGE:
2245 return getTrue(ITy);
2246 case CmpInst::ICMP_SLT:
2248 return getFalse(ITy);
2252 // Unsigned variants on "max(a,b)>=a -> true".
2253 P = CmpInst::BAD_ICMP_PREDICATE;
2254 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2255 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2256 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2257 // We analyze this as umax(A, B) pred A.
2259 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2260 (A == LHS || B == LHS)) {
2261 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2262 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2263 // We analyze this as umax(A, B) swapped-pred A.
2264 P = CmpInst::getSwappedPredicate(Pred);
2265 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2266 (A == RHS || B == RHS)) {
2267 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2268 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2269 // We analyze this as umax(-A, -B) swapped-pred -A.
2270 // Note that we do not need to actually form -A or -B thanks to EqP.
2271 P = CmpInst::getSwappedPredicate(Pred);
2272 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2273 (A == LHS || B == LHS)) {
2274 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2275 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2276 // We analyze this as umax(-A, -B) pred -A.
2277 // Note that we do not need to actually form -A or -B thanks to EqP.
2280 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2281 // Cases correspond to "max(A, B) p A".
2285 case CmpInst::ICMP_EQ:
2286 case CmpInst::ICMP_ULE:
2287 // Equivalent to "A EqP B". This may be the same as the condition tested
2288 // in the max/min; if so, we can just return that.
2289 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2291 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2293 // Otherwise, see if "A EqP B" simplifies.
2295 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2298 case CmpInst::ICMP_NE:
2299 case CmpInst::ICMP_UGT: {
2300 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2301 // Equivalent to "A InvEqP B". This may be the same as the condition
2302 // tested in the max/min; if so, we can just return that.
2303 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2305 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2307 // Otherwise, see if "A InvEqP B" simplifies.
2309 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2313 case CmpInst::ICMP_UGE:
2315 return getTrue(ITy);
2316 case CmpInst::ICMP_ULT:
2318 return getFalse(ITy);
2322 // Variants on "max(x,y) >= min(x,z)".
2324 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2325 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2326 (A == C || A == D || B == C || B == D)) {
2327 // max(x, ?) pred min(x, ?).
2328 if (Pred == CmpInst::ICMP_SGE)
2330 return getTrue(ITy);
2331 if (Pred == CmpInst::ICMP_SLT)
2333 return getFalse(ITy);
2334 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2335 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2336 (A == C || A == D || B == C || B == D)) {
2337 // min(x, ?) pred max(x, ?).
2338 if (Pred == CmpInst::ICMP_SLE)
2340 return getTrue(ITy);
2341 if (Pred == CmpInst::ICMP_SGT)
2343 return getFalse(ITy);
2344 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2345 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2346 (A == C || A == D || B == C || B == D)) {
2347 // max(x, ?) pred min(x, ?).
2348 if (Pred == CmpInst::ICMP_UGE)
2350 return getTrue(ITy);
2351 if (Pred == CmpInst::ICMP_ULT)
2353 return getFalse(ITy);
2354 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2355 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2356 (A == C || A == D || B == C || B == D)) {
2357 // min(x, ?) pred max(x, ?).
2358 if (Pred == CmpInst::ICMP_ULE)
2360 return getTrue(ITy);
2361 if (Pred == CmpInst::ICMP_UGT)
2363 return getFalse(ITy);
2366 // Simplify comparisons of GEPs.
2367 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2368 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2369 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2370 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2371 (ICmpInst::isEquality(Pred) ||
2372 (GLHS->isInBounds() && GRHS->isInBounds() &&
2373 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2374 // The bases are equal and the indices are constant. Build a constant
2375 // expression GEP with the same indices and a null base pointer to see
2376 // what constant folding can make out of it.
2377 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2378 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2379 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2381 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2382 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2383 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2388 // If the comparison is with the result of a select instruction, check whether
2389 // comparing with either branch of the select always yields the same value.
2390 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2391 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2394 // If the comparison is with the result of a phi instruction, check whether
2395 // doing the compare with each incoming phi value yields a common result.
2396 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2397 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2403 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2404 const TargetData *TD,
2405 const TargetLibraryInfo *TLI,
2406 const DominatorTree *DT) {
2407 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2410 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2411 /// fold the result. If not, this returns null.
2412 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2413 const TargetData *TD,
2414 const TargetLibraryInfo *TLI,
2415 const DominatorTree *DT,
2416 unsigned MaxRecurse) {
2417 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2418 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2420 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2421 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2422 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
2424 // If we have a constant, make sure it is on the RHS.
2425 std::swap(LHS, RHS);
2426 Pred = CmpInst::getSwappedPredicate(Pred);
2429 // Fold trivial predicates.
2430 if (Pred == FCmpInst::FCMP_FALSE)
2431 return ConstantInt::get(GetCompareTy(LHS), 0);
2432 if (Pred == FCmpInst::FCMP_TRUE)
2433 return ConstantInt::get(GetCompareTy(LHS), 1);
2435 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2436 return UndefValue::get(GetCompareTy(LHS));
2438 // fcmp x,x -> true/false. Not all compares are foldable.
2440 if (CmpInst::isTrueWhenEqual(Pred))
2441 return ConstantInt::get(GetCompareTy(LHS), 1);
2442 if (CmpInst::isFalseWhenEqual(Pred))
2443 return ConstantInt::get(GetCompareTy(LHS), 0);
2446 // Handle fcmp with constant RHS
2447 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2448 // If the constant is a nan, see if we can fold the comparison based on it.
2449 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2450 if (CFP->getValueAPF().isNaN()) {
2451 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2452 return ConstantInt::getFalse(CFP->getContext());
2453 assert(FCmpInst::isUnordered(Pred) &&
2454 "Comparison must be either ordered or unordered!");
2455 // True if unordered.
2456 return ConstantInt::getTrue(CFP->getContext());
2458 // Check whether the constant is an infinity.
2459 if (CFP->getValueAPF().isInfinity()) {
2460 if (CFP->getValueAPF().isNegative()) {
2462 case FCmpInst::FCMP_OLT:
2463 // No value is ordered and less than negative infinity.
2464 return ConstantInt::getFalse(CFP->getContext());
2465 case FCmpInst::FCMP_UGE:
2466 // All values are unordered with or at least negative infinity.
2467 return ConstantInt::getTrue(CFP->getContext());
2473 case FCmpInst::FCMP_OGT:
2474 // No value is ordered and greater than infinity.
2475 return ConstantInt::getFalse(CFP->getContext());
2476 case FCmpInst::FCMP_ULE:
2477 // All values are unordered with and at most infinity.
2478 return ConstantInt::getTrue(CFP->getContext());
2487 // If the comparison is with the result of a select instruction, check whether
2488 // comparing with either branch of the select always yields the same value.
2489 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2490 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2493 // If the comparison is with the result of a phi instruction, check whether
2494 // doing the compare with each incoming phi value yields a common result.
2495 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2496 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2502 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2503 const TargetData *TD,
2504 const TargetLibraryInfo *TLI,
2505 const DominatorTree *DT) {
2506 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2509 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2510 /// the result. If not, this returns null.
2511 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2512 const TargetData *TD, const DominatorTree *) {
2513 // select true, X, Y -> X
2514 // select false, X, Y -> Y
2515 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2516 return CB->getZExtValue() ? TrueVal : FalseVal;
2518 // select C, X, X -> X
2519 if (TrueVal == FalseVal)
2522 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2523 if (isa<Constant>(TrueVal))
2527 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2529 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2535 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2536 /// fold the result. If not, this returns null.
2537 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2538 const DominatorTree *) {
2539 // The type of the GEP pointer operand.
2540 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2541 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2545 // getelementptr P -> P.
2546 if (Ops.size() == 1)
2549 if (isa<UndefValue>(Ops[0])) {
2550 // Compute the (pointer) type returned by the GEP instruction.
2551 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2552 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2553 return UndefValue::get(GEPTy);
2556 if (Ops.size() == 2) {
2557 // getelementptr P, 0 -> P.
2558 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2561 // getelementptr P, N -> P if P points to a type of zero size.
2563 Type *Ty = PtrTy->getElementType();
2564 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2569 // Check to see if this is constant foldable.
2570 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2571 if (!isa<Constant>(Ops[i]))
2574 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2577 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2578 /// can fold the result. If not, this returns null.
2579 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2580 ArrayRef<unsigned> Idxs,
2582 const DominatorTree *) {
2583 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2584 if (Constant *CVal = dyn_cast<Constant>(Val))
2585 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2587 // insertvalue x, undef, n -> x
2588 if (match(Val, m_Undef()))
2591 // insertvalue x, (extractvalue y, n), n
2592 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2593 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2594 EV->getIndices() == Idxs) {
2595 // insertvalue undef, (extractvalue y, n), n -> y
2596 if (match(Agg, m_Undef()))
2597 return EV->getAggregateOperand();
2599 // insertvalue y, (extractvalue y, n), n -> y
2600 if (Agg == EV->getAggregateOperand())
2607 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2608 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2609 // If all of the PHI's incoming values are the same then replace the PHI node
2610 // with the common value.
2611 Value *CommonValue = 0;
2612 bool HasUndefInput = false;
2613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2614 Value *Incoming = PN->getIncomingValue(i);
2615 // If the incoming value is the phi node itself, it can safely be skipped.
2616 if (Incoming == PN) continue;
2617 if (isa<UndefValue>(Incoming)) {
2618 // Remember that we saw an undef value, but otherwise ignore them.
2619 HasUndefInput = true;
2622 if (CommonValue && Incoming != CommonValue)
2623 return 0; // Not the same, bail out.
2624 CommonValue = Incoming;
2627 // If CommonValue is null then all of the incoming values were either undef or
2628 // equal to the phi node itself.
2630 return UndefValue::get(PN->getType());
2632 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2633 // instruction, we cannot return X as the result of the PHI node unless it
2634 // dominates the PHI block.
2636 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2641 //=== Helper functions for higher up the class hierarchy.
2643 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2644 /// fold the result. If not, this returns null.
2645 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2646 const TargetData *TD,
2647 const TargetLibraryInfo *TLI,
2648 const DominatorTree *DT,
2649 unsigned MaxRecurse) {
2651 case Instruction::Add:
2652 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2653 TD, TLI, DT, MaxRecurse);
2654 case Instruction::Sub:
2655 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2656 TD, TLI, DT, MaxRecurse);
2657 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2659 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2661 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2663 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2665 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2667 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2669 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2671 case Instruction::Shl:
2672 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2673 TD, TLI, DT, MaxRecurse);
2674 case Instruction::LShr:
2675 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2677 case Instruction::AShr:
2678 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2680 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2682 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2684 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2687 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2688 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2689 Constant *COps[] = {CLHS, CRHS};
2690 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
2693 // If the operation is associative, try some generic simplifications.
2694 if (Instruction::isAssociative(Opcode))
2695 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
2699 // If the operation is with the result of a select instruction, check whether
2700 // operating on either branch of the select always yields the same value.
2701 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2702 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
2706 // If the operation is with the result of a phi instruction, check whether
2707 // operating on all incoming values of the phi always yields the same value.
2708 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2709 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2717 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2718 const TargetData *TD, const TargetLibraryInfo *TLI,
2719 const DominatorTree *DT) {
2720 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
2723 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2724 /// fold the result.
2725 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2726 const TargetData *TD,
2727 const TargetLibraryInfo *TLI,
2728 const DominatorTree *DT,
2729 unsigned MaxRecurse) {
2730 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2731 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2732 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2735 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2736 const TargetData *TD, const TargetLibraryInfo *TLI,
2737 const DominatorTree *DT) {
2738 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2741 static Value *SimplifyCallInst(CallInst *CI) {
2742 // call undef -> undef
2743 if (isa<UndefValue>(CI->getCalledValue()))
2744 return UndefValue::get(CI->getType());
2749 /// SimplifyInstruction - See if we can compute a simplified version of this
2750 /// instruction. If not, this returns null.
2751 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2752 const TargetLibraryInfo *TLI,
2753 const DominatorTree *DT) {
2756 switch (I->getOpcode()) {
2758 Result = ConstantFoldInstruction(I, TD, TLI);
2760 case Instruction::Add:
2761 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2762 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2763 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2766 case Instruction::Sub:
2767 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2768 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2769 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2772 case Instruction::Mul:
2773 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2775 case Instruction::SDiv:
2776 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2778 case Instruction::UDiv:
2779 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2781 case Instruction::FDiv:
2782 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2784 case Instruction::SRem:
2785 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2787 case Instruction::URem:
2788 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2790 case Instruction::FRem:
2791 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2793 case Instruction::Shl:
2794 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2795 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2796 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2799 case Instruction::LShr:
2800 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2801 cast<BinaryOperator>(I)->isExact(),
2804 case Instruction::AShr:
2805 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2806 cast<BinaryOperator>(I)->isExact(),
2809 case Instruction::And:
2810 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2812 case Instruction::Or:
2813 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2815 case Instruction::Xor:
2816 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2818 case Instruction::ICmp:
2819 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2820 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2822 case Instruction::FCmp:
2823 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2824 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2826 case Instruction::Select:
2827 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2828 I->getOperand(2), TD, DT);
2830 case Instruction::GetElementPtr: {
2831 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2832 Result = SimplifyGEPInst(Ops, TD, DT);
2835 case Instruction::InsertValue: {
2836 InsertValueInst *IV = cast<InsertValueInst>(I);
2837 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2838 IV->getInsertedValueOperand(),
2839 IV->getIndices(), TD, DT);
2842 case Instruction::PHI:
2843 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2845 case Instruction::Call:
2846 Result = SimplifyCallInst(cast<CallInst>(I));
2850 /// If called on unreachable code, the above logic may report that the
2851 /// instruction simplified to itself. Make life easier for users by
2852 /// detecting that case here, returning a safe value instead.
2853 return Result == I ? UndefValue::get(I->getType()) : Result;
2856 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2857 /// delete the From instruction. In addition to a basic RAUW, this does a
2858 /// recursive simplification of the newly formed instructions. This catches
2859 /// things where one simplification exposes other opportunities. This only
2860 /// simplifies and deletes scalar operations, it does not change the CFG.
2862 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2863 const TargetData *TD,
2864 const TargetLibraryInfo *TLI,
2865 const DominatorTree *DT) {
2866 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2868 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2869 // we can know if it gets deleted out from under us or replaced in a
2870 // recursive simplification.
2871 WeakVH FromHandle(From);
2872 WeakVH ToHandle(To);
2874 while (!From->use_empty()) {
2875 // Update the instruction to use the new value.
2876 Use &TheUse = From->use_begin().getUse();
2877 Instruction *User = cast<Instruction>(TheUse.getUser());
2880 // Check to see if the instruction can be folded due to the operand
2881 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2882 // the 'or' with -1.
2883 Value *SimplifiedVal;
2885 // Sanity check to make sure 'User' doesn't dangle across
2886 // SimplifyInstruction.
2887 AssertingVH<> UserHandle(User);
2889 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
2890 if (SimplifiedVal == 0) continue;
2893 // Recursively simplify this user to the new value.
2894 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
2895 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2898 assert(ToHandle && "To value deleted by recursive simplification?");
2900 // If the recursive simplification ended up revisiting and deleting
2901 // 'From' then we're done.
2906 // If 'From' has value handles referring to it, do a real RAUW to update them.
2907 From->replaceAllUsesWith(To);
2909 From->eraseFromParent();