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/Analysis/InstructionSimplify.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/ValueHandle.h"
36 using namespace llvm::PatternMatch;
38 enum { RecursionLimit = 3 };
40 STATISTIC(NumExpand, "Number of expansions");
41 STATISTIC(NumFactor , "Number of factorizations");
42 STATISTIC(NumReassoc, "Number of reassociations");
46 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
49 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
50 const DominatorTree *dt) : DL(DL), TLI(tli), DT(dt) {}
53 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
56 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
58 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
60 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
62 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
63 /// a vector with every element false, as appropriate for the type.
64 static Constant *getFalse(Type *Ty) {
65 assert(Ty->getScalarType()->isIntegerTy(1) &&
66 "Expected i1 type or a vector of i1!");
67 return Constant::getNullValue(Ty);
70 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
71 /// a vector with every element true, as appropriate for the type.
72 static Constant *getTrue(Type *Ty) {
73 assert(Ty->getScalarType()->isIntegerTy(1) &&
74 "Expected i1 type or a vector of i1!");
75 return Constant::getAllOnesValue(Ty);
78 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
81 CmpInst *Cmp = dyn_cast<CmpInst>(V);
84 CmpInst::Predicate CPred = Cmp->getPredicate();
85 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
88 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
92 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
93 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94 Instruction *I = dyn_cast<Instruction>(V);
96 // Arguments and constants dominate all instructions.
99 // If we are processing instructions (and/or basic blocks) that have not been
100 // fully added to a function, the parent nodes may still be null. Simply
101 // return the conservative answer in these cases.
102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
105 // If we have a DominatorTree then do a precise test.
107 if (!DT->isReachableFromEntry(P->getParent()))
109 if (!DT->isReachableFromEntry(I->getParent()))
111 return DT->dominates(I, P);
114 // Otherwise, if the instruction is in the entry block, and is not an invoke,
115 // then it obviously dominates all phi nodes.
116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
123 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
125 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127 /// Returns the simplified value, or null if no simplification was performed.
128 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
129 unsigned OpcToExpand, const Query &Q,
130 unsigned MaxRecurse) {
131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
132 // Recursion is always used, so bail out at once if we already hit the limit.
136 // Check whether the expression has the form "(A op' B) op C".
137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138 if (Op0->getOpcode() == OpcodeToExpand) {
139 // It does! Try turning it into "(A op C) op' (B op C)".
140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141 // Do "A op C" and "B op C" both simplify?
142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
144 // They do! Return "L op' R" if it simplifies or is already available.
145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147 && L == B && R == A)) {
151 // Otherwise return "L op' R" if it simplifies.
152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
159 // Check whether the expression has the form "A op (B op' C)".
160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161 if (Op1->getOpcode() == OpcodeToExpand) {
162 // It does! Try turning it into "(A op B) op' (A op C)".
163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164 // Do "A op B" and "A op C" both simplify?
165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
167 // They do! Return "L op' R" if it simplifies or is already available.
168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170 && L == C && R == B)) {
174 // Otherwise return "L op' R" if it simplifies.
175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
185 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
186 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
187 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
188 /// Returns the simplified value, or null if no simplification was performed.
189 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
190 unsigned OpcToExtract, const Query &Q,
191 unsigned MaxRecurse) {
192 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
193 // Recursion is always used, so bail out at once if we already hit the limit.
197 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
198 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
200 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
201 !Op1 || Op1->getOpcode() != OpcodeToExtract)
204 // The expression has the form "(A op' B) op (C op' D)".
205 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
206 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
208 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
209 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
210 // commutative case, "(A op' B) op (C op' A)"?
211 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
212 Value *DD = A == C ? D : C;
213 // Form "A op' (B op DD)" if it simplifies completely.
214 // Does "B op DD" simplify?
215 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
216 // It does! Return "A op' V" if it simplifies or is already available.
217 // If V equals B then "A op' V" is just the LHS. If V equals DD then
218 // "A op' V" is just the RHS.
219 if (V == B || V == DD) {
221 return V == B ? LHS : RHS;
223 // Otherwise return "A op' V" if it simplifies.
224 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
231 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
232 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
233 // commutative case, "(A op' B) op (B op' D)"?
234 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
235 Value *CC = B == D ? C : D;
236 // Form "(A op CC) op' B" if it simplifies completely..
237 // Does "A op CC" simplify?
238 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
239 // It does! Return "V op' B" if it simplifies or is already available.
240 // If V equals A then "V op' B" is just the LHS. If V equals CC then
241 // "V op' B" is just the RHS.
242 if (V == A || V == CC) {
244 return V == A ? LHS : RHS;
246 // Otherwise return "V op' B" if it simplifies.
247 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
257 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
258 /// operations. Returns the simpler value, or null if none was found.
259 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
260 const Query &Q, unsigned MaxRecurse) {
261 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
262 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
264 // Recursion is always used, so bail out at once if we already hit the limit.
268 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
269 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
271 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
272 if (Op0 && Op0->getOpcode() == Opcode) {
273 Value *A = Op0->getOperand(0);
274 Value *B = Op0->getOperand(1);
277 // Does "B op C" simplify?
278 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
279 // It does! Return "A op V" if it simplifies or is already available.
280 // If V equals B then "A op V" is just the LHS.
281 if (V == B) return LHS;
282 // Otherwise return "A op V" if it simplifies.
283 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
290 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
291 if (Op1 && Op1->getOpcode() == Opcode) {
293 Value *B = Op1->getOperand(0);
294 Value *C = Op1->getOperand(1);
296 // Does "A op B" simplify?
297 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
298 // It does! Return "V op C" if it simplifies or is already available.
299 // If V equals B then "V op C" is just the RHS.
300 if (V == B) return RHS;
301 // Otherwise return "V op C" if it simplifies.
302 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
309 // The remaining transforms require commutativity as well as associativity.
310 if (!Instruction::isCommutative(Opcode))
313 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
314 if (Op0 && Op0->getOpcode() == Opcode) {
315 Value *A = Op0->getOperand(0);
316 Value *B = Op0->getOperand(1);
319 // Does "C op A" simplify?
320 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
321 // It does! Return "V op B" if it simplifies or is already available.
322 // If V equals A then "V op B" is just the LHS.
323 if (V == A) return LHS;
324 // Otherwise return "V op B" if it simplifies.
325 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
332 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
333 if (Op1 && Op1->getOpcode() == Opcode) {
335 Value *B = Op1->getOperand(0);
336 Value *C = Op1->getOperand(1);
338 // Does "C op A" simplify?
339 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
340 // It does! Return "B op V" if it simplifies or is already available.
341 // If V equals C then "B op V" is just the RHS.
342 if (V == C) return RHS;
343 // Otherwise return "B op V" if it simplifies.
344 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
354 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
355 /// instruction as an operand, try to simplify the binop by seeing whether
356 /// evaluating it on both branches of the select results in the same value.
357 /// Returns the common value if so, otherwise returns null.
358 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
359 const Query &Q, unsigned MaxRecurse) {
360 // Recursion is always used, so bail out at once if we already hit the limit.
365 if (isa<SelectInst>(LHS)) {
366 SI = cast<SelectInst>(LHS);
368 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369 SI = cast<SelectInst>(RHS);
372 // Evaluate the BinOp on the true and false branches of the select.
376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
383 // If they simplified to the same value, then return the common value.
384 // If they both failed to simplify then return null.
388 // If one branch simplified to undef, return the other one.
389 if (TV && isa<UndefValue>(TV))
391 if (FV && isa<UndefValue>(FV))
394 // If applying the operation did not change the true and false select values,
395 // then the result of the binop is the select itself.
396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
399 // If one branch simplified and the other did not, and the simplified
400 // value is equal to the unsimplified one, return the simplified value.
401 // For example, select (cond, X, X & Z) & Z -> X & Z.
402 if ((FV && !TV) || (TV && !FV)) {
403 // Check that the simplified value has the form "X op Y" where "op" is the
404 // same as the original operation.
405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406 if (Simplified && Simplified->getOpcode() == Opcode) {
407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408 // We already know that "op" is the same as for the simplified value. See
409 // if the operands match too. If so, return the simplified value.
410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
413 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414 Simplified->getOperand(1) == UnsimplifiedRHS)
416 if (Simplified->isCommutative() &&
417 Simplified->getOperand(1) == UnsimplifiedLHS &&
418 Simplified->getOperand(0) == UnsimplifiedRHS)
426 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427 /// try to simplify the comparison by seeing whether both branches of the select
428 /// result in the same value. Returns the common value if so, otherwise returns
430 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
431 Value *RHS, const Query &Q,
432 unsigned MaxRecurse) {
433 // Recursion is always used, so bail out at once if we already hit the limit.
437 // Make sure the select is on the LHS.
438 if (!isa<SelectInst>(LHS)) {
440 Pred = CmpInst::getSwappedPredicate(Pred);
442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443 SelectInst *SI = cast<SelectInst>(LHS);
444 Value *Cond = SI->getCondition();
445 Value *TV = SI->getTrueValue();
446 Value *FV = SI->getFalseValue();
448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
449 // Does "cmp TV, RHS" simplify?
450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
452 // It not only simplified, it simplified to the select condition. Replace
454 TCmp = getTrue(Cond->getType());
456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
457 // condition then we can replace it with 'true'. Otherwise give up.
458 if (!isSameCompare(Cond, Pred, TV, RHS))
460 TCmp = getTrue(Cond->getType());
463 // Does "cmp FV, RHS" simplify?
464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
466 // It not only simplified, it simplified to the select condition. Replace
468 FCmp = getFalse(Cond->getType());
470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
471 // condition then we can replace it with 'false'. Otherwise give up.
472 if (!isSameCompare(Cond, Pred, FV, RHS))
474 FCmp = getFalse(Cond->getType());
477 // If both sides simplified to the same value, then use it as the result of
478 // the original comparison.
482 // The remaining cases only make sense if the select condition has the same
483 // type as the result of the comparison, so bail out if this is not so.
484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
486 // If the false value simplified to false, then the result of the compare
487 // is equal to "Cond && TCmp". This also catches the case when the false
488 // value simplified to false and the true value to true, returning "Cond".
489 if (match(FCmp, m_Zero()))
490 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
492 // If the true value simplified to true, then the result of the compare
493 // is equal to "Cond || FCmp".
494 if (match(TCmp, m_One()))
495 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
497 // Finally, if the false value simplified to true and the true value to
498 // false, then the result of the compare is equal to "!Cond".
499 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
508 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510 /// it on the incoming phi values yields the same result for every value. If so
511 /// returns the common value, otherwise returns null.
512 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
513 const Query &Q, unsigned MaxRecurse) {
514 // Recursion is always used, so bail out at once if we already hit the limit.
519 if (isa<PHINode>(LHS)) {
520 PI = cast<PHINode>(LHS);
521 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
522 if (!ValueDominatesPHI(RHS, PI, Q.DT))
525 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
526 PI = cast<PHINode>(RHS);
527 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
528 if (!ValueDominatesPHI(LHS, PI, Q.DT))
532 // Evaluate the BinOp on the incoming phi values.
533 Value *CommonValue = 0;
534 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
535 Value *Incoming = PI->getIncomingValue(i);
536 // If the incoming value is the phi node itself, it can safely be skipped.
537 if (Incoming == PI) continue;
538 Value *V = PI == LHS ?
539 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
540 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
541 // If the operation failed to simplify, or simplified to a different value
542 // to previously, then give up.
543 if (!V || (CommonValue && V != CommonValue))
551 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
552 /// try to simplify the comparison by seeing whether comparing with all of the
553 /// incoming phi values yields the same result every time. If so returns the
554 /// common result, otherwise returns null.
555 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
556 const Query &Q, unsigned MaxRecurse) {
557 // Recursion is always used, so bail out at once if we already hit the limit.
561 // Make sure the phi is on the LHS.
562 if (!isa<PHINode>(LHS)) {
564 Pred = CmpInst::getSwappedPredicate(Pred);
566 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
567 PHINode *PI = cast<PHINode>(LHS);
569 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
570 if (!ValueDominatesPHI(RHS, PI, Q.DT))
573 // Evaluate the BinOp on the incoming phi values.
574 Value *CommonValue = 0;
575 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
576 Value *Incoming = PI->getIncomingValue(i);
577 // If the incoming value is the phi node itself, it can safely be skipped.
578 if (Incoming == PI) continue;
579 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
580 // If the operation failed to simplify, or simplified to a different value
581 // to previously, then give up.
582 if (!V || (CommonValue && V != CommonValue))
590 /// SimplifyAddInst - Given operands for an Add, see if we can
591 /// fold the result. If not, this returns null.
592 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
593 const Query &Q, unsigned MaxRecurse) {
594 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596 Constant *Ops[] = { CLHS, CRHS };
597 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
601 // Canonicalize the constant to the RHS.
605 // X + undef -> undef
606 if (match(Op1, m_Undef()))
610 if (match(Op1, m_Zero()))
617 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
618 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
621 // X + ~X -> -1 since ~X = -X-1
622 if (match(Op0, m_Not(m_Specific(Op1))) ||
623 match(Op1, m_Not(m_Specific(Op0))))
624 return Constant::getAllOnesValue(Op0->getType());
627 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
628 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
631 // Try some generic simplifications for associative operations.
632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
636 // Mul distributes over Add. Try some generic simplifications based on this.
637 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
641 // Threading Add over selects and phi nodes is pointless, so don't bother.
642 // Threading over the select in "A + select(cond, B, C)" means evaluating
643 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
644 // only if B and C are equal. If B and C are equal then (since we assume
645 // that operands have already been simplified) "select(cond, B, C)" should
646 // have been simplified to the common value of B and C already. Analysing
647 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
648 // for threading over phi nodes.
653 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
654 const DataLayout *DL, const TargetLibraryInfo *TLI,
655 const DominatorTree *DT) {
656 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
660 /// \brief Compute the base pointer and cumulative constant offsets for V.
662 /// This strips all constant offsets off of V, leaving it the base pointer, and
663 /// accumulates the total constant offset applied in the returned constant. It
664 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
665 /// no constant offsets applied.
667 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
668 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
670 static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
672 bool AllowNonInbounds = false) {
673 assert(V->getType()->getScalarType()->isPointerTy());
675 // Without DataLayout, just be conservative for now. Theoretically, more could
676 // be done in this case.
678 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
680 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
681 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
683 // Even though we don't look through PHI nodes, we could be called on an
684 // instruction in an unreachable block, which may be on a cycle.
685 SmallPtrSet<Value *, 4> Visited;
688 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
689 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
690 !GEP->accumulateConstantOffset(*DL, Offset))
692 V = GEP->getPointerOperand();
693 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
694 V = cast<Operator>(V)->getOperand(0);
695 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
696 if (GA->mayBeOverridden())
698 V = GA->getAliasee();
702 assert(V->getType()->getScalarType()->isPointerTy() &&
703 "Unexpected operand type!");
704 } while (Visited.insert(V));
706 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
707 if (V->getType()->isVectorTy())
708 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
713 /// \brief Compute the constant difference between two pointer values.
714 /// If the difference is not a constant, returns zero.
715 static Constant *computePointerDifference(const DataLayout *DL,
716 Value *LHS, Value *RHS) {
717 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
718 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
720 // If LHS and RHS are not related via constant offsets to the same base
721 // value, there is nothing we can do here.
725 // Otherwise, the difference of LHS - RHS can be computed as:
727 // = (LHSOffset + Base) - (RHSOffset + Base)
728 // = LHSOffset - RHSOffset
729 return ConstantExpr::getSub(LHSOffset, RHSOffset);
732 /// SimplifySubInst - Given operands for a Sub, see if we can
733 /// fold the result. If not, this returns null.
734 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
735 const Query &Q, unsigned MaxRecurse) {
736 if (Constant *CLHS = dyn_cast<Constant>(Op0))
737 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
738 Constant *Ops[] = { CLHS, CRHS };
739 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
743 // X - undef -> undef
744 // undef - X -> undef
745 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
746 return UndefValue::get(Op0->getType());
749 if (match(Op1, m_Zero()))
754 return Constant::getNullValue(Op0->getType());
759 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
760 match(Op0, m_Shl(m_Specific(Op1), m_One())))
763 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
764 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
765 Value *Y = 0, *Z = Op1;
766 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
767 // See if "V === Y - Z" simplifies.
768 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
769 // It does! Now see if "X + V" simplifies.
770 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
771 // It does, we successfully reassociated!
775 // See if "V === X - Z" simplifies.
776 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
777 // It does! Now see if "Y + V" simplifies.
778 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
779 // It does, we successfully reassociated!
785 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
786 // For example, X - (X + 1) -> -1
788 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
789 // See if "V === X - Y" simplifies.
790 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
791 // It does! Now see if "V - Z" simplifies.
792 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
793 // It does, we successfully reassociated!
797 // See if "V === X - Z" simplifies.
798 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
799 // It does! Now see if "V - Y" simplifies.
800 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
801 // It does, we successfully reassociated!
807 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
808 // For example, X - (X - Y) -> Y.
810 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
811 // See if "V === Z - X" simplifies.
812 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
813 // It does! Now see if "V + Y" simplifies.
814 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
815 // It does, we successfully reassociated!
820 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
821 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
822 match(Op1, m_Trunc(m_Value(Y))))
823 if (X->getType() == Y->getType())
824 // See if "V === X - Y" simplifies.
825 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
826 // It does! Now see if "trunc V" simplifies.
827 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
828 // It does, return the simplified "trunc V".
831 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
832 if (match(Op0, m_PtrToInt(m_Value(X))) &&
833 match(Op1, m_PtrToInt(m_Value(Y))))
834 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
835 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
837 // Mul distributes over Sub. Try some generic simplifications based on this.
838 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
843 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
844 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
847 // Threading Sub over selects and phi nodes is pointless, so don't bother.
848 // Threading over the select in "A - select(cond, B, C)" means evaluating
849 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
850 // only if B and C are equal. If B and C are equal then (since we assume
851 // that operands have already been simplified) "select(cond, B, C)" should
852 // have been simplified to the common value of B and C already. Analysing
853 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
854 // for threading over phi nodes.
859 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
860 const DataLayout *DL, const TargetLibraryInfo *TLI,
861 const DominatorTree *DT) {
862 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
866 /// Given operands for an FAdd, see if we can fold the result. If not, this
868 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
869 const Query &Q, unsigned MaxRecurse) {
870 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
871 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
872 Constant *Ops[] = { CLHS, CRHS };
873 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
877 // Canonicalize the constant to the RHS.
882 if (match(Op1, m_NegZero()))
885 // fadd X, 0 ==> X, when we know X is not -0
886 if (match(Op1, m_Zero()) &&
887 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
890 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
891 // where nnan and ninf have to occur at least once somewhere in this
894 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
896 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
899 Instruction *FSub = cast<Instruction>(SubOp);
900 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
901 (FMF.noInfs() || FSub->hasNoInfs()))
902 return Constant::getNullValue(Op0->getType());
908 /// Given operands for an FSub, see if we can fold the result. If not, this
910 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
911 const Query &Q, unsigned MaxRecurse) {
912 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
913 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
914 Constant *Ops[] = { CLHS, CRHS };
915 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
921 if (match(Op1, m_Zero()))
924 // fsub X, -0 ==> X, when we know X is not -0
925 if (match(Op1, m_NegZero()) &&
926 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
929 // fsub 0, (fsub -0.0, X) ==> X
931 if (match(Op0, m_AnyZero())) {
932 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
934 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
938 // fsub nnan ninf x, x ==> 0.0
939 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
940 return Constant::getNullValue(Op0->getType());
945 /// Given the operands for an FMul, see if we can fold the result
946 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
949 unsigned MaxRecurse) {
950 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
951 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
952 Constant *Ops[] = { CLHS, CRHS };
953 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
957 // Canonicalize the constant to the RHS.
962 if (match(Op1, m_FPOne()))
965 // fmul nnan nsz X, 0 ==> 0
966 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
972 /// SimplifyMulInst - Given operands for a Mul, see if we can
973 /// fold the result. If not, this returns null.
974 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
975 unsigned MaxRecurse) {
976 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
977 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
978 Constant *Ops[] = { CLHS, CRHS };
979 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
983 // Canonicalize the constant to the RHS.
988 if (match(Op1, m_Undef()))
989 return Constant::getNullValue(Op0->getType());
992 if (match(Op1, m_Zero()))
996 if (match(Op1, m_One()))
999 // (X / Y) * Y -> X if the division is exact.
1001 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
1002 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
1006 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
1007 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
1010 // Try some generic simplifications for associative operations.
1011 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
1015 // Mul distributes over Add. Try some generic simplifications based on this.
1016 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
1020 // If the operation is with the result of a select instruction, check whether
1021 // operating on either branch of the select always yields the same value.
1022 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1023 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
1027 // If the operation is with the result of a phi instruction, check whether
1028 // operating on all incoming values of the phi always yields the same value.
1029 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1030 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
1037 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1038 const DataLayout *DL, const TargetLibraryInfo *TLI,
1039 const DominatorTree *DT) {
1040 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
1043 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1044 const DataLayout *DL, const TargetLibraryInfo *TLI,
1045 const DominatorTree *DT) {
1046 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
1049 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1051 const DataLayout *DL,
1052 const TargetLibraryInfo *TLI,
1053 const DominatorTree *DT) {
1054 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
1057 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
1058 const TargetLibraryInfo *TLI,
1059 const DominatorTree *DT) {
1060 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1063 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1064 /// fold the result. If not, this returns null.
1065 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1066 const Query &Q, unsigned MaxRecurse) {
1067 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1068 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1069 Constant *Ops[] = { C0, C1 };
1070 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1074 bool isSigned = Opcode == Instruction::SDiv;
1076 // X / undef -> undef
1077 if (match(Op1, m_Undef()))
1081 if (match(Op0, m_Undef()))
1082 return Constant::getNullValue(Op0->getType());
1084 // 0 / X -> 0, we don't need to preserve faults!
1085 if (match(Op0, m_Zero()))
1089 if (match(Op1, m_One()))
1092 if (Op0->getType()->isIntegerTy(1))
1093 // It can't be division by zero, hence it must be division by one.
1098 return ConstantInt::get(Op0->getType(), 1);
1100 // (X * Y) / Y -> X if the multiplication does not overflow.
1101 Value *X = 0, *Y = 0;
1102 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1103 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1104 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1105 // If the Mul knows it does not overflow, then we are good to go.
1106 if ((isSigned && Mul->hasNoSignedWrap()) ||
1107 (!isSigned && Mul->hasNoUnsignedWrap()))
1109 // If X has the form X = A / Y then X * Y cannot overflow.
1110 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1111 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1115 // (X rem Y) / Y -> 0
1116 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1117 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1118 return Constant::getNullValue(Op0->getType());
1120 // If the operation is with the result of a select instruction, check whether
1121 // operating on either branch of the select always yields the same value.
1122 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1123 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1126 // If the operation is with the result of a phi instruction, check whether
1127 // operating on all incoming values of the phi always yields the same value.
1128 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1129 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1135 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1136 /// fold the result. If not, this returns null.
1137 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1138 unsigned MaxRecurse) {
1139 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1145 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1146 const TargetLibraryInfo *TLI,
1147 const DominatorTree *DT) {
1148 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1151 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1152 /// fold the result. If not, this returns null.
1153 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1154 unsigned MaxRecurse) {
1155 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1161 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1162 const TargetLibraryInfo *TLI,
1163 const DominatorTree *DT) {
1164 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1167 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1169 // undef / X -> undef (the undef could be a snan).
1170 if (match(Op0, m_Undef()))
1173 // X / undef -> undef
1174 if (match(Op1, m_Undef()))
1180 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1181 const TargetLibraryInfo *TLI,
1182 const DominatorTree *DT) {
1183 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1186 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1187 /// fold the result. If not, this returns null.
1188 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1189 const Query &Q, unsigned MaxRecurse) {
1190 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1191 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1192 Constant *Ops[] = { C0, C1 };
1193 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1197 // X % undef -> undef
1198 if (match(Op1, m_Undef()))
1202 if (match(Op0, m_Undef()))
1203 return Constant::getNullValue(Op0->getType());
1205 // 0 % X -> 0, we don't need to preserve faults!
1206 if (match(Op0, m_Zero()))
1209 // X % 0 -> undef, we don't need to preserve faults!
1210 if (match(Op1, m_Zero()))
1211 return UndefValue::get(Op0->getType());
1214 if (match(Op1, m_One()))
1215 return Constant::getNullValue(Op0->getType());
1217 if (Op0->getType()->isIntegerTy(1))
1218 // It can't be remainder by zero, hence it must be remainder by one.
1219 return Constant::getNullValue(Op0->getType());
1223 return Constant::getNullValue(Op0->getType());
1225 // If the operation is with the result of a select instruction, check whether
1226 // operating on either branch of the select always yields the same value.
1227 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1228 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1231 // If the operation is with the result of a phi instruction, check whether
1232 // operating on all incoming values of the phi always yields the same value.
1233 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1234 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1240 /// SimplifySRemInst - Given operands for an SRem, see if we can
1241 /// fold the result. If not, this returns null.
1242 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1243 unsigned MaxRecurse) {
1244 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1250 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1251 const TargetLibraryInfo *TLI,
1252 const DominatorTree *DT) {
1253 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1256 /// SimplifyURemInst - Given operands for a URem, see if we can
1257 /// fold the result. If not, this returns null.
1258 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1259 unsigned MaxRecurse) {
1260 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1266 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1267 const TargetLibraryInfo *TLI,
1268 const DominatorTree *DT) {
1269 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1272 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1274 // undef % X -> undef (the undef could be a snan).
1275 if (match(Op0, m_Undef()))
1278 // X % undef -> undef
1279 if (match(Op1, m_Undef()))
1285 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1286 const TargetLibraryInfo *TLI,
1287 const DominatorTree *DT) {
1288 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1291 /// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1292 static bool isUndefShift(Value *Amount) {
1293 Constant *C = dyn_cast<Constant>(Amount);
1297 // X shift by undef -> undef because it may shift by the bitwidth.
1298 if (isa<UndefValue>(C))
1301 // Shifting by the bitwidth or more is undefined.
1302 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1303 if (CI->getValue().getLimitedValue() >=
1304 CI->getType()->getScalarSizeInBits())
1307 // If all lanes of a vector shift are undefined the whole shift is.
1308 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1309 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1310 if (!isUndefShift(C->getAggregateElement(I)))
1318 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1319 /// fold the result. If not, this returns null.
1320 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1321 const Query &Q, unsigned MaxRecurse) {
1322 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1323 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1324 Constant *Ops[] = { C0, C1 };
1325 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1329 // 0 shift by X -> 0
1330 if (match(Op0, m_Zero()))
1333 // X shift by 0 -> X
1334 if (match(Op1, m_Zero()))
1337 // Fold undefined shifts.
1338 if (isUndefShift(Op1))
1339 return UndefValue::get(Op0->getType());
1341 // If the operation is with the result of a select instruction, check whether
1342 // operating on either branch of the select always yields the same value.
1343 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1344 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1347 // If the operation is with the result of a phi instruction, check whether
1348 // operating on all incoming values of the phi always yields the same value.
1349 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1350 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1356 /// SimplifyShlInst - Given operands for an Shl, see if we can
1357 /// fold the result. If not, this returns null.
1358 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1359 const Query &Q, unsigned MaxRecurse) {
1360 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1364 if (match(Op0, m_Undef()))
1365 return Constant::getNullValue(Op0->getType());
1367 // (X >> A) << A -> X
1369 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1374 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1375 const DataLayout *DL, const TargetLibraryInfo *TLI,
1376 const DominatorTree *DT) {
1377 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
1381 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1382 /// fold the result. If not, this returns null.
1383 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1384 const Query &Q, unsigned MaxRecurse) {
1385 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1390 return Constant::getNullValue(Op0->getType());
1393 if (match(Op0, m_Undef()))
1394 return Constant::getNullValue(Op0->getType());
1396 // (X << A) >> A -> X
1398 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1399 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1405 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1406 const DataLayout *DL,
1407 const TargetLibraryInfo *TLI,
1408 const DominatorTree *DT) {
1409 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
1413 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1414 /// fold the result. If not, this returns null.
1415 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1416 const Query &Q, unsigned MaxRecurse) {
1417 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1422 return Constant::getNullValue(Op0->getType());
1424 // all ones >>a X -> all ones
1425 if (match(Op0, m_AllOnes()))
1428 // undef >>a X -> all ones
1429 if (match(Op0, m_Undef()))
1430 return Constant::getAllOnesValue(Op0->getType());
1432 // (X << A) >> A -> X
1434 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1435 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1441 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1442 const DataLayout *DL,
1443 const TargetLibraryInfo *TLI,
1444 const DominatorTree *DT) {
1445 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
1449 /// SimplifyAndInst - Given operands for an And, see if we can
1450 /// fold the result. If not, this returns null.
1451 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1452 unsigned MaxRecurse) {
1453 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1454 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1455 Constant *Ops[] = { CLHS, CRHS };
1456 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1460 // Canonicalize the constant to the RHS.
1461 std::swap(Op0, Op1);
1465 if (match(Op1, m_Undef()))
1466 return Constant::getNullValue(Op0->getType());
1473 if (match(Op1, m_Zero()))
1477 if (match(Op1, m_AllOnes()))
1480 // A & ~A = ~A & A = 0
1481 if (match(Op0, m_Not(m_Specific(Op1))) ||
1482 match(Op1, m_Not(m_Specific(Op0))))
1483 return Constant::getNullValue(Op0->getType());
1486 Value *A = 0, *B = 0;
1487 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1488 (A == Op1 || B == Op1))
1492 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1493 (A == Op0 || B == Op0))
1496 // A & (-A) = A if A is a power of two or zero.
1497 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1498 match(Op1, m_Neg(m_Specific(Op0)))) {
1499 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
1501 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
1505 // Try some generic simplifications for associative operations.
1506 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1510 // And distributes over Or. Try some generic simplifications based on this.
1511 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1515 // And distributes over Xor. Try some generic simplifications based on this.
1516 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1520 // Or distributes over And. Try some generic simplifications based on this.
1521 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1525 // If the operation is with the result of a select instruction, check whether
1526 // operating on either branch of the select always yields the same value.
1527 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1528 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1532 // If the operation is with the result of a phi instruction, check whether
1533 // operating on all incoming values of the phi always yields the same value.
1534 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1535 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1542 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
1543 const TargetLibraryInfo *TLI,
1544 const DominatorTree *DT) {
1545 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1548 /// SimplifyOrInst - Given operands for an Or, see if we can
1549 /// fold the result. If not, this returns null.
1550 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1551 unsigned MaxRecurse) {
1552 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1553 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1554 Constant *Ops[] = { CLHS, CRHS };
1555 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1559 // Canonicalize the constant to the RHS.
1560 std::swap(Op0, Op1);
1564 if (match(Op1, m_Undef()))
1565 return Constant::getAllOnesValue(Op0->getType());
1572 if (match(Op1, m_Zero()))
1576 if (match(Op1, m_AllOnes()))
1579 // A | ~A = ~A | A = -1
1580 if (match(Op0, m_Not(m_Specific(Op1))) ||
1581 match(Op1, m_Not(m_Specific(Op0))))
1582 return Constant::getAllOnesValue(Op0->getType());
1585 Value *A = 0, *B = 0;
1586 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1587 (A == Op1 || B == Op1))
1591 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1592 (A == Op0 || B == Op0))
1595 // ~(A & ?) | A = -1
1596 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1597 (A == Op1 || B == Op1))
1598 return Constant::getAllOnesValue(Op1->getType());
1600 // A | ~(A & ?) = -1
1601 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1602 (A == Op0 || B == Op0))
1603 return Constant::getAllOnesValue(Op0->getType());
1605 // Try some generic simplifications for associative operations.
1606 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1610 // Or distributes over And. Try some generic simplifications based on this.
1611 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1615 // And distributes over Or. Try some generic simplifications based on this.
1616 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1620 // If the operation is with the result of a select instruction, check whether
1621 // operating on either branch of the select always yields the same value.
1622 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1623 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1627 // If the operation is with the result of a phi instruction, check whether
1628 // operating on all incoming values of the phi always yields the same value.
1629 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1630 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1636 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
1637 const TargetLibraryInfo *TLI,
1638 const DominatorTree *DT) {
1639 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1642 /// SimplifyXorInst - Given operands for a Xor, see if we can
1643 /// fold the result. If not, this returns null.
1644 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1645 unsigned MaxRecurse) {
1646 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1647 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1648 Constant *Ops[] = { CLHS, CRHS };
1649 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1653 // Canonicalize the constant to the RHS.
1654 std::swap(Op0, Op1);
1657 // A ^ undef -> undef
1658 if (match(Op1, m_Undef()))
1662 if (match(Op1, m_Zero()))
1667 return Constant::getNullValue(Op0->getType());
1669 // A ^ ~A = ~A ^ A = -1
1670 if (match(Op0, m_Not(m_Specific(Op1))) ||
1671 match(Op1, m_Not(m_Specific(Op0))))
1672 return Constant::getAllOnesValue(Op0->getType());
1674 // Try some generic simplifications for associative operations.
1675 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1679 // And distributes over Xor. Try some generic simplifications based on this.
1680 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1684 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1685 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1686 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1687 // only if B and C are equal. If B and C are equal then (since we assume
1688 // that operands have already been simplified) "select(cond, B, C)" should
1689 // have been simplified to the common value of B and C already. Analysing
1690 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1691 // for threading over phi nodes.
1696 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
1697 const TargetLibraryInfo *TLI,
1698 const DominatorTree *DT) {
1699 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1702 static Type *GetCompareTy(Value *Op) {
1703 return CmpInst::makeCmpResultType(Op->getType());
1706 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1707 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1708 /// otherwise return null. Helper function for analyzing max/min idioms.
1709 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1710 Value *LHS, Value *RHS) {
1711 SelectInst *SI = dyn_cast<SelectInst>(V);
1714 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1717 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1718 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1720 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1721 LHS == CmpRHS && RHS == CmpLHS)
1726 // A significant optimization not implemented here is assuming that alloca
1727 // addresses are not equal to incoming argument values. They don't *alias*,
1728 // as we say, but that doesn't mean they aren't equal, so we take a
1729 // conservative approach.
1731 // This is inspired in part by C++11 5.10p1:
1732 // "Two pointers of the same type compare equal if and only if they are both
1733 // null, both point to the same function, or both represent the same
1736 // This is pretty permissive.
1738 // It's also partly due to C11 6.5.9p6:
1739 // "Two pointers compare equal if and only if both are null pointers, both are
1740 // pointers to the same object (including a pointer to an object and a
1741 // subobject at its beginning) or function, both are pointers to one past the
1742 // last element of the same array object, or one is a pointer to one past the
1743 // end of one array object and the other is a pointer to the start of a
1744 // different array object that happens to immediately follow the first array
1745 // object in the address space.)
1747 // C11's version is more restrictive, however there's no reason why an argument
1748 // couldn't be a one-past-the-end value for a stack object in the caller and be
1749 // equal to the beginning of a stack object in the callee.
1751 // If the C and C++ standards are ever made sufficiently restrictive in this
1752 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1753 // this optimization.
1754 static Constant *computePointerICmp(const DataLayout *DL,
1755 const TargetLibraryInfo *TLI,
1756 CmpInst::Predicate Pred,
1757 Value *LHS, Value *RHS) {
1758 // First, skip past any trivial no-ops.
1759 LHS = LHS->stripPointerCasts();
1760 RHS = RHS->stripPointerCasts();
1762 // A non-null pointer is not equal to a null pointer.
1763 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1764 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1765 return ConstantInt::get(GetCompareTy(LHS),
1766 !CmpInst::isTrueWhenEqual(Pred));
1768 // We can only fold certain predicates on pointer comparisons.
1773 // Equality comaprisons are easy to fold.
1774 case CmpInst::ICMP_EQ:
1775 case CmpInst::ICMP_NE:
1778 // We can only handle unsigned relational comparisons because 'inbounds' on
1779 // a GEP only protects against unsigned wrapping.
1780 case CmpInst::ICMP_UGT:
1781 case CmpInst::ICMP_UGE:
1782 case CmpInst::ICMP_ULT:
1783 case CmpInst::ICMP_ULE:
1784 // However, we have to switch them to their signed variants to handle
1785 // negative indices from the base pointer.
1786 Pred = ICmpInst::getSignedPredicate(Pred);
1790 // Strip off any constant offsets so that we can reason about them.
1791 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1792 // here and compare base addresses like AliasAnalysis does, however there are
1793 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1794 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1795 // doesn't need to guarantee pointer inequality when it says NoAlias.
1796 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1797 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
1799 // If LHS and RHS are related via constant offsets to the same base
1800 // value, we can replace it with an icmp which just compares the offsets.
1802 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1804 // Various optimizations for (in)equality comparisons.
1805 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1806 // Different non-empty allocations that exist at the same time have
1807 // different addresses (if the program can tell). Global variables always
1808 // exist, so they always exist during the lifetime of each other and all
1809 // allocas. Two different allocas usually have different addresses...
1811 // However, if there's an @llvm.stackrestore dynamically in between two
1812 // allocas, they may have the same address. It's tempting to reduce the
1813 // scope of the problem by only looking at *static* allocas here. That would
1814 // cover the majority of allocas while significantly reducing the likelihood
1815 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1816 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1817 // an entry block. Also, if we have a block that's not attached to a
1818 // function, we can't tell if it's "static" under the current definition.
1819 // Theoretically, this problem could be fixed by creating a new kind of
1820 // instruction kind specifically for static allocas. Such a new instruction
1821 // could be required to be at the top of the entry block, thus preventing it
1822 // from being subject to a @llvm.stackrestore. Instcombine could even
1823 // convert regular allocas into these special allocas. It'd be nifty.
1824 // However, until then, this problem remains open.
1826 // So, we'll assume that two non-empty allocas have different addresses
1829 // With all that, if the offsets are within the bounds of their allocations
1830 // (and not one-past-the-end! so we can't use inbounds!), and their
1831 // allocations aren't the same, the pointers are not equal.
1833 // Note that it's not necessary to check for LHS being a global variable
1834 // address, due to canonicalization and constant folding.
1835 if (isa<AllocaInst>(LHS) &&
1836 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
1837 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1838 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
1839 uint64_t LHSSize, RHSSize;
1840 if (LHSOffsetCI && RHSOffsetCI &&
1841 getObjectSize(LHS, LHSSize, DL, TLI) &&
1842 getObjectSize(RHS, RHSSize, DL, TLI)) {
1843 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1844 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
1845 if (!LHSOffsetValue.isNegative() &&
1846 !RHSOffsetValue.isNegative() &&
1847 LHSOffsetValue.ult(LHSSize) &&
1848 RHSOffsetValue.ult(RHSSize)) {
1849 return ConstantInt::get(GetCompareTy(LHS),
1850 !CmpInst::isTrueWhenEqual(Pred));
1854 // Repeat the above check but this time without depending on DataLayout
1855 // or being able to compute a precise size.
1856 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1857 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1858 LHSOffset->isNullValue() &&
1859 RHSOffset->isNullValue())
1860 return ConstantInt::get(GetCompareTy(LHS),
1861 !CmpInst::isTrueWhenEqual(Pred));
1864 // Even if an non-inbounds GEP occurs along the path we can still optimize
1865 // equality comparisons concerning the result. We avoid walking the whole
1866 // chain again by starting where the last calls to
1867 // stripAndComputeConstantOffsets left off and accumulate the offsets.
1868 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1869 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
1871 return ConstantExpr::getICmp(Pred,
1872 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1873 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
1880 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1881 /// fold the result. If not, this returns null.
1882 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1883 const Query &Q, unsigned MaxRecurse) {
1884 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1885 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1887 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1888 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1889 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
1891 // If we have a constant, make sure it is on the RHS.
1892 std::swap(LHS, RHS);
1893 Pred = CmpInst::getSwappedPredicate(Pred);
1896 Type *ITy = GetCompareTy(LHS); // The return type.
1897 Type *OpTy = LHS->getType(); // The operand type.
1899 // icmp X, X -> true/false
1900 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1901 // because X could be 0.
1902 if (LHS == RHS || isa<UndefValue>(RHS))
1903 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1905 // Special case logic when the operands have i1 type.
1906 if (OpTy->getScalarType()->isIntegerTy(1)) {
1909 case ICmpInst::ICMP_EQ:
1911 if (match(RHS, m_One()))
1914 case ICmpInst::ICMP_NE:
1916 if (match(RHS, m_Zero()))
1919 case ICmpInst::ICMP_UGT:
1921 if (match(RHS, m_Zero()))
1924 case ICmpInst::ICMP_UGE:
1926 if (match(RHS, m_One()))
1929 case ICmpInst::ICMP_SLT:
1931 if (match(RHS, m_Zero()))
1934 case ICmpInst::ICMP_SLE:
1936 if (match(RHS, m_One()))
1942 // If we are comparing with zero then try hard since this is a common case.
1943 if (match(RHS, m_Zero())) {
1944 bool LHSKnownNonNegative, LHSKnownNegative;
1946 default: llvm_unreachable("Unknown ICmp predicate!");
1947 case ICmpInst::ICMP_ULT:
1948 return getFalse(ITy);
1949 case ICmpInst::ICMP_UGE:
1950 return getTrue(ITy);
1951 case ICmpInst::ICMP_EQ:
1952 case ICmpInst::ICMP_ULE:
1953 if (isKnownNonZero(LHS, Q.DL))
1954 return getFalse(ITy);
1956 case ICmpInst::ICMP_NE:
1957 case ICmpInst::ICMP_UGT:
1958 if (isKnownNonZero(LHS, Q.DL))
1959 return getTrue(ITy);
1961 case ICmpInst::ICMP_SLT:
1962 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1963 if (LHSKnownNegative)
1964 return getTrue(ITy);
1965 if (LHSKnownNonNegative)
1966 return getFalse(ITy);
1968 case ICmpInst::ICMP_SLE:
1969 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1970 if (LHSKnownNegative)
1971 return getTrue(ITy);
1972 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
1973 return getFalse(ITy);
1975 case ICmpInst::ICMP_SGE:
1976 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1977 if (LHSKnownNegative)
1978 return getFalse(ITy);
1979 if (LHSKnownNonNegative)
1980 return getTrue(ITy);
1982 case ICmpInst::ICMP_SGT:
1983 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1984 if (LHSKnownNegative)
1985 return getFalse(ITy);
1986 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
1987 return getTrue(ITy);
1992 // See if we are doing a comparison with a constant integer.
1993 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1994 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1995 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1996 if (RHS_CR.isEmptySet())
1997 return ConstantInt::getFalse(CI->getContext());
1998 if (RHS_CR.isFullSet())
1999 return ConstantInt::getTrue(CI->getContext());
2001 // Many binary operators with constant RHS have easy to compute constant
2002 // range. Use them to check whether the comparison is a tautology.
2003 uint32_t Width = CI->getBitWidth();
2004 APInt Lower = APInt(Width, 0);
2005 APInt Upper = APInt(Width, 0);
2007 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2008 // 'urem x, CI2' produces [0, CI2).
2009 Upper = CI2->getValue();
2010 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2011 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2012 Upper = CI2->getValue().abs();
2013 Lower = (-Upper) + 1;
2014 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2015 // 'udiv CI2, x' produces [0, CI2].
2016 Upper = CI2->getValue() + 1;
2017 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2018 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2019 APInt NegOne = APInt::getAllOnesValue(Width);
2021 Upper = NegOne.udiv(CI2->getValue()) + 1;
2022 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2023 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
2024 APInt IntMin = APInt::getSignedMinValue(Width);
2025 APInt IntMax = APInt::getSignedMaxValue(Width);
2026 APInt Val = CI2->getValue().abs();
2027 if (!Val.isMinValue()) {
2028 Lower = IntMin.sdiv(Val);
2029 Upper = IntMax.sdiv(Val) + 1;
2031 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2032 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2033 APInt NegOne = APInt::getAllOnesValue(Width);
2034 if (CI2->getValue().ult(Width))
2035 Upper = NegOne.lshr(CI2->getValue()) + 1;
2036 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2037 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2038 APInt IntMin = APInt::getSignedMinValue(Width);
2039 APInt IntMax = APInt::getSignedMaxValue(Width);
2040 if (CI2->getValue().ult(Width)) {
2041 Lower = IntMin.ashr(CI2->getValue());
2042 Upper = IntMax.ashr(CI2->getValue()) + 1;
2044 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2045 // 'or x, CI2' produces [CI2, UINT_MAX].
2046 Lower = CI2->getValue();
2047 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2048 // 'and x, CI2' produces [0, CI2].
2049 Upper = CI2->getValue() + 1;
2051 if (Lower != Upper) {
2052 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2053 if (RHS_CR.contains(LHS_CR))
2054 return ConstantInt::getTrue(RHS->getContext());
2055 if (RHS_CR.inverse().contains(LHS_CR))
2056 return ConstantInt::getFalse(RHS->getContext());
2060 // Compare of cast, for example (zext X) != 0 -> X != 0
2061 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2062 Instruction *LI = cast<CastInst>(LHS);
2063 Value *SrcOp = LI->getOperand(0);
2064 Type *SrcTy = SrcOp->getType();
2065 Type *DstTy = LI->getType();
2067 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2068 // if the integer type is the same size as the pointer type.
2069 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2070 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2071 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2072 // Transfer the cast to the constant.
2073 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2074 ConstantExpr::getIntToPtr(RHSC, SrcTy),
2077 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2078 if (RI->getOperand(0)->getType() == SrcTy)
2079 // Compare without the cast.
2080 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2086 if (isa<ZExtInst>(LHS)) {
2087 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2089 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2090 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2091 // Compare X and Y. Note that signed predicates become unsigned.
2092 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2093 SrcOp, RI->getOperand(0), Q,
2097 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2098 // too. If not, then try to deduce the result of the comparison.
2099 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2100 // Compute the constant that would happen if we truncated to SrcTy then
2101 // reextended to DstTy.
2102 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2103 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2105 // If the re-extended constant didn't change then this is effectively
2106 // also a case of comparing two zero-extended values.
2107 if (RExt == CI && MaxRecurse)
2108 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2109 SrcOp, Trunc, Q, MaxRecurse-1))
2112 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2113 // there. Use this to work out the result of the comparison.
2116 default: llvm_unreachable("Unknown ICmp predicate!");
2118 case ICmpInst::ICMP_EQ:
2119 case ICmpInst::ICMP_UGT:
2120 case ICmpInst::ICMP_UGE:
2121 return ConstantInt::getFalse(CI->getContext());
2123 case ICmpInst::ICMP_NE:
2124 case ICmpInst::ICMP_ULT:
2125 case ICmpInst::ICMP_ULE:
2126 return ConstantInt::getTrue(CI->getContext());
2128 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2129 // is non-negative then LHS <s RHS.
2130 case ICmpInst::ICMP_SGT:
2131 case ICmpInst::ICMP_SGE:
2132 return CI->getValue().isNegative() ?
2133 ConstantInt::getTrue(CI->getContext()) :
2134 ConstantInt::getFalse(CI->getContext());
2136 case ICmpInst::ICMP_SLT:
2137 case ICmpInst::ICMP_SLE:
2138 return CI->getValue().isNegative() ?
2139 ConstantInt::getFalse(CI->getContext()) :
2140 ConstantInt::getTrue(CI->getContext());
2146 if (isa<SExtInst>(LHS)) {
2147 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2149 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2150 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2151 // Compare X and Y. Note that the predicate does not change.
2152 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2156 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2157 // too. If not, then try to deduce the result of the comparison.
2158 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2159 // Compute the constant that would happen if we truncated to SrcTy then
2160 // reextended to DstTy.
2161 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2162 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2164 // If the re-extended constant didn't change then this is effectively
2165 // also a case of comparing two sign-extended values.
2166 if (RExt == CI && MaxRecurse)
2167 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2170 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2171 // bits there. Use this to work out the result of the comparison.
2174 default: llvm_unreachable("Unknown ICmp predicate!");
2175 case ICmpInst::ICMP_EQ:
2176 return ConstantInt::getFalse(CI->getContext());
2177 case ICmpInst::ICMP_NE:
2178 return ConstantInt::getTrue(CI->getContext());
2180 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2182 case ICmpInst::ICMP_SGT:
2183 case ICmpInst::ICMP_SGE:
2184 return CI->getValue().isNegative() ?
2185 ConstantInt::getTrue(CI->getContext()) :
2186 ConstantInt::getFalse(CI->getContext());
2187 case ICmpInst::ICMP_SLT:
2188 case ICmpInst::ICMP_SLE:
2189 return CI->getValue().isNegative() ?
2190 ConstantInt::getFalse(CI->getContext()) :
2191 ConstantInt::getTrue(CI->getContext());
2193 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2195 case ICmpInst::ICMP_UGT:
2196 case ICmpInst::ICMP_UGE:
2197 // Comparison is true iff the LHS <s 0.
2199 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2200 Constant::getNullValue(SrcTy),
2204 case ICmpInst::ICMP_ULT:
2205 case ICmpInst::ICMP_ULE:
2206 // Comparison is true iff the LHS >=s 0.
2208 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2209 Constant::getNullValue(SrcTy),
2219 // Special logic for binary operators.
2220 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2221 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2222 if (MaxRecurse && (LBO || RBO)) {
2223 // Analyze the case when either LHS or RHS is an add instruction.
2224 Value *A = 0, *B = 0, *C = 0, *D = 0;
2225 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2226 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2227 if (LBO && LBO->getOpcode() == Instruction::Add) {
2228 A = LBO->getOperand(0); B = LBO->getOperand(1);
2229 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2230 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2231 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2233 if (RBO && RBO->getOpcode() == Instruction::Add) {
2234 C = RBO->getOperand(0); D = RBO->getOperand(1);
2235 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2236 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2237 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2240 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2241 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2242 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2243 Constant::getNullValue(RHS->getType()),
2247 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2248 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2249 if (Value *V = SimplifyICmpInst(Pred,
2250 Constant::getNullValue(LHS->getType()),
2251 C == LHS ? D : C, Q, MaxRecurse-1))
2254 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2255 if (A && C && (A == C || A == D || B == C || B == D) &&
2256 NoLHSWrapProblem && NoRHSWrapProblem) {
2257 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2260 // C + B == C + D -> B == D
2263 } else if (A == D) {
2264 // D + B == C + D -> B == C
2267 } else if (B == C) {
2268 // A + C == C + D -> A == D
2273 // A + D == C + D -> A == C
2277 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2282 // icmp pred (urem X, Y), Y
2283 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2284 bool KnownNonNegative, KnownNegative;
2288 case ICmpInst::ICMP_SGT:
2289 case ICmpInst::ICMP_SGE:
2290 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
2291 if (!KnownNonNegative)
2294 case ICmpInst::ICMP_EQ:
2295 case ICmpInst::ICMP_UGT:
2296 case ICmpInst::ICMP_UGE:
2297 return getFalse(ITy);
2298 case ICmpInst::ICMP_SLT:
2299 case ICmpInst::ICMP_SLE:
2300 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
2301 if (!KnownNonNegative)
2304 case ICmpInst::ICMP_NE:
2305 case ICmpInst::ICMP_ULT:
2306 case ICmpInst::ICMP_ULE:
2307 return getTrue(ITy);
2311 // icmp pred X, (urem Y, X)
2312 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2313 bool KnownNonNegative, KnownNegative;
2317 case ICmpInst::ICMP_SGT:
2318 case ICmpInst::ICMP_SGE:
2319 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
2320 if (!KnownNonNegative)
2323 case ICmpInst::ICMP_NE:
2324 case ICmpInst::ICMP_UGT:
2325 case ICmpInst::ICMP_UGE:
2326 return getTrue(ITy);
2327 case ICmpInst::ICMP_SLT:
2328 case ICmpInst::ICMP_SLE:
2329 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
2330 if (!KnownNonNegative)
2333 case ICmpInst::ICMP_EQ:
2334 case ICmpInst::ICMP_ULT:
2335 case ICmpInst::ICMP_ULE:
2336 return getFalse(ITy);
2341 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2342 // icmp pred (X /u Y), X
2343 if (Pred == ICmpInst::ICMP_UGT)
2344 return getFalse(ITy);
2345 if (Pred == ICmpInst::ICMP_ULE)
2346 return getTrue(ITy);
2349 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2350 LBO->getOperand(1) == RBO->getOperand(1)) {
2351 switch (LBO->getOpcode()) {
2353 case Instruction::UDiv:
2354 case Instruction::LShr:
2355 if (ICmpInst::isSigned(Pred))
2358 case Instruction::SDiv:
2359 case Instruction::AShr:
2360 if (!LBO->isExact() || !RBO->isExact())
2362 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2363 RBO->getOperand(0), Q, MaxRecurse-1))
2366 case Instruction::Shl: {
2367 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2368 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2371 if (!NSW && ICmpInst::isSigned(Pred))
2373 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2374 RBO->getOperand(0), Q, MaxRecurse-1))
2381 // Simplify comparisons involving max/min.
2383 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2384 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2386 // Signed variants on "max(a,b)>=a -> true".
2387 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2388 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2389 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2390 // We analyze this as smax(A, B) pred A.
2392 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2393 (A == LHS || B == LHS)) {
2394 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2395 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2396 // We analyze this as smax(A, B) swapped-pred A.
2397 P = CmpInst::getSwappedPredicate(Pred);
2398 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2399 (A == RHS || B == RHS)) {
2400 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2401 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2402 // We analyze this as smax(-A, -B) swapped-pred -A.
2403 // Note that we do not need to actually form -A or -B thanks to EqP.
2404 P = CmpInst::getSwappedPredicate(Pred);
2405 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2406 (A == LHS || B == LHS)) {
2407 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2408 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2409 // We analyze this as smax(-A, -B) pred -A.
2410 // Note that we do not need to actually form -A or -B thanks to EqP.
2413 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2414 // Cases correspond to "max(A, B) p A".
2418 case CmpInst::ICMP_EQ:
2419 case CmpInst::ICMP_SLE:
2420 // Equivalent to "A EqP B". This may be the same as the condition tested
2421 // in the max/min; if so, we can just return that.
2422 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2424 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2426 // Otherwise, see if "A EqP B" simplifies.
2428 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2431 case CmpInst::ICMP_NE:
2432 case CmpInst::ICMP_SGT: {
2433 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2434 // Equivalent to "A InvEqP B". This may be the same as the condition
2435 // tested in the max/min; if so, we can just return that.
2436 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2438 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2440 // Otherwise, see if "A InvEqP B" simplifies.
2442 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2446 case CmpInst::ICMP_SGE:
2448 return getTrue(ITy);
2449 case CmpInst::ICMP_SLT:
2451 return getFalse(ITy);
2455 // Unsigned variants on "max(a,b)>=a -> true".
2456 P = CmpInst::BAD_ICMP_PREDICATE;
2457 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2458 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2459 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2460 // We analyze this as umax(A, B) pred A.
2462 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2463 (A == LHS || B == LHS)) {
2464 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2465 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2466 // We analyze this as umax(A, B) swapped-pred A.
2467 P = CmpInst::getSwappedPredicate(Pred);
2468 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2469 (A == RHS || B == RHS)) {
2470 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2471 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2472 // We analyze this as umax(-A, -B) swapped-pred -A.
2473 // Note that we do not need to actually form -A or -B thanks to EqP.
2474 P = CmpInst::getSwappedPredicate(Pred);
2475 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2476 (A == LHS || B == LHS)) {
2477 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2478 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2479 // We analyze this as umax(-A, -B) pred -A.
2480 // Note that we do not need to actually form -A or -B thanks to EqP.
2483 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2484 // Cases correspond to "max(A, B) p A".
2488 case CmpInst::ICMP_EQ:
2489 case CmpInst::ICMP_ULE:
2490 // Equivalent to "A EqP B". This may be the same as the condition tested
2491 // in the max/min; if so, we can just return that.
2492 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2494 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2496 // Otherwise, see if "A EqP B" simplifies.
2498 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2501 case CmpInst::ICMP_NE:
2502 case CmpInst::ICMP_UGT: {
2503 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2504 // Equivalent to "A InvEqP B". This may be the same as the condition
2505 // tested in the max/min; if so, we can just return that.
2506 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2508 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2510 // Otherwise, see if "A InvEqP B" simplifies.
2512 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2516 case CmpInst::ICMP_UGE:
2518 return getTrue(ITy);
2519 case CmpInst::ICMP_ULT:
2521 return getFalse(ITy);
2525 // Variants on "max(x,y) >= min(x,z)".
2527 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2528 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2529 (A == C || A == D || B == C || B == D)) {
2530 // max(x, ?) pred min(x, ?).
2531 if (Pred == CmpInst::ICMP_SGE)
2533 return getTrue(ITy);
2534 if (Pred == CmpInst::ICMP_SLT)
2536 return getFalse(ITy);
2537 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2538 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2539 (A == C || A == D || B == C || B == D)) {
2540 // min(x, ?) pred max(x, ?).
2541 if (Pred == CmpInst::ICMP_SLE)
2543 return getTrue(ITy);
2544 if (Pred == CmpInst::ICMP_SGT)
2546 return getFalse(ITy);
2547 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2548 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2549 (A == C || A == D || B == C || B == D)) {
2550 // max(x, ?) pred min(x, ?).
2551 if (Pred == CmpInst::ICMP_UGE)
2553 return getTrue(ITy);
2554 if (Pred == CmpInst::ICMP_ULT)
2556 return getFalse(ITy);
2557 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2558 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2559 (A == C || A == D || B == C || B == D)) {
2560 // min(x, ?) pred max(x, ?).
2561 if (Pred == CmpInst::ICMP_ULE)
2563 return getTrue(ITy);
2564 if (Pred == CmpInst::ICMP_UGT)
2566 return getFalse(ITy);
2569 // Simplify comparisons of related pointers using a powerful, recursive
2570 // GEP-walk when we have target data available..
2571 if (LHS->getType()->isPointerTy())
2572 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
2575 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2576 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2577 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2578 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2579 (ICmpInst::isEquality(Pred) ||
2580 (GLHS->isInBounds() && GRHS->isInBounds() &&
2581 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2582 // The bases are equal and the indices are constant. Build a constant
2583 // expression GEP with the same indices and a null base pointer to see
2584 // what constant folding can make out of it.
2585 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2586 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2587 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2589 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2590 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2591 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2596 // If the comparison is with the result of a select instruction, check whether
2597 // comparing with either branch of the select always yields the same value.
2598 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2599 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2602 // If the comparison is with the result of a phi instruction, check whether
2603 // doing the compare with each incoming phi value yields a common result.
2604 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2605 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2611 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2612 const DataLayout *DL,
2613 const TargetLibraryInfo *TLI,
2614 const DominatorTree *DT) {
2615 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
2619 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2620 /// fold the result. If not, this returns null.
2621 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2622 const Query &Q, unsigned MaxRecurse) {
2623 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2624 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2626 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2627 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2628 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2630 // If we have a constant, make sure it is on the RHS.
2631 std::swap(LHS, RHS);
2632 Pred = CmpInst::getSwappedPredicate(Pred);
2635 // Fold trivial predicates.
2636 if (Pred == FCmpInst::FCMP_FALSE)
2637 return ConstantInt::get(GetCompareTy(LHS), 0);
2638 if (Pred == FCmpInst::FCMP_TRUE)
2639 return ConstantInt::get(GetCompareTy(LHS), 1);
2641 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2642 return UndefValue::get(GetCompareTy(LHS));
2644 // fcmp x,x -> true/false. Not all compares are foldable.
2646 if (CmpInst::isTrueWhenEqual(Pred))
2647 return ConstantInt::get(GetCompareTy(LHS), 1);
2648 if (CmpInst::isFalseWhenEqual(Pred))
2649 return ConstantInt::get(GetCompareTy(LHS), 0);
2652 // Handle fcmp with constant RHS
2653 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2654 // If the constant is a nan, see if we can fold the comparison based on it.
2655 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2656 if (CFP->getValueAPF().isNaN()) {
2657 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2658 return ConstantInt::getFalse(CFP->getContext());
2659 assert(FCmpInst::isUnordered(Pred) &&
2660 "Comparison must be either ordered or unordered!");
2661 // True if unordered.
2662 return ConstantInt::getTrue(CFP->getContext());
2664 // Check whether the constant is an infinity.
2665 if (CFP->getValueAPF().isInfinity()) {
2666 if (CFP->getValueAPF().isNegative()) {
2668 case FCmpInst::FCMP_OLT:
2669 // No value is ordered and less than negative infinity.
2670 return ConstantInt::getFalse(CFP->getContext());
2671 case FCmpInst::FCMP_UGE:
2672 // All values are unordered with or at least negative infinity.
2673 return ConstantInt::getTrue(CFP->getContext());
2679 case FCmpInst::FCMP_OGT:
2680 // No value is ordered and greater than infinity.
2681 return ConstantInt::getFalse(CFP->getContext());
2682 case FCmpInst::FCMP_ULE:
2683 // All values are unordered with and at most infinity.
2684 return ConstantInt::getTrue(CFP->getContext());
2693 // If the comparison is with the result of a select instruction, check whether
2694 // comparing with either branch of the select always yields the same value.
2695 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2696 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2699 // If the comparison is with the result of a phi instruction, check whether
2700 // doing the compare with each incoming phi value yields a common result.
2701 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2702 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2708 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2709 const DataLayout *DL,
2710 const TargetLibraryInfo *TLI,
2711 const DominatorTree *DT) {
2712 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
2716 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2717 /// the result. If not, this returns null.
2718 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2719 Value *FalseVal, const Query &Q,
2720 unsigned MaxRecurse) {
2721 // select true, X, Y -> X
2722 // select false, X, Y -> Y
2723 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2724 if (CB->isAllOnesValue())
2726 if (CB->isNullValue())
2730 // select C, X, X -> X
2731 if (TrueVal == FalseVal)
2734 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2735 if (isa<Constant>(TrueVal))
2739 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2741 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2747 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2748 const DataLayout *DL,
2749 const TargetLibraryInfo *TLI,
2750 const DominatorTree *DT) {
2751 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (DL, TLI, DT),
2755 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2756 /// fold the result. If not, this returns null.
2757 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2758 // The type of the GEP pointer operand.
2759 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
2761 // getelementptr P -> P.
2762 if (Ops.size() == 1)
2765 if (isa<UndefValue>(Ops[0])) {
2766 // Compute the (pointer) type returned by the GEP instruction.
2767 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2768 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2769 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
2770 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
2771 return UndefValue::get(GEPTy);
2774 if (Ops.size() == 2) {
2775 // getelementptr P, 0 -> P.
2776 if (match(Ops[1], m_Zero()))
2778 // getelementptr P, N -> P if P points to a type of zero size.
2780 Type *Ty = PtrTy->getElementType();
2781 if (Ty->isSized() && Q.DL->getTypeAllocSize(Ty) == 0)
2786 // Check to see if this is constant foldable.
2787 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2788 if (!isa<Constant>(Ops[i]))
2791 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2794 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
2795 const TargetLibraryInfo *TLI,
2796 const DominatorTree *DT) {
2797 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT), RecursionLimit);
2800 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2801 /// can fold the result. If not, this returns null.
2802 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2803 ArrayRef<unsigned> Idxs, const Query &Q,
2805 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2806 if (Constant *CVal = dyn_cast<Constant>(Val))
2807 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2809 // insertvalue x, undef, n -> x
2810 if (match(Val, m_Undef()))
2813 // insertvalue x, (extractvalue y, n), n
2814 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2815 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2816 EV->getIndices() == Idxs) {
2817 // insertvalue undef, (extractvalue y, n), n -> y
2818 if (match(Agg, m_Undef()))
2819 return EV->getAggregateOperand();
2821 // insertvalue y, (extractvalue y, n), n -> y
2822 if (Agg == EV->getAggregateOperand())
2829 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2830 ArrayRef<unsigned> Idxs,
2831 const DataLayout *DL,
2832 const TargetLibraryInfo *TLI,
2833 const DominatorTree *DT) {
2834 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (DL, TLI, DT),
2838 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2839 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
2840 // If all of the PHI's incoming values are the same then replace the PHI node
2841 // with the common value.
2842 Value *CommonValue = 0;
2843 bool HasUndefInput = false;
2844 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2845 Value *Incoming = PN->getIncomingValue(i);
2846 // If the incoming value is the phi node itself, it can safely be skipped.
2847 if (Incoming == PN) continue;
2848 if (isa<UndefValue>(Incoming)) {
2849 // Remember that we saw an undef value, but otherwise ignore them.
2850 HasUndefInput = true;
2853 if (CommonValue && Incoming != CommonValue)
2854 return 0; // Not the same, bail out.
2855 CommonValue = Incoming;
2858 // If CommonValue is null then all of the incoming values were either undef or
2859 // equal to the phi node itself.
2861 return UndefValue::get(PN->getType());
2863 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2864 // instruction, we cannot return X as the result of the PHI node unless it
2865 // dominates the PHI block.
2867 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
2872 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2873 if (Constant *C = dyn_cast<Constant>(Op))
2874 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
2879 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
2880 const TargetLibraryInfo *TLI,
2881 const DominatorTree *DT) {
2882 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT), RecursionLimit);
2885 //=== Helper functions for higher up the class hierarchy.
2887 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2888 /// fold the result. If not, this returns null.
2889 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2890 const Query &Q, unsigned MaxRecurse) {
2892 case Instruction::Add:
2893 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2895 case Instruction::FAdd:
2896 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2898 case Instruction::Sub:
2899 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2901 case Instruction::FSub:
2902 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2904 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2905 case Instruction::FMul:
2906 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2907 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2908 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2909 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2910 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2911 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2912 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
2913 case Instruction::Shl:
2914 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2916 case Instruction::LShr:
2917 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2918 case Instruction::AShr:
2919 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2920 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2921 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2922 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
2924 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2925 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2926 Constant *COps[] = {CLHS, CRHS};
2927 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
2931 // If the operation is associative, try some generic simplifications.
2932 if (Instruction::isAssociative(Opcode))
2933 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
2936 // If the operation is with the result of a select instruction check whether
2937 // operating on either branch of the select always yields the same value.
2938 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2939 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
2942 // If the operation is with the result of a phi instruction, check whether
2943 // operating on all incoming values of the phi always yields the same value.
2944 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2945 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
2952 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2953 const DataLayout *DL, const TargetLibraryInfo *TLI,
2954 const DominatorTree *DT) {
2955 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT), RecursionLimit);
2958 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2959 /// fold the result.
2960 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2961 const Query &Q, unsigned MaxRecurse) {
2962 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2963 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2964 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2967 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2968 const DataLayout *DL, const TargetLibraryInfo *TLI,
2969 const DominatorTree *DT) {
2970 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
2974 static bool IsIdempotent(Intrinsic::ID ID) {
2976 default: return false;
2978 // Unary idempotent: f(f(x)) = f(x)
2979 case Intrinsic::fabs:
2980 case Intrinsic::floor:
2981 case Intrinsic::ceil:
2982 case Intrinsic::trunc:
2983 case Intrinsic::rint:
2984 case Intrinsic::nearbyint:
2985 case Intrinsic::round:
2990 template <typename IterTy>
2991 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
2992 const Query &Q, unsigned MaxRecurse) {
2993 // Perform idempotent optimizations
2994 if (!IsIdempotent(IID))
2998 if (std::distance(ArgBegin, ArgEnd) == 1)
2999 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3000 if (II->getIntrinsicID() == IID)
3006 template <typename IterTy>
3007 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
3008 const Query &Q, unsigned MaxRecurse) {
3009 Type *Ty = V->getType();
3010 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3011 Ty = PTy->getElementType();
3012 FunctionType *FTy = cast<FunctionType>(Ty);
3014 // call undef -> undef
3015 if (isa<UndefValue>(V))
3016 return UndefValue::get(FTy->getReturnType());
3018 Function *F = dyn_cast<Function>(V);
3022 if (unsigned IID = F->getIntrinsicID())
3024 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3027 if (!canConstantFoldCallTo(F))
3030 SmallVector<Constant *, 4> ConstantArgs;
3031 ConstantArgs.reserve(ArgEnd - ArgBegin);
3032 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3033 Constant *C = dyn_cast<Constant>(*I);
3036 ConstantArgs.push_back(C);
3039 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
3042 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
3043 User::op_iterator ArgEnd, const DataLayout *DL,
3044 const TargetLibraryInfo *TLI,
3045 const DominatorTree *DT) {
3046 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT),
3050 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
3051 const DataLayout *DL, const TargetLibraryInfo *TLI,
3052 const DominatorTree *DT) {
3053 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(DL, TLI, DT),
3057 /// SimplifyInstruction - See if we can compute a simplified version of this
3058 /// instruction. If not, this returns null.
3059 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
3060 const TargetLibraryInfo *TLI,
3061 const DominatorTree *DT) {
3064 switch (I->getOpcode()) {
3066 Result = ConstantFoldInstruction(I, DL, TLI);
3068 case Instruction::FAdd:
3069 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3070 I->getFastMathFlags(), DL, TLI, DT);
3072 case Instruction::Add:
3073 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3074 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3075 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3078 case Instruction::FSub:
3079 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3080 I->getFastMathFlags(), DL, TLI, DT);
3082 case Instruction::Sub:
3083 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3084 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3085 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3088 case Instruction::FMul:
3089 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3090 I->getFastMathFlags(), DL, TLI, DT);
3092 case Instruction::Mul:
3093 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3095 case Instruction::SDiv:
3096 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3098 case Instruction::UDiv:
3099 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3101 case Instruction::FDiv:
3102 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3104 case Instruction::SRem:
3105 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3107 case Instruction::URem:
3108 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3110 case Instruction::FRem:
3111 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3113 case Instruction::Shl:
3114 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3115 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3116 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3119 case Instruction::LShr:
3120 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3121 cast<BinaryOperator>(I)->isExact(),
3124 case Instruction::AShr:
3125 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3126 cast<BinaryOperator>(I)->isExact(),
3129 case Instruction::And:
3130 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3132 case Instruction::Or:
3133 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3135 case Instruction::Xor:
3136 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3138 case Instruction::ICmp:
3139 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
3140 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3142 case Instruction::FCmp:
3143 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
3144 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3146 case Instruction::Select:
3147 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
3148 I->getOperand(2), DL, TLI, DT);
3150 case Instruction::GetElementPtr: {
3151 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
3152 Result = SimplifyGEPInst(Ops, DL, TLI, DT);
3155 case Instruction::InsertValue: {
3156 InsertValueInst *IV = cast<InsertValueInst>(I);
3157 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3158 IV->getInsertedValueOperand(),
3159 IV->getIndices(), DL, TLI, DT);
3162 case Instruction::PHI:
3163 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT));
3165 case Instruction::Call: {
3166 CallSite CS(cast<CallInst>(I));
3167 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3171 case Instruction::Trunc:
3172 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT);
3176 /// If called on unreachable code, the above logic may report that the
3177 /// instruction simplified to itself. Make life easier for users by
3178 /// detecting that case here, returning a safe value instead.
3179 return Result == I ? UndefValue::get(I->getType()) : Result;
3182 /// \brief Implementation of recursive simplification through an instructions
3185 /// This is the common implementation of the recursive simplification routines.
3186 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3187 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3188 /// instructions to process and attempt to simplify it using
3189 /// InstructionSimplify.
3191 /// This routine returns 'true' only when *it* simplifies something. The passed
3192 /// in simplified value does not count toward this.
3193 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
3194 const DataLayout *DL,
3195 const TargetLibraryInfo *TLI,
3196 const DominatorTree *DT) {
3197 bool Simplified = false;
3198 SmallSetVector<Instruction *, 8> Worklist;
3200 // If we have an explicit value to collapse to, do that round of the
3201 // simplification loop by hand initially.
3203 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3206 Worklist.insert(cast<Instruction>(*UI));
3208 // Replace the instruction with its simplified value.
3209 I->replaceAllUsesWith(SimpleV);
3211 // Gracefully handle edge cases where the instruction is not wired into any
3214 I->eraseFromParent();
3219 // Note that we must test the size on each iteration, the worklist can grow.
3220 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3223 // See if this instruction simplifies.
3224 SimpleV = SimplifyInstruction(I, DL, TLI, DT);
3230 // Stash away all the uses of the old instruction so we can check them for
3231 // recursive simplifications after a RAUW. This is cheaper than checking all
3232 // uses of To on the recursive step in most cases.
3233 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3235 Worklist.insert(cast<Instruction>(*UI));
3237 // Replace the instruction with its simplified value.
3238 I->replaceAllUsesWith(SimpleV);
3240 // Gracefully handle edge cases where the instruction is not wired into any
3243 I->eraseFromParent();
3248 bool llvm::recursivelySimplifyInstruction(Instruction *I,
3249 const DataLayout *DL,
3250 const TargetLibraryInfo *TLI,
3251 const DominatorTree *DT) {
3252 return replaceAndRecursivelySimplifyImpl(I, 0, DL, TLI, DT);
3255 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
3256 const DataLayout *DL,
3257 const TargetLibraryInfo *TLI,
3258 const DominatorTree *DT) {
3259 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3260 assert(SimpleV && "Must provide a simplified value.");
3261 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT);