InstructionSimplify.cpp revision 223017
1111314Snyan//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2111314Snyan//
3111314Snyan//                     The LLVM Compiler Infrastructure
4111314Snyan//
5111314Snyan// This file is distributed under the University of Illinois Open Source
6111314Snyan// License. See LICENSE.TXT for details.
7111314Snyan//
8111314Snyan//===----------------------------------------------------------------------===//
9111314Snyan//
10111314Snyan// This file implements routines for folding instructions into simpler forms
11111314Snyan// that do not require creating new instructions.  This does constant folding
12111314Snyan// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13111314Snyan// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14111314Snyan// ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15144512Simp// simplified: This is usually true and assuming it simplifies the logic (if
16111314Snyan// they have not been simplified then results are correct but maybe suboptimal).
17111314Snyan//
18125234Snyan//===----------------------------------------------------------------------===//
19127520Snyan
20111314Snyan#define DEBUG_TYPE "instsimplify"
21111314Snyan#include "llvm/Operator.h"
22111314Snyan#include "llvm/ADT/Statistic.h"
23111314Snyan#include "llvm/Analysis/InstructionSimplify.h"
24111314Snyan#include "llvm/Analysis/ConstantFolding.h"
25111314Snyan#include "llvm/Analysis/Dominators.h"
26122755Snyan#include "llvm/Analysis/ValueTracking.h"
27122755Snyan#include "llvm/Support/ConstantRange.h"
28122755Snyan#include "llvm/Support/PatternMatch.h"
29122755Snyan#include "llvm/Support/ValueHandle.h"
30111314Snyan#include "llvm/Target/TargetData.h"
31111314Snyanusing namespace llvm;
32111314Snyanusing namespace llvm::PatternMatch;
33122056Snyan
34124795Snyanenum { RecursionLimit = 3 };
35142783Snyan
36142783SnyanSTATISTIC(NumExpand,  "Number of expansions");
37142783SnyanSTATISTIC(NumFactor , "Number of factorizations");
38142783SnyanSTATISTIC(NumReassoc, "Number of reassociations");
39142783Snyan
40145743Snyanstatic Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41145743Snyan                              const DominatorTree *, unsigned);
42145743Snyanstatic Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
43145743Snyan                            const DominatorTree *, unsigned);
44145743Snyanstatic Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
45111314Snyan                              const DominatorTree *, unsigned);
46111314Snyanstatic Value *SimplifyOrInst(Value *, Value *, const TargetData *,
47111314Snyan                             const DominatorTree *, unsigned);
48111314Snyanstatic Value *SimplifyXorInst(Value *, Value *, const TargetData *,
49111314Snyan                              const DominatorTree *, unsigned);
50111314Snyan
51111314Snyan/// ValueDominatesPHI - Does the given value dominate the specified phi node?
52111314Snyanstatic bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
53111314Snyan  Instruction *I = dyn_cast<Instruction>(V);
54111314Snyan  if (!I)
55111314Snyan    // Arguments and constants dominate all instructions.
56111314Snyan    return true;
57111314Snyan
58111314Snyan  // If we have a DominatorTree then do a precise test.
59111314Snyan  if (DT)
60111314Snyan    return DT->dominates(I, P);
61124795Snyan
62124795Snyan  // Otherwise, if the instruction is in the entry block, and is not an invoke,
63124795Snyan  // then it obviously dominates all phi nodes.
64124795Snyan  if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
65111314Snyan      !isa<InvokeInst>(I))
66111314Snyan    return true;
67111314Snyan
68111314Snyan  return false;
69111314Snyan}
70111314Snyan
71111314Snyan/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
72111314Snyan/// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
73111314Snyan/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
74111314Snyan/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
75124795Snyan/// Returns the simplified value, or null if no simplification was performed.
76124795Snyanstatic Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
77124795Snyan                          unsigned OpcToExpand, const TargetData *TD,
78127520Snyan                          const DominatorTree *DT, unsigned MaxRecurse) {
79111314Snyan  Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
80111314Snyan  // Recursion is always used, so bail out at once if we already hit the limit.
81111314Snyan  if (!MaxRecurse--)
82125234Snyan    return 0;
83137526Snyan
84137526Snyan  // Check whether the expression has the form "(A op' B) op C".
85137526Snyan  if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
86137526Snyan    if (Op0->getOpcode() == OpcodeToExpand) {
87137526Snyan      // It does!  Try turning it into "(A op C) op' (B op C)".
88124795Snyan      Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
89127520Snyan      // Do "A op C" and "B op C" both simplify?
90124795Snyan      if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
91111314Snyan        if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
92111314Snyan          // They do! Return "L op' R" if it simplifies or is already available.
93111314Snyan          // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
94111314Snyan          if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
95111314Snyan                                     && L == B && R == A)) {
96111314Snyan            ++NumExpand;
97111314Snyan            return LHS;
98111314Snyan          }
99111314Snyan          // Otherwise return "L op' R" if it simplifies.
100125234Snyan          if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
101111314Snyan                                       MaxRecurse)) {
102111314Snyan            ++NumExpand;
103111314Snyan            return V;
104111314Snyan          }
105111314Snyan        }
106111314Snyan    }
107111314Snyan
108111314Snyan  // Check whether the expression has the form "A op (B op' C)".
109111314Snyan  if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
110111314Snyan    if (Op1->getOpcode() == OpcodeToExpand) {
111111314Snyan      // It does!  Try turning it into "(A op B) op' (A op C)".
112111314Snyan      Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
113111314Snyan      // Do "A op B" and "A op C" both simplify?
114111314Snyan      if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
115111314Snyan        if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
116111314Snyan          // They do! Return "L op' R" if it simplifies or is already available.
117111314Snyan          // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
118111314Snyan          if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
119111314Snyan                                     && L == C && R == B)) {
120125234Snyan            ++NumExpand;
121111314Snyan            return RHS;
122111314Snyan          }
123111314Snyan          // Otherwise return "L op' R" if it simplifies.
124111314Snyan          if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
125111314Snyan                                       MaxRecurse)) {
126111314Snyan            ++NumExpand;
127111314Snyan            return V;
128111314Snyan          }
129111314Snyan        }
130111314Snyan    }
131111314Snyan
132111314Snyan  return 0;
133111314Snyan}
134111314Snyan
135111314Snyan/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
136111314Snyan/// using the operation OpCodeToExtract.  For example, when Opcode is Add and
137111314Snyan/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
138111314Snyan/// Returns the simplified value, or null if no simplification was performed.
139111314Snyanstatic Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
140111314Snyan                             unsigned OpcToExtract, const TargetData *TD,
141111314Snyan                             const DominatorTree *DT, unsigned MaxRecurse) {
142111314Snyan  Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
143111314Snyan  // Recursion is always used, so bail out at once if we already hit the limit.
144111314Snyan  if (!MaxRecurse--)
145111314Snyan    return 0;
146111314Snyan
147111314Snyan  BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
148111314Snyan  BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
149124795Snyan
150111314Snyan  if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
151111314Snyan      !Op1 || Op1->getOpcode() != OpcodeToExtract)
152111314Snyan    return 0;
153111314Snyan
154124795Snyan  // The expression has the form "(A op' B) op (C op' D)".
155124795Snyan  Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
156111314Snyan  Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
157111314Snyan
158111314Snyan  // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
159111314Snyan  // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
160111314Snyan  // commutative case, "(A op' B) op (C op' A)"?
161111314Snyan  if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
162111314Snyan    Value *DD = A == C ? D : C;
163111314Snyan    // Form "A op' (B op DD)" if it simplifies completely.
164111314Snyan    // Does "B op DD" simplify?
165111314Snyan    if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
166111314Snyan      // It does!  Return "A op' V" if it simplifies or is already available.
167111314Snyan      // If V equals B then "A op' V" is just the LHS.  If V equals DD then
168111314Snyan      // "A op' V" is just the RHS.
169111314Snyan      if (V == B || V == DD) {
170111314Snyan        ++NumFactor;
171124795Snyan        return V == B ? LHS : RHS;
172111314Snyan      }
173111314Snyan      // Otherwise return "A op' V" if it simplifies.
174111314Snyan      if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
175111314Snyan        ++NumFactor;
176111314Snyan        return W;
177111314Snyan      }
178111314Snyan    }
179111314Snyan  }
180111314Snyan
181111314Snyan  // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
182111314Snyan  // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
183111314Snyan  // commutative case, "(A op' B) op (B op' D)"?
184111314Snyan  if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
185111314Snyan    Value *CC = B == D ? C : D;
186111314Snyan    // Form "(A op CC) op' B" if it simplifies completely..
187111314Snyan    // Does "A op CC" simplify?
188124795Snyan    if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
189111314Snyan      // It does!  Return "V op' B" if it simplifies or is already available.
190111314Snyan      // If V equals A then "V op' B" is just the LHS.  If V equals CC then
191111314Snyan      // "V op' B" is just the RHS.
192111314Snyan      if (V == A || V == CC) {
193111314Snyan        ++NumFactor;
194111314Snyan        return V == A ? LHS : RHS;
195111314Snyan      }
196111314Snyan      // Otherwise return "V op' B" if it simplifies.
197124408Snyan      if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
198124408Snyan        ++NumFactor;
199111314Snyan        return W;
200111314Snyan      }
201111314Snyan    }
202111314Snyan  }
203111314Snyan
204111314Snyan  return 0;
205111314Snyan}
206111314Snyan
207111314Snyan/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
208111314Snyan/// operations.  Returns the simpler value, or null if none was found.
209123984Sbdestatic Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
210123984Sbde                                       const TargetData *TD,
211123984Sbde                                       const DominatorTree *DT,
212123984Sbde                                       unsigned MaxRecurse) {
213111314Snyan  Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
214111314Snyan  assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
215123984Sbde
216123984Sbde  // Recursion is always used, so bail out at once if we already hit the limit.
217111314Snyan  if (!MaxRecurse--)
218111314Snyan    return 0;
219111314Snyan
220111314Snyan  BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
221111314Snyan  BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
222111314Snyan
223111314Snyan  // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
224111314Snyan  if (Op0 && Op0->getOpcode() == Opcode) {
225111314Snyan    Value *A = Op0->getOperand(0);
226124795Snyan    Value *B = Op0->getOperand(1);
227111314Snyan    Value *C = RHS;
228111314Snyan
229111314Snyan    // Does "B op C" simplify?
230111314Snyan    if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
231111314Snyan      // It does!  Return "A op V" if it simplifies or is already available.
232111314Snyan      // If V equals B then "A op V" is just the LHS.
233111314Snyan      if (V == B) return LHS;
234111314Snyan      // Otherwise return "A op V" if it simplifies.
235111314Snyan      if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
236111314Snyan        ++NumReassoc;
237111314Snyan        return W;
238111314Snyan      }
239111314Snyan    }
240111314Snyan  }
241111314Snyan
242111314Snyan  // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
243111314Snyan  if (Op1 && Op1->getOpcode() == Opcode) {
244111314Snyan    Value *A = LHS;
245111314Snyan    Value *B = Op1->getOperand(0);
246111314Snyan    Value *C = Op1->getOperand(1);
247111314Snyan
248111314Snyan    // Does "A op B" simplify?
249111314Snyan    if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
250111314Snyan      // It does!  Return "V op C" if it simplifies or is already available.
251111314Snyan      // If V equals B then "V op C" is just the RHS.
252111314Snyan      if (V == B) return RHS;
253111314Snyan      // Otherwise return "V op C" if it simplifies.
254111314Snyan      if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
255111314Snyan        ++NumReassoc;
256111314Snyan        return W;
257111314Snyan      }
258111314Snyan    }
259111314Snyan  }
260111314Snyan
261111314Snyan  // The remaining transforms require commutativity as well as associativity.
262111314Snyan  if (!Instruction::isCommutative(Opcode))
263111314Snyan    return 0;
264111314Snyan
265111314Snyan  // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
266111314Snyan  if (Op0 && Op0->getOpcode() == Opcode) {
267111314Snyan    Value *A = Op0->getOperand(0);
268111314Snyan    Value *B = Op0->getOperand(1);
269111314Snyan    Value *C = RHS;
270111314Snyan
271111314Snyan    // Does "C op A" simplify?
272111314Snyan    if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
273111314Snyan      // It does!  Return "V op B" if it simplifies or is already available.
274111314Snyan      // If V equals A then "V op B" is just the LHS.
275111314Snyan      if (V == A) return LHS;
276111314Snyan      // Otherwise return "V op B" if it simplifies.
277111314Snyan      if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
278111314Snyan        ++NumReassoc;
279111314Snyan        return W;
280111314Snyan      }
281111314Snyan    }
282111314Snyan  }
283111314Snyan
284111314Snyan  // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
285111314Snyan  if (Op1 && Op1->getOpcode() == Opcode) {
286111314Snyan    Value *A = LHS;
287111314Snyan    Value *B = Op1->getOperand(0);
288111314Snyan    Value *C = Op1->getOperand(1);
289111314Snyan
290111314Snyan    // Does "C op A" simplify?
291111314Snyan    if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
292111314Snyan      // It does!  Return "B op V" if it simplifies or is already available.
293111314Snyan      // If V equals C then "B op V" is just the RHS.
294131815Snyan      if (V == C) return RHS;
295111314Snyan      // Otherwise return "B op V" if it simplifies.
296111314Snyan      if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
297111314Snyan        ++NumReassoc;
298111314Snyan        return W;
299111314Snyan      }
300111314Snyan    }
301111314Snyan  }
302111314Snyan
303111314Snyan  return 0;
304111314Snyan}
305111314Snyan
306111314Snyan/// ThreadBinOpOverSelect - In the case of a binary operation with a select
307111314Snyan/// instruction as an operand, try to simplify the binop by seeing whether
308111314Snyan/// evaluating it on both branches of the select results in the same value.
309111314Snyan/// Returns the common value if so, otherwise returns null.
310140371Srustatic Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
311111314Snyan                                    const TargetData *TD,
312111314Snyan                                    const DominatorTree *DT,
313111314Snyan                                    unsigned MaxRecurse) {
314111314Snyan  // Recursion is always used, so bail out at once if we already hit the limit.
315111314Snyan  if (!MaxRecurse--)
316111314Snyan    return 0;
317111314Snyan
318111314Snyan  SelectInst *SI;
319124795Snyan  if (isa<SelectInst>(LHS)) {
320124795Snyan    SI = cast<SelectInst>(LHS);
321124795Snyan  } else {
322111314Snyan    assert(isa<SelectInst>(RHS) && "No select instruction operand!");
323111314Snyan    SI = cast<SelectInst>(RHS);
324111314Snyan  }
325124795Snyan
326111314Snyan  // Evaluate the BinOp on the true and false branches of the select.
327111314Snyan  Value *TV;
328126708Snyan  Value *FV;
329111314Snyan  if (SI == LHS) {
330111314Snyan    TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
331145183Snyan    FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
332145183Snyan  } else {
333145183Snyan    TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
334145183Snyan    FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
335145183Snyan  }
336148235Snyan
337145183Snyan  // If they simplified to the same value, then return the common value.
338145183Snyan  // If they both failed to simplify then return null.
339145183Snyan  if (TV == FV)
340111314Snyan    return TV;
341111314Snyan
342111314Snyan  // If one branch simplified to undef, return the other one.
343111314Snyan  if (TV && isa<UndefValue>(TV))
344111314Snyan    return FV;
345111314Snyan  if (FV && isa<UndefValue>(FV))
346111314Snyan    return TV;
347111314Snyan
348111314Snyan  // If applying the operation did not change the true and false select values,
349111314Snyan  // then the result of the binop is the select itself.
350111314Snyan  if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
351111314Snyan    return SI;
352111314Snyan
353111314Snyan  // If one branch simplified and the other did not, and the simplified
354111314Snyan  // value is equal to the unsimplified one, return the simplified value.
355129384Snyan  // For example, select (cond, X, X & Z) & Z -> X & Z.
356129384Snyan  if ((FV && !TV) || (TV && !FV)) {
357129384Snyan    // Check that the simplified value has the form "X op Y" where "op" is the
358129384Snyan    // same as the original operation.
359111314Snyan    Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
360125234Snyan    if (Simplified && Simplified->getOpcode() == Opcode) {
361111314Snyan      // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
362111314Snyan      // We already know that "op" is the same as for the simplified value.  See
363111314Snyan      // if the operands match too.  If so, return the simplified value.
364111314Snyan      Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
365111314Snyan      Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
366126708Snyan      Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
367111314Snyan      if (Simplified->getOperand(0) == UnsimplifiedLHS &&
368126708Snyan          Simplified->getOperand(1) == UnsimplifiedRHS)
369126708Snyan        return Simplified;
370111314Snyan      if (Simplified->isCommutative() &&
371111314Snyan          Simplified->getOperand(1) == UnsimplifiedLHS &&
372111314Snyan          Simplified->getOperand(0) == UnsimplifiedRHS)
373111314Snyan        return Simplified;
374111314Snyan    }
375129384Snyan  }
376111314Snyan
377111314Snyan  return 0;
378111314Snyan}
379111314Snyan
380111314Snyan/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
381111314Snyan/// try to simplify the comparison by seeing whether both branches of the select
382112840Smdodd/// result in the same value.  Returns the common value if so, otherwise returns
383112840Smdodd/// null.
384112840Smdoddstatic Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
385112840Smdodd                                  Value *RHS, const TargetData *TD,
386112840Smdodd                                  const DominatorTree *DT,
387111314Snyan                                  unsigned MaxRecurse) {
388111314Snyan  // Recursion is always used, so bail out at once if we already hit the limit.
389111314Snyan  if (!MaxRecurse--)
390111314Snyan    return 0;
391111314Snyan
392111314Snyan  // Make sure the select is on the LHS.
393111314Snyan  if (!isa<SelectInst>(LHS)) {
394111314Snyan    std::swap(LHS, RHS);
395111314Snyan    Pred = CmpInst::getSwappedPredicate(Pred);
396111314Snyan  }
397111314Snyan  assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
398111314Snyan  SelectInst *SI = cast<SelectInst>(LHS);
399111314Snyan
400111314Snyan  // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
401111314Snyan  // Does "cmp TV, RHS" simplify?
402111314Snyan  if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
403111314Snyan                                    MaxRecurse)) {
404111314Snyan    // It does!  Does "cmp FV, RHS" simplify?
405125234Snyan    if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
406111314Snyan                                      MaxRecurse)) {
407125234Snyan      // It does!  If they simplified to the same value, then use it as the
408111314Snyan      // result of the original comparison.
409111314Snyan      if (TCmp == FCmp)
410111314Snyan        return TCmp;
411111314Snyan      Value *Cond = SI->getCondition();
412111314Snyan      // If the false value simplified to false, then the result of the compare
413111314Snyan      // is equal to "Cond && TCmp".  This also catches the case when the false
414111314Snyan      // value simplified to false and the true value to true, returning "Cond".
415126708Snyan      if (match(FCmp, m_Zero()))
416126708Snyan        if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
417126708Snyan          return V;
418111314Snyan      // If the true value simplified to true, then the result of the compare
419111314Snyan      // is equal to "Cond || FCmp".
420117918Snyan      if (match(TCmp, m_One()))
421117918Snyan        if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
422117918Snyan          return V;
423117918Snyan      // Finally, if the false value simplified to true and the true value to
424142783Snyan      // false, then the result of the compare is equal to "!Cond".
425142783Snyan      if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
426117918Snyan        if (Value *V =
427117918Snyan            SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
428117918Snyan                            TD, DT, MaxRecurse))
429117918Snyan          return V;
430111314Snyan    }
431111314Snyan  }
432111314Snyan
433111314Snyan  return 0;
434124795Snyan}
435111314Snyan
436111314Snyan/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
437111314Snyan/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
438111314Snyan/// it on the incoming phi values yields the same result for every value.  If so
439111314Snyan/// returns the common value, otherwise returns null.
440111314Snyanstatic Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
441111314Snyan                                 const TargetData *TD, const DominatorTree *DT,
442111314Snyan                                 unsigned MaxRecurse) {
443111314Snyan  // Recursion is always used, so bail out at once if we already hit the limit.
444111314Snyan  if (!MaxRecurse--)
445128876Sbde    return 0;
446127945Snyan
447111314Snyan  PHINode *PI;
448111314Snyan  if (isa<PHINode>(LHS)) {
449111314Snyan    PI = cast<PHINode>(LHS);
450111314Snyan    // Bail out if RHS and the phi may be mutually interdependent due to a loop.
451111314Snyan    if (!ValueDominatesPHI(RHS, PI, DT))
452111314Snyan      return 0;
453111314Snyan  } else {
454111314Snyan    assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
455111314Snyan    PI = cast<PHINode>(RHS);
456124795Snyan    // Bail out if LHS and the phi may be mutually interdependent due to a loop.
457124795Snyan    if (!ValueDominatesPHI(LHS, PI, DT))
458124795Snyan      return 0;
459128221Simp  }
460128221Simp
461128221Simp  // Evaluate the BinOp on the incoming phi values.
462128221Simp  Value *CommonValue = 0;
463128221Simp  for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
464128221Simp    Value *Incoming = PI->getIncomingValue(i);
465128221Simp    // If the incoming value is the phi node itself, it can safely be skipped.
466111314Snyan    if (Incoming == PI) continue;
467111314Snyan    Value *V = PI == LHS ?
468111314Snyan      SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
469111314Snyan      SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
470111314Snyan    // If the operation failed to simplify, or simplified to a different value
471111314Snyan    // to previously, then give up.
472111314Snyan    if (!V || (CommonValue && V != CommonValue))
473111314Snyan      return 0;
474111314Snyan    CommonValue = V;
475111314Snyan  }
476111314Snyan
477111314Snyan  return CommonValue;
478111314Snyan}
479111314Snyan
480111314Snyan/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
481111314Snyan/// try to simplify the comparison by seeing whether comparing with all of the
482111314Snyan/// incoming phi values yields the same result every time.  If so returns the
483111314Snyan/// common result, otherwise returns null.
484111314Snyanstatic Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
485111314Snyan                               const TargetData *TD, const DominatorTree *DT,
486111314Snyan                               unsigned MaxRecurse) {
487111314Snyan  // Recursion is always used, so bail out at once if we already hit the limit.
488132155Sdes  if (!MaxRecurse--)
489111314Snyan    return 0;
490111314Snyan
491111314Snyan  // Make sure the phi is on the LHS.
492111314Snyan  if (!isa<PHINode>(LHS)) {
493111314Snyan    std::swap(LHS, RHS);
494111314Snyan    Pred = CmpInst::getSwappedPredicate(Pred);
495111314Snyan  }
496111314Snyan  assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
497111314Snyan  PHINode *PI = cast<PHINode>(LHS);
498111314Snyan
499111314Snyan  // Bail out if RHS and the phi may be mutually interdependent due to a loop.
500111314Snyan  if (!ValueDominatesPHI(RHS, PI, DT))
501111314Snyan    return 0;
502125234Snyan
503111314Snyan  // Evaluate the BinOp on the incoming phi values.
504111314Snyan  Value *CommonValue = 0;
505111314Snyan  for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
506111314Snyan    Value *Incoming = PI->getIncomingValue(i);
507111314Snyan    // If the incoming value is the phi node itself, it can safely be skipped.
508111314Snyan    if (Incoming == PI) continue;
509111314Snyan    Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
510111314Snyan    // If the operation failed to simplify, or simplified to a different value
511111314Snyan    // to previously, then give up.
512111314Snyan    if (!V || (CommonValue && V != CommonValue))
513125234Snyan      return 0;
514111314Snyan    CommonValue = V;
515111314Snyan  }
516111314Snyan
517111314Snyan  return CommonValue;
518111314Snyan}
519111314Snyan
520111314Snyan/// SimplifyAddInst - Given operands for an Add, see if we can
521111314Snyan/// fold the result.  If not, this returns null.
522111314Snyanstatic Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
523111314Snyan                              const TargetData *TD, const DominatorTree *DT,
524111314Snyan                              unsigned MaxRecurse) {
525111314Snyan  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
526111314Snyan    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
527111314Snyan      Constant *Ops[] = { CLHS, CRHS };
528111314Snyan      return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
529111314Snyan                                      Ops, 2, TD);
530111314Snyan    }
531126708Snyan
532111314Snyan    // Canonicalize the constant to the RHS.
533111314Snyan    std::swap(Op0, Op1);
534111314Snyan  }
535111314Snyan
536111314Snyan  // X + undef -> undef
537111314Snyan  if (match(Op1, m_Undef()))
538111314Snyan    return Op1;
539126708Snyan
540111314Snyan  // X + 0 -> X
541111314Snyan  if (match(Op1, m_Zero()))
542111314Snyan    return Op0;
543111314Snyan
544111314Snyan  // X + (Y - X) -> Y
545126708Snyan  // (Y - X) + X -> Y
546111314Snyan  // Eg: X + -X -> 0
547111314Snyan  Value *Y = 0;
548111314Snyan  if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
549111314Snyan      match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
550111314Snyan    return Y;
551134634Sru
552111314Snyan  // X + ~X -> -1   since   ~X = -X-1
553111314Snyan  if (match(Op0, m_Not(m_Specific(Op1))) ||
554111314Snyan      match(Op1, m_Not(m_Specific(Op0))))
555111314Snyan    return Constant::getAllOnesValue(Op0->getType());
556111314Snyan
557126708Snyan  /// i1 add -> xor.
558111314Snyan  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
559111314Snyan    if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
560125234Snyan      return V;
561111314Snyan
562111314Snyan  // Try some generic simplifications for associative operations.
563111314Snyan  if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
564126708Snyan                                          MaxRecurse))
565111314Snyan    return V;
566111314Snyan
567111314Snyan  // Mul distributes over Add.  Try some generic simplifications based on this.
568111314Snyan  if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
569126708Snyan                                TD, DT, MaxRecurse))
570111314Snyan    return V;
571111314Snyan
572111314Snyan  // Threading Add over selects and phi nodes is pointless, so don't bother.
573111314Snyan  // Threading over the select in "A + select(cond, B, C)" means evaluating
574111314Snyan  // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
575134634Sru  // only if B and C are equal.  If B and C are equal then (since we assume
576111314Snyan  // that operands have already been simplified) "select(cond, B, C)" should
577111314Snyan  // have been simplified to the common value of B and C already.  Analysing
578134634Sru  // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
579111314Snyan  // for threading over phi nodes.
580111314Snyan
581134634Sru  return 0;
582111314Snyan}
583111314Snyan
584111314SnyanValue *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
585111314Snyan                             const TargetData *TD, const DominatorTree *DT) {
586111314Snyan  return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
587134634Sru}
588142783Snyan
589111314Snyan/// SimplifySubInst - Given operands for a Sub, see if we can
590111314Snyan/// fold the result.  If not, this returns null.
591134634Srustatic Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
592111314Snyan                              const TargetData *TD, const DominatorTree *DT,
593111314Snyan                              unsigned MaxRecurse) {
594111314Snyan  if (Constant *CLHS = dyn_cast<Constant>(Op0))
595111314Snyan    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596111314Snyan      Constant *Ops[] = { CLHS, CRHS };
597134634Sru      return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
598142783Snyan                                      Ops, 2, TD);
599111314Snyan    }
600111314Snyan
601134634Sru  // X - undef -> undef
602134634Sru  // undef - X -> undef
603111314Snyan  if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
604111314Snyan    return UndefValue::get(Op0->getType());
605134634Sru
606134634Sru  // X - 0 -> X
607111314Snyan  if (match(Op1, m_Zero()))
608111314Snyan    return Op0;
609111314Snyan
610111314Snyan  // X - X -> 0
611111314Snyan  if (Op0 == Op1)
612111314Snyan    return Constant::getNullValue(Op0->getType());
613111314Snyan
614134634Sru  // (X*2) - X -> X
615134634Sru  // (X<<1) - X -> X
616111314Snyan  Value *X = 0;
617111314Snyan  if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
618134634Sru      match(Op0, m_Shl(m_Specific(Op1), m_One())))
619142783Snyan    return Op1;
620111314Snyan
621111314Snyan  // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
622134634Sru  // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
623111314Snyan  Value *Y = 0, *Z = Op1;
624111314Snyan  if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
625111314Snyan    // See if "V === Y - Z" simplifies.
626111314Snyan    if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
627111314Snyan      // It does!  Now see if "X + V" simplifies.
628124795Snyan      if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
629111314Snyan                                   MaxRecurse-1)) {
630111314Snyan        // It does, we successfully reassociated!
631111314Snyan        ++NumReassoc;
632111314Snyan        return W;
633111314Snyan      }
634111314Snyan    // See if "V === X - Z" simplifies.
635111314Snyan    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
636111314Snyan      // It does!  Now see if "Y + V" simplifies.
637111314Snyan      if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
638111314Snyan                                   MaxRecurse-1)) {
639111314Snyan        // It does, we successfully reassociated!
640111314Snyan        ++NumReassoc;
641111314Snyan        return W;
642111314Snyan      }
643111314Snyan  }
644111314Snyan
645111314Snyan  // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
646111314Snyan  // For example, X - (X + 1) -> -1
647111314Snyan  X = Op0;
648111314Snyan  if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
649111314Snyan    // See if "V === X - Y" simplifies.
650111314Snyan    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
651111314Snyan      // It does!  Now see if "V - Z" simplifies.
652111314Snyan      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
653111314Snyan                                   MaxRecurse-1)) {
654111314Snyan        // It does, we successfully reassociated!
655111314Snyan        ++NumReassoc;
656111314Snyan        return W;
657111314Snyan      }
658111314Snyan    // See if "V === X - Z" simplifies.
659111314Snyan    if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
660111314Snyan      // It does!  Now see if "V - Y" simplifies.
661111314Snyan      if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
662111314Snyan                                   MaxRecurse-1)) {
663111314Snyan        // It does, we successfully reassociated!
664111314Snyan        ++NumReassoc;
665111314Snyan        return W;
666111314Snyan      }
667111314Snyan  }
668111314Snyan
669111314Snyan  // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
670111314Snyan  // For example, X - (X - Y) -> Y.
671111314Snyan  Z = Op0;
672125234Snyan  if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
673125234Snyan    // See if "V === Z - X" simplifies.
674111314Snyan    if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
675111314Snyan      // It does!  Now see if "V + Y" simplifies.
676111314Snyan      if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
677125234Snyan                                   MaxRecurse-1)) {
678111314Snyan        // It does, we successfully reassociated!
679111314Snyan        ++NumReassoc;
680111314Snyan        return W;
681111314Snyan      }
682125234Snyan
683125234Snyan  // Mul distributes over Sub.  Try some generic simplifications based on this.
684111314Snyan  if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
685111314Snyan                                TD, DT, MaxRecurse))
686111314Snyan    return V;
687111314Snyan
688111314Snyan  // i1 sub -> xor.
689111314Snyan  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
690111314Snyan    if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
691111314Snyan      return V;
692111314Snyan
693130596Snyan  // Threading Sub over selects and phi nodes is pointless, so don't bother.
694111314Snyan  // Threading over the select in "A - select(cond, B, C)" means evaluating
695111314Snyan  // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
696111314Snyan  // only if B and C are equal.  If B and C are equal then (since we assume
697111314Snyan  // that operands have already been simplified) "select(cond, B, C)" should
698111314Snyan  // have been simplified to the common value of B and C already.  Analysing
699111314Snyan  // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
700111314Snyan  // for threading over phi nodes.
701111314Snyan
702111314Snyan  return 0;
703111314Snyan}
704111314Snyan
705111314SnyanValue *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
706111314Snyan                             const TargetData *TD, const DominatorTree *DT) {
707111314Snyan  return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
708111314Snyan}
709111314Snyan
710111314Snyan/// SimplifyMulInst - Given operands for a Mul, see if we can
711111314Snyan/// fold the result.  If not, this returns null.
712111314Snyanstatic Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
713111314Snyan                              const DominatorTree *DT, unsigned MaxRecurse) {
714111314Snyan  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
715111314Snyan    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
716111314Snyan      Constant *Ops[] = { CLHS, CRHS };
717111314Snyan      return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
718111314Snyan                                      Ops, 2, TD);
719111314Snyan    }
720111314Snyan
721111314Snyan    // Canonicalize the constant to the RHS.
722111314Snyan    std::swap(Op0, Op1);
723111314Snyan  }
724111314Snyan
725111314Snyan  // X * undef -> 0
726111314Snyan  if (match(Op1, m_Undef()))
727111314Snyan    return Constant::getNullValue(Op0->getType());
728111314Snyan
729111314Snyan  // X * 0 -> 0
730111314Snyan  if (match(Op1, m_Zero()))
731111314Snyan    return Op1;
732111314Snyan
733111314Snyan  // X * 1 -> X
734111314Snyan  if (match(Op1, m_One()))
735111314Snyan    return Op0;
736111314Snyan
737111500Sobrien  // (X / Y) * Y -> X if the division is exact.
738132960Snyan  Value *X = 0, *Y = 0;
739132960Snyan  if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
740132960Snyan      (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
741132960Snyan    BinaryOperator *Div = cast<BinaryOperator>(Y == Op1 ? Op0 : Op1);
742111500Sobrien    if (Div->isExact())
743111500Sobrien      return X;
744111500Sobrien  }
745111500Sobrien
746111500Sobrien  // i1 mul -> and.
747111500Sobrien  if (MaxRecurse && Op0->getType()->isIntegerTy(1))
748111500Sobrien    if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
749116382Snyan      return V;
750116382Snyan
751111500Sobrien  // Try some generic simplifications for associative operations.
752116382Snyan  if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
753116382Snyan                                          MaxRecurse))
754116382Snyan    return V;
755116382Snyan
756111500Sobrien  // Mul distributes over Add.  Try some generic simplifications based on this.
757111500Sobrien  if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
758111500Sobrien                             TD, DT, MaxRecurse))
759111500Sobrien    return V;
760111500Sobrien
761111500Sobrien  // If the operation is with the result of a select instruction, check whether
762111500Sobrien  // operating on either branch of the select always yields the same value.
763111500Sobrien  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
764111500Sobrien    if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
765111500Sobrien                                         MaxRecurse))
766125086Snyan      return V;
767116382Snyan
768116382Snyan  // If the operation is with the result of a phi instruction, check whether
769116382Snyan  // operating on all incoming values of the phi always yields the same value.
770116382Snyan  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
771111500Sobrien    if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
772111500Sobrien                                      MaxRecurse))
773111500Sobrien      return V;
774116382Snyan
775116382Snyan  return 0;
776116382Snyan}
777116382Snyan
778116382SnyanValue *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
779116382Snyan                             const DominatorTree *DT) {
780111582Sru  return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
781111582Sru}
782111582Sru
783111582Sru/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
784111582Sru/// fold the result.  If not, this returns null.
785111582Srustatic Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
786111582Sru                          const TargetData *TD, const DominatorTree *DT,
787111582Sru                          unsigned MaxRecurse) {
788111582Sru  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
789111582Sru    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
790111582Sru      Constant *Ops[] = { C0, C1 };
791111582Sru      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
792116382Snyan    }
793116382Snyan  }
794116382Snyan
795116382Snyan  bool isSigned = Opcode == Instruction::SDiv;
796111582Sru
797111582Sru  // X / undef -> undef
798111582Sru  if (match(Op1, m_Undef()))
799116382Snyan    return Op1;
800116382Snyan
801111582Sru  // undef / X -> 0
802111582Sru  if (match(Op0, m_Undef()))
803111582Sru    return Constant::getNullValue(Op0->getType());
804111582Sru
805111582Sru  // 0 / X -> 0, we don't need to preserve faults!
806111582Sru  if (match(Op0, m_Zero()))
807    return Op0;
808
809  // X / 1 -> X
810  if (match(Op1, m_One()))
811    return Op0;
812
813  if (Op0->getType()->isIntegerTy(1))
814    // It can't be division by zero, hence it must be division by one.
815    return Op0;
816
817  // X / X -> 1
818  if (Op0 == Op1)
819    return ConstantInt::get(Op0->getType(), 1);
820
821  // (X * Y) / Y -> X if the multiplication does not overflow.
822  Value *X = 0, *Y = 0;
823  if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
824    if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
825    BinaryOperator *Mul = cast<BinaryOperator>(Op0);
826    // If the Mul knows it does not overflow, then we are good to go.
827    if ((isSigned && Mul->hasNoSignedWrap()) ||
828        (!isSigned && Mul->hasNoUnsignedWrap()))
829      return X;
830    // If X has the form X = A / Y then X * Y cannot overflow.
831    if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
832      if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
833        return X;
834  }
835
836  // (X rem Y) / Y -> 0
837  if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
838      (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
839    return Constant::getNullValue(Op0->getType());
840
841  // If the operation is with the result of a select instruction, check whether
842  // operating on either branch of the select always yields the same value.
843  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
844    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
845      return V;
846
847  // If the operation is with the result of a phi instruction, check whether
848  // operating on all incoming values of the phi always yields the same value.
849  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
850    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
851      return V;
852
853  return 0;
854}
855
856/// SimplifySDivInst - Given operands for an SDiv, see if we can
857/// fold the result.  If not, this returns null.
858static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
859                               const DominatorTree *DT, unsigned MaxRecurse) {
860  if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
861    return V;
862
863  return 0;
864}
865
866Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
867                              const DominatorTree *DT) {
868  return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
869}
870
871/// SimplifyUDivInst - Given operands for a UDiv, see if we can
872/// fold the result.  If not, this returns null.
873static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
874                               const DominatorTree *DT, unsigned MaxRecurse) {
875  if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
876    return V;
877
878  return 0;
879}
880
881Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
882                              const DominatorTree *DT) {
883  return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
884}
885
886static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
887                               const DominatorTree *, unsigned) {
888  // undef / X -> undef    (the undef could be a snan).
889  if (match(Op0, m_Undef()))
890    return Op0;
891
892  // X / undef -> undef
893  if (match(Op1, m_Undef()))
894    return Op1;
895
896  return 0;
897}
898
899Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
900                              const DominatorTree *DT) {
901  return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
902}
903
904/// SimplifyRem - Given operands for an SRem or URem, see if we can
905/// fold the result.  If not, this returns null.
906static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
907                          const TargetData *TD, const DominatorTree *DT,
908                          unsigned MaxRecurse) {
909  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
910    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
911      Constant *Ops[] = { C0, C1 };
912      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
913    }
914  }
915
916  // X % undef -> undef
917  if (match(Op1, m_Undef()))
918    return Op1;
919
920  // undef % X -> 0
921  if (match(Op0, m_Undef()))
922    return Constant::getNullValue(Op0->getType());
923
924  // 0 % X -> 0, we don't need to preserve faults!
925  if (match(Op0, m_Zero()))
926    return Op0;
927
928  // X % 0 -> undef, we don't need to preserve faults!
929  if (match(Op1, m_Zero()))
930    return UndefValue::get(Op0->getType());
931
932  // X % 1 -> 0
933  if (match(Op1, m_One()))
934    return Constant::getNullValue(Op0->getType());
935
936  if (Op0->getType()->isIntegerTy(1))
937    // It can't be remainder by zero, hence it must be remainder by one.
938    return Constant::getNullValue(Op0->getType());
939
940  // X % X -> 0
941  if (Op0 == Op1)
942    return Constant::getNullValue(Op0->getType());
943
944  // If the operation is with the result of a select instruction, check whether
945  // operating on either branch of the select always yields the same value.
946  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
947    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
948      return V;
949
950  // If the operation is with the result of a phi instruction, check whether
951  // operating on all incoming values of the phi always yields the same value.
952  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
953    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
954      return V;
955
956  return 0;
957}
958
959/// SimplifySRemInst - Given operands for an SRem, see if we can
960/// fold the result.  If not, this returns null.
961static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
962                               const DominatorTree *DT, unsigned MaxRecurse) {
963  if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
964    return V;
965
966  return 0;
967}
968
969Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
970                              const DominatorTree *DT) {
971  return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
972}
973
974/// SimplifyURemInst - Given operands for a URem, see if we can
975/// fold the result.  If not, this returns null.
976static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
977                               const DominatorTree *DT, unsigned MaxRecurse) {
978  if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
979    return V;
980
981  return 0;
982}
983
984Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
985                              const DominatorTree *DT) {
986  return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
987}
988
989static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
990                               const DominatorTree *, unsigned) {
991  // undef % X -> undef    (the undef could be a snan).
992  if (match(Op0, m_Undef()))
993    return Op0;
994
995  // X % undef -> undef
996  if (match(Op1, m_Undef()))
997    return Op1;
998
999  return 0;
1000}
1001
1002Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1003                              const DominatorTree *DT) {
1004  return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1005}
1006
1007/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1008/// fold the result.  If not, this returns null.
1009static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1010                            const TargetData *TD, const DominatorTree *DT,
1011                            unsigned MaxRecurse) {
1012  if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1013    if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1014      Constant *Ops[] = { C0, C1 };
1015      return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
1016    }
1017  }
1018
1019  // 0 shift by X -> 0
1020  if (match(Op0, m_Zero()))
1021    return Op0;
1022
1023  // X shift by 0 -> X
1024  if (match(Op1, m_Zero()))
1025    return Op0;
1026
1027  // X shift by undef -> undef because it may shift by the bitwidth.
1028  if (match(Op1, m_Undef()))
1029    return Op1;
1030
1031  // Shifting by the bitwidth or more is undefined.
1032  if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1033    if (CI->getValue().getLimitedValue() >=
1034        Op0->getType()->getScalarSizeInBits())
1035      return UndefValue::get(Op0->getType());
1036
1037  // If the operation is with the result of a select instruction, check whether
1038  // operating on either branch of the select always yields the same value.
1039  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1040    if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1041      return V;
1042
1043  // If the operation is with the result of a phi instruction, check whether
1044  // operating on all incoming values of the phi always yields the same value.
1045  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1046    if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1047      return V;
1048
1049  return 0;
1050}
1051
1052/// SimplifyShlInst - Given operands for an Shl, see if we can
1053/// fold the result.  If not, this returns null.
1054static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1055                              const TargetData *TD, const DominatorTree *DT,
1056                              unsigned MaxRecurse) {
1057  if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1058    return V;
1059
1060  // undef << X -> 0
1061  if (match(Op0, m_Undef()))
1062    return Constant::getNullValue(Op0->getType());
1063
1064  // (X >> A) << A -> X
1065  Value *X;
1066  if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1067      cast<PossiblyExactOperator>(Op0)->isExact())
1068    return X;
1069  return 0;
1070}
1071
1072Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1073                             const TargetData *TD, const DominatorTree *DT) {
1074  return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
1075}
1076
1077/// SimplifyLShrInst - Given operands for an LShr, see if we can
1078/// fold the result.  If not, this returns null.
1079static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1080                               const TargetData *TD, const DominatorTree *DT,
1081                               unsigned MaxRecurse) {
1082  if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1083    return V;
1084
1085  // undef >>l X -> 0
1086  if (match(Op0, m_Undef()))
1087    return Constant::getNullValue(Op0->getType());
1088
1089  // (X << A) >> A -> X
1090  Value *X;
1091  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1092      cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1093    return X;
1094
1095  return 0;
1096}
1097
1098Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1099                              const TargetData *TD, const DominatorTree *DT) {
1100  return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1101}
1102
1103/// SimplifyAShrInst - Given operands for an AShr, see if we can
1104/// fold the result.  If not, this returns null.
1105static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1106                               const TargetData *TD, const DominatorTree *DT,
1107                               unsigned MaxRecurse) {
1108  if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1109    return V;
1110
1111  // all ones >>a X -> all ones
1112  if (match(Op0, m_AllOnes()))
1113    return Op0;
1114
1115  // undef >>a X -> all ones
1116  if (match(Op0, m_Undef()))
1117    return Constant::getAllOnesValue(Op0->getType());
1118
1119  // (X << A) >> A -> X
1120  Value *X;
1121  if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1122      cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1123    return X;
1124
1125  return 0;
1126}
1127
1128Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1129                              const TargetData *TD, const DominatorTree *DT) {
1130  return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1131}
1132
1133/// SimplifyAndInst - Given operands for an And, see if we can
1134/// fold the result.  If not, this returns null.
1135static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1136                              const DominatorTree *DT, unsigned MaxRecurse) {
1137  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1138    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1139      Constant *Ops[] = { CLHS, CRHS };
1140      return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1141                                      Ops, 2, TD);
1142    }
1143
1144    // Canonicalize the constant to the RHS.
1145    std::swap(Op0, Op1);
1146  }
1147
1148  // X & undef -> 0
1149  if (match(Op1, m_Undef()))
1150    return Constant::getNullValue(Op0->getType());
1151
1152  // X & X = X
1153  if (Op0 == Op1)
1154    return Op0;
1155
1156  // X & 0 = 0
1157  if (match(Op1, m_Zero()))
1158    return Op1;
1159
1160  // X & -1 = X
1161  if (match(Op1, m_AllOnes()))
1162    return Op0;
1163
1164  // A & ~A  =  ~A & A  =  0
1165  if (match(Op0, m_Not(m_Specific(Op1))) ||
1166      match(Op1, m_Not(m_Specific(Op0))))
1167    return Constant::getNullValue(Op0->getType());
1168
1169  // (A | ?) & A = A
1170  Value *A = 0, *B = 0;
1171  if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1172      (A == Op1 || B == Op1))
1173    return Op1;
1174
1175  // A & (A | ?) = A
1176  if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1177      (A == Op0 || B == Op0))
1178    return Op0;
1179
1180  // Try some generic simplifications for associative operations.
1181  if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1182                                          MaxRecurse))
1183    return V;
1184
1185  // And distributes over Or.  Try some generic simplifications based on this.
1186  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1187                             TD, DT, MaxRecurse))
1188    return V;
1189
1190  // And distributes over Xor.  Try some generic simplifications based on this.
1191  if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1192                             TD, DT, MaxRecurse))
1193    return V;
1194
1195  // Or distributes over And.  Try some generic simplifications based on this.
1196  if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1197                                TD, DT, MaxRecurse))
1198    return V;
1199
1200  // If the operation is with the result of a select instruction, check whether
1201  // operating on either branch of the select always yields the same value.
1202  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1203    if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
1204                                         MaxRecurse))
1205      return V;
1206
1207  // If the operation is with the result of a phi instruction, check whether
1208  // operating on all incoming values of the phi always yields the same value.
1209  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1210    if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
1211                                      MaxRecurse))
1212      return V;
1213
1214  return 0;
1215}
1216
1217Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1218                             const DominatorTree *DT) {
1219  return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
1220}
1221
1222/// SimplifyOrInst - Given operands for an Or, see if we can
1223/// fold the result.  If not, this returns null.
1224static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1225                             const DominatorTree *DT, unsigned MaxRecurse) {
1226  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1227    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1228      Constant *Ops[] = { CLHS, CRHS };
1229      return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1230                                      Ops, 2, TD);
1231    }
1232
1233    // Canonicalize the constant to the RHS.
1234    std::swap(Op0, Op1);
1235  }
1236
1237  // X | undef -> -1
1238  if (match(Op1, m_Undef()))
1239    return Constant::getAllOnesValue(Op0->getType());
1240
1241  // X | X = X
1242  if (Op0 == Op1)
1243    return Op0;
1244
1245  // X | 0 = X
1246  if (match(Op1, m_Zero()))
1247    return Op0;
1248
1249  // X | -1 = -1
1250  if (match(Op1, m_AllOnes()))
1251    return Op1;
1252
1253  // A | ~A  =  ~A | A  =  -1
1254  if (match(Op0, m_Not(m_Specific(Op1))) ||
1255      match(Op1, m_Not(m_Specific(Op0))))
1256    return Constant::getAllOnesValue(Op0->getType());
1257
1258  // (A & ?) | A = A
1259  Value *A = 0, *B = 0;
1260  if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1261      (A == Op1 || B == Op1))
1262    return Op1;
1263
1264  // A | (A & ?) = A
1265  if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1266      (A == Op0 || B == Op0))
1267    return Op0;
1268
1269  // ~(A & ?) | A = -1
1270  if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1271      (A == Op1 || B == Op1))
1272    return Constant::getAllOnesValue(Op1->getType());
1273
1274  // A | ~(A & ?) = -1
1275  if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1276      (A == Op0 || B == Op0))
1277    return Constant::getAllOnesValue(Op0->getType());
1278
1279  // Try some generic simplifications for associative operations.
1280  if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1281                                          MaxRecurse))
1282    return V;
1283
1284  // Or distributes over And.  Try some generic simplifications based on this.
1285  if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1286                             TD, DT, MaxRecurse))
1287    return V;
1288
1289  // And distributes over Or.  Try some generic simplifications based on this.
1290  if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1291                                TD, DT, MaxRecurse))
1292    return V;
1293
1294  // If the operation is with the result of a select instruction, check whether
1295  // operating on either branch of the select always yields the same value.
1296  if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1297    if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
1298                                         MaxRecurse))
1299      return V;
1300
1301  // If the operation is with the result of a phi instruction, check whether
1302  // operating on all incoming values of the phi always yields the same value.
1303  if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1304    if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
1305                                      MaxRecurse))
1306      return V;
1307
1308  return 0;
1309}
1310
1311Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1312                            const DominatorTree *DT) {
1313  return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
1314}
1315
1316/// SimplifyXorInst - Given operands for a Xor, see if we can
1317/// fold the result.  If not, this returns null.
1318static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1319                              const DominatorTree *DT, unsigned MaxRecurse) {
1320  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1321    if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1322      Constant *Ops[] = { CLHS, CRHS };
1323      return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1324                                      Ops, 2, TD);
1325    }
1326
1327    // Canonicalize the constant to the RHS.
1328    std::swap(Op0, Op1);
1329  }
1330
1331  // A ^ undef -> undef
1332  if (match(Op1, m_Undef()))
1333    return Op1;
1334
1335  // A ^ 0 = A
1336  if (match(Op1, m_Zero()))
1337    return Op0;
1338
1339  // A ^ A = 0
1340  if (Op0 == Op1)
1341    return Constant::getNullValue(Op0->getType());
1342
1343  // A ^ ~A  =  ~A ^ A  =  -1
1344  if (match(Op0, m_Not(m_Specific(Op1))) ||
1345      match(Op1, m_Not(m_Specific(Op0))))
1346    return Constant::getAllOnesValue(Op0->getType());
1347
1348  // Try some generic simplifications for associative operations.
1349  if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1350                                          MaxRecurse))
1351    return V;
1352
1353  // And distributes over Xor.  Try some generic simplifications based on this.
1354  if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1355                                TD, DT, MaxRecurse))
1356    return V;
1357
1358  // Threading Xor over selects and phi nodes is pointless, so don't bother.
1359  // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1360  // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1361  // only if B and C are equal.  If B and C are equal then (since we assume
1362  // that operands have already been simplified) "select(cond, B, C)" should
1363  // have been simplified to the common value of B and C already.  Analysing
1364  // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1365  // for threading over phi nodes.
1366
1367  return 0;
1368}
1369
1370Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1371                             const DominatorTree *DT) {
1372  return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1373}
1374
1375static const Type *GetCompareTy(Value *Op) {
1376  return CmpInst::makeCmpResultType(Op->getType());
1377}
1378
1379/// ExtractEquivalentCondition - Rummage around inside V looking for something
1380/// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1381/// otherwise return null.  Helper function for analyzing max/min idioms.
1382static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1383                                         Value *LHS, Value *RHS) {
1384  SelectInst *SI = dyn_cast<SelectInst>(V);
1385  if (!SI)
1386    return 0;
1387  CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1388  if (!Cmp)
1389    return 0;
1390  Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1391  if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1392    return Cmp;
1393  if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1394      LHS == CmpRHS && RHS == CmpLHS)
1395    return Cmp;
1396  return 0;
1397}
1398
1399/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1400/// fold the result.  If not, this returns null.
1401static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1402                               const TargetData *TD, const DominatorTree *DT,
1403                               unsigned MaxRecurse) {
1404  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1405  assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1406
1407  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1408    if (Constant *CRHS = dyn_cast<Constant>(RHS))
1409      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1410
1411    // If we have a constant, make sure it is on the RHS.
1412    std::swap(LHS, RHS);
1413    Pred = CmpInst::getSwappedPredicate(Pred);
1414  }
1415
1416  const Type *ITy = GetCompareTy(LHS); // The return type.
1417  const Type *OpTy = LHS->getType();   // The operand type.
1418
1419  // icmp X, X -> true/false
1420  // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1421  // because X could be 0.
1422  if (LHS == RHS || isa<UndefValue>(RHS))
1423    return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1424
1425  // Special case logic when the operands have i1 type.
1426  if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1427       cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1428    switch (Pred) {
1429    default: break;
1430    case ICmpInst::ICMP_EQ:
1431      // X == 1 -> X
1432      if (match(RHS, m_One()))
1433        return LHS;
1434      break;
1435    case ICmpInst::ICMP_NE:
1436      // X != 0 -> X
1437      if (match(RHS, m_Zero()))
1438        return LHS;
1439      break;
1440    case ICmpInst::ICMP_UGT:
1441      // X >u 0 -> X
1442      if (match(RHS, m_Zero()))
1443        return LHS;
1444      break;
1445    case ICmpInst::ICMP_UGE:
1446      // X >=u 1 -> X
1447      if (match(RHS, m_One()))
1448        return LHS;
1449      break;
1450    case ICmpInst::ICMP_SLT:
1451      // X <s 0 -> X
1452      if (match(RHS, m_Zero()))
1453        return LHS;
1454      break;
1455    case ICmpInst::ICMP_SLE:
1456      // X <=s -1 -> X
1457      if (match(RHS, m_One()))
1458        return LHS;
1459      break;
1460    }
1461  }
1462
1463  // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1464  // different addresses, and what's more the address of a stack variable is
1465  // never null or equal to the address of a global.  Note that generalizing
1466  // to the case where LHS is a global variable address or null is pointless,
1467  // since if both LHS and RHS are constants then we already constant folded
1468  // the compare, and if only one of them is then we moved it to RHS already.
1469  if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1470                               isa<ConstantPointerNull>(RHS)))
1471    // We already know that LHS != RHS.
1472    return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1473
1474  // If we are comparing with zero then try hard since this is a common case.
1475  if (match(RHS, m_Zero())) {
1476    bool LHSKnownNonNegative, LHSKnownNegative;
1477    switch (Pred) {
1478    default:
1479      assert(false && "Unknown ICmp predicate!");
1480    case ICmpInst::ICMP_ULT:
1481      // getNullValue also works for vectors, unlike getFalse.
1482      return Constant::getNullValue(ITy);
1483    case ICmpInst::ICMP_UGE:
1484      // getAllOnesValue also works for vectors, unlike getTrue.
1485      return ConstantInt::getAllOnesValue(ITy);
1486    case ICmpInst::ICMP_EQ:
1487    case ICmpInst::ICMP_ULE:
1488      if (isKnownNonZero(LHS, TD))
1489        return Constant::getNullValue(ITy);
1490      break;
1491    case ICmpInst::ICMP_NE:
1492    case ICmpInst::ICMP_UGT:
1493      if (isKnownNonZero(LHS, TD))
1494        return ConstantInt::getAllOnesValue(ITy);
1495      break;
1496    case ICmpInst::ICMP_SLT:
1497      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1498      if (LHSKnownNegative)
1499        return ConstantInt::getAllOnesValue(ITy);
1500      if (LHSKnownNonNegative)
1501        return Constant::getNullValue(ITy);
1502      break;
1503    case ICmpInst::ICMP_SLE:
1504      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1505      if (LHSKnownNegative)
1506        return ConstantInt::getAllOnesValue(ITy);
1507      if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1508        return Constant::getNullValue(ITy);
1509      break;
1510    case ICmpInst::ICMP_SGE:
1511      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1512      if (LHSKnownNegative)
1513        return Constant::getNullValue(ITy);
1514      if (LHSKnownNonNegative)
1515        return ConstantInt::getAllOnesValue(ITy);
1516      break;
1517    case ICmpInst::ICMP_SGT:
1518      ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1519      if (LHSKnownNegative)
1520        return Constant::getNullValue(ITy);
1521      if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1522        return ConstantInt::getAllOnesValue(ITy);
1523      break;
1524    }
1525  }
1526
1527  // See if we are doing a comparison with a constant integer.
1528  if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1529    // Rule out tautological comparisons (eg., ult 0 or uge 0).
1530    ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1531    if (RHS_CR.isEmptySet())
1532      return ConstantInt::getFalse(CI->getContext());
1533    if (RHS_CR.isFullSet())
1534      return ConstantInt::getTrue(CI->getContext());
1535
1536    // Many binary operators with constant RHS have easy to compute constant
1537    // range.  Use them to check whether the comparison is a tautology.
1538    uint32_t Width = CI->getBitWidth();
1539    APInt Lower = APInt(Width, 0);
1540    APInt Upper = APInt(Width, 0);
1541    ConstantInt *CI2;
1542    if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1543      // 'urem x, CI2' produces [0, CI2).
1544      Upper = CI2->getValue();
1545    } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1546      // 'srem x, CI2' produces (-|CI2|, |CI2|).
1547      Upper = CI2->getValue().abs();
1548      Lower = (-Upper) + 1;
1549    } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1550      // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1551      APInt NegOne = APInt::getAllOnesValue(Width);
1552      if (!CI2->isZero())
1553        Upper = NegOne.udiv(CI2->getValue()) + 1;
1554    } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1555      // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1556      APInt IntMin = APInt::getSignedMinValue(Width);
1557      APInt IntMax = APInt::getSignedMaxValue(Width);
1558      APInt Val = CI2->getValue().abs();
1559      if (!Val.isMinValue()) {
1560        Lower = IntMin.sdiv(Val);
1561        Upper = IntMax.sdiv(Val) + 1;
1562      }
1563    } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1564      // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1565      APInt NegOne = APInt::getAllOnesValue(Width);
1566      if (CI2->getValue().ult(Width))
1567        Upper = NegOne.lshr(CI2->getValue()) + 1;
1568    } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1569      // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1570      APInt IntMin = APInt::getSignedMinValue(Width);
1571      APInt IntMax = APInt::getSignedMaxValue(Width);
1572      if (CI2->getValue().ult(Width)) {
1573        Lower = IntMin.ashr(CI2->getValue());
1574        Upper = IntMax.ashr(CI2->getValue()) + 1;
1575      }
1576    } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1577      // 'or x, CI2' produces [CI2, UINT_MAX].
1578      Lower = CI2->getValue();
1579    } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1580      // 'and x, CI2' produces [0, CI2].
1581      Upper = CI2->getValue() + 1;
1582    }
1583    if (Lower != Upper) {
1584      ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1585      if (RHS_CR.contains(LHS_CR))
1586        return ConstantInt::getTrue(RHS->getContext());
1587      if (RHS_CR.inverse().contains(LHS_CR))
1588        return ConstantInt::getFalse(RHS->getContext());
1589    }
1590  }
1591
1592  // Compare of cast, for example (zext X) != 0 -> X != 0
1593  if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1594    Instruction *LI = cast<CastInst>(LHS);
1595    Value *SrcOp = LI->getOperand(0);
1596    const Type *SrcTy = SrcOp->getType();
1597    const Type *DstTy = LI->getType();
1598
1599    // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1600    // if the integer type is the same size as the pointer type.
1601    if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1602        TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1603      if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1604        // Transfer the cast to the constant.
1605        if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1606                                        ConstantExpr::getIntToPtr(RHSC, SrcTy),
1607                                        TD, DT, MaxRecurse-1))
1608          return V;
1609      } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1610        if (RI->getOperand(0)->getType() == SrcTy)
1611          // Compare without the cast.
1612          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1613                                          TD, DT, MaxRecurse-1))
1614            return V;
1615      }
1616    }
1617
1618    if (isa<ZExtInst>(LHS)) {
1619      // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1620      // same type.
1621      if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1622        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1623          // Compare X and Y.  Note that signed predicates become unsigned.
1624          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1625                                          SrcOp, RI->getOperand(0), TD, DT,
1626                                          MaxRecurse-1))
1627            return V;
1628      }
1629      // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1630      // too.  If not, then try to deduce the result of the comparison.
1631      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1632        // Compute the constant that would happen if we truncated to SrcTy then
1633        // reextended to DstTy.
1634        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1635        Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1636
1637        // If the re-extended constant didn't change then this is effectively
1638        // also a case of comparing two zero-extended values.
1639        if (RExt == CI && MaxRecurse)
1640          if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1641                                          SrcOp, Trunc, TD, DT, MaxRecurse-1))
1642            return V;
1643
1644        // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1645        // there.  Use this to work out the result of the comparison.
1646        if (RExt != CI) {
1647          switch (Pred) {
1648          default:
1649            assert(false && "Unknown ICmp predicate!");
1650          // LHS <u RHS.
1651          case ICmpInst::ICMP_EQ:
1652          case ICmpInst::ICMP_UGT:
1653          case ICmpInst::ICMP_UGE:
1654            return ConstantInt::getFalse(CI->getContext());
1655
1656          case ICmpInst::ICMP_NE:
1657          case ICmpInst::ICMP_ULT:
1658          case ICmpInst::ICMP_ULE:
1659            return ConstantInt::getTrue(CI->getContext());
1660
1661          // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
1662          // is non-negative then LHS <s RHS.
1663          case ICmpInst::ICMP_SGT:
1664          case ICmpInst::ICMP_SGE:
1665            return CI->getValue().isNegative() ?
1666              ConstantInt::getTrue(CI->getContext()) :
1667              ConstantInt::getFalse(CI->getContext());
1668
1669          case ICmpInst::ICMP_SLT:
1670          case ICmpInst::ICMP_SLE:
1671            return CI->getValue().isNegative() ?
1672              ConstantInt::getFalse(CI->getContext()) :
1673              ConstantInt::getTrue(CI->getContext());
1674          }
1675        }
1676      }
1677    }
1678
1679    if (isa<SExtInst>(LHS)) {
1680      // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1681      // same type.
1682      if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1683        if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1684          // Compare X and Y.  Note that the predicate does not change.
1685          if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1686                                          TD, DT, MaxRecurse-1))
1687            return V;
1688      }
1689      // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1690      // too.  If not, then try to deduce the result of the comparison.
1691      else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1692        // Compute the constant that would happen if we truncated to SrcTy then
1693        // reextended to DstTy.
1694        Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1695        Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1696
1697        // If the re-extended constant didn't change then this is effectively
1698        // also a case of comparing two sign-extended values.
1699        if (RExt == CI && MaxRecurse)
1700          if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1701                                          MaxRecurse-1))
1702            return V;
1703
1704        // Otherwise the upper bits of LHS are all equal, while RHS has varying
1705        // bits there.  Use this to work out the result of the comparison.
1706        if (RExt != CI) {
1707          switch (Pred) {
1708          default:
1709            assert(false && "Unknown ICmp predicate!");
1710          case ICmpInst::ICMP_EQ:
1711            return ConstantInt::getFalse(CI->getContext());
1712          case ICmpInst::ICMP_NE:
1713            return ConstantInt::getTrue(CI->getContext());
1714
1715          // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
1716          // LHS >s RHS.
1717          case ICmpInst::ICMP_SGT:
1718          case ICmpInst::ICMP_SGE:
1719            return CI->getValue().isNegative() ?
1720              ConstantInt::getTrue(CI->getContext()) :
1721              ConstantInt::getFalse(CI->getContext());
1722          case ICmpInst::ICMP_SLT:
1723          case ICmpInst::ICMP_SLE:
1724            return CI->getValue().isNegative() ?
1725              ConstantInt::getFalse(CI->getContext()) :
1726              ConstantInt::getTrue(CI->getContext());
1727
1728          // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
1729          // LHS >u RHS.
1730          case ICmpInst::ICMP_UGT:
1731          case ICmpInst::ICMP_UGE:
1732            // Comparison is true iff the LHS <s 0.
1733            if (MaxRecurse)
1734              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1735                                              Constant::getNullValue(SrcTy),
1736                                              TD, DT, MaxRecurse-1))
1737                return V;
1738            break;
1739          case ICmpInst::ICMP_ULT:
1740          case ICmpInst::ICMP_ULE:
1741            // Comparison is true iff the LHS >=s 0.
1742            if (MaxRecurse)
1743              if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1744                                              Constant::getNullValue(SrcTy),
1745                                              TD, DT, MaxRecurse-1))
1746                return V;
1747            break;
1748          }
1749        }
1750      }
1751    }
1752  }
1753
1754  // Special logic for binary operators.
1755  BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1756  BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1757  if (MaxRecurse && (LBO || RBO)) {
1758    // Analyze the case when either LHS or RHS is an add instruction.
1759    Value *A = 0, *B = 0, *C = 0, *D = 0;
1760    // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1761    bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1762    if (LBO && LBO->getOpcode() == Instruction::Add) {
1763      A = LBO->getOperand(0); B = LBO->getOperand(1);
1764      NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1765        (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1766        (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1767    }
1768    if (RBO && RBO->getOpcode() == Instruction::Add) {
1769      C = RBO->getOperand(0); D = RBO->getOperand(1);
1770      NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1771        (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1772        (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1773    }
1774
1775    // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1776    if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1777      if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1778                                      Constant::getNullValue(RHS->getType()),
1779                                      TD, DT, MaxRecurse-1))
1780        return V;
1781
1782    // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1783    if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1784      if (Value *V = SimplifyICmpInst(Pred,
1785                                      Constant::getNullValue(LHS->getType()),
1786                                      C == LHS ? D : C, TD, DT, MaxRecurse-1))
1787        return V;
1788
1789    // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1790    if (A && C && (A == C || A == D || B == C || B == D) &&
1791        NoLHSWrapProblem && NoRHSWrapProblem) {
1792      // Determine Y and Z in the form icmp (X+Y), (X+Z).
1793      Value *Y = (A == C || A == D) ? B : A;
1794      Value *Z = (C == A || C == B) ? D : C;
1795      if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1796        return V;
1797    }
1798  }
1799
1800  if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1801    bool KnownNonNegative, KnownNegative;
1802    switch (Pred) {
1803    default:
1804      break;
1805    case ICmpInst::ICMP_SGT:
1806    case ICmpInst::ICMP_SGE:
1807      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1808      if (!KnownNonNegative)
1809        break;
1810      // fall-through
1811    case ICmpInst::ICMP_EQ:
1812    case ICmpInst::ICMP_UGT:
1813    case ICmpInst::ICMP_UGE:
1814      // getNullValue also works for vectors, unlike getFalse.
1815      return Constant::getNullValue(ITy);
1816    case ICmpInst::ICMP_SLT:
1817    case ICmpInst::ICMP_SLE:
1818      ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1819      if (!KnownNonNegative)
1820        break;
1821      // fall-through
1822    case ICmpInst::ICMP_NE:
1823    case ICmpInst::ICMP_ULT:
1824    case ICmpInst::ICMP_ULE:
1825      // getAllOnesValue also works for vectors, unlike getTrue.
1826      return Constant::getAllOnesValue(ITy);
1827    }
1828  }
1829  if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1830    bool KnownNonNegative, KnownNegative;
1831    switch (Pred) {
1832    default:
1833      break;
1834    case ICmpInst::ICMP_SGT:
1835    case ICmpInst::ICMP_SGE:
1836      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1837      if (!KnownNonNegative)
1838        break;
1839      // fall-through
1840    case ICmpInst::ICMP_NE:
1841    case ICmpInst::ICMP_UGT:
1842    case ICmpInst::ICMP_UGE:
1843      // getAllOnesValue also works for vectors, unlike getTrue.
1844      return Constant::getAllOnesValue(ITy);
1845    case ICmpInst::ICMP_SLT:
1846    case ICmpInst::ICMP_SLE:
1847      ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1848      if (!KnownNonNegative)
1849        break;
1850      // fall-through
1851    case ICmpInst::ICMP_EQ:
1852    case ICmpInst::ICMP_ULT:
1853    case ICmpInst::ICMP_ULE:
1854      // getNullValue also works for vectors, unlike getFalse.
1855      return Constant::getNullValue(ITy);
1856    }
1857  }
1858
1859  if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1860      LBO->getOperand(1) == RBO->getOperand(1)) {
1861    switch (LBO->getOpcode()) {
1862    default: break;
1863    case Instruction::UDiv:
1864    case Instruction::LShr:
1865      if (ICmpInst::isSigned(Pred))
1866        break;
1867      // fall-through
1868    case Instruction::SDiv:
1869    case Instruction::AShr:
1870      if (!LBO->isExact() || !RBO->isExact())
1871        break;
1872      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1873                                      RBO->getOperand(0), TD, DT, MaxRecurse-1))
1874        return V;
1875      break;
1876    case Instruction::Shl: {
1877      bool NUW = LBO->hasNoUnsignedWrap() && LBO->hasNoUnsignedWrap();
1878      bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1879      if (!NUW && !NSW)
1880        break;
1881      if (!NSW && ICmpInst::isSigned(Pred))
1882        break;
1883      if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1884                                      RBO->getOperand(0), TD, DT, MaxRecurse-1))
1885        return V;
1886      break;
1887    }
1888    }
1889  }
1890
1891  // Simplify comparisons involving max/min.
1892  Value *A, *B;
1893  CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1894  CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1895
1896  // Signed variants on "max(a,b)>=a -> true".
1897  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1898    if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1899    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1900    // We analyze this as smax(A, B) pred A.
1901    P = Pred;
1902  } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1903             (A == LHS || B == LHS)) {
1904    if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1905    EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1906    // We analyze this as smax(A, B) swapped-pred A.
1907    P = CmpInst::getSwappedPredicate(Pred);
1908  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1909             (A == RHS || B == RHS)) {
1910    if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1911    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1912    // We analyze this as smax(-A, -B) swapped-pred -A.
1913    // Note that we do not need to actually form -A or -B thanks to EqP.
1914    P = CmpInst::getSwappedPredicate(Pred);
1915  } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1916             (A == LHS || B == LHS)) {
1917    if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1918    EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1919    // We analyze this as smax(-A, -B) pred -A.
1920    // Note that we do not need to actually form -A or -B thanks to EqP.
1921    P = Pred;
1922  }
1923  if (P != CmpInst::BAD_ICMP_PREDICATE) {
1924    // Cases correspond to "max(A, B) p A".
1925    switch (P) {
1926    default:
1927      break;
1928    case CmpInst::ICMP_EQ:
1929    case CmpInst::ICMP_SLE:
1930      // Equivalent to "A EqP B".  This may be the same as the condition tested
1931      // in the max/min; if so, we can just return that.
1932      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
1933        return V;
1934      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
1935        return V;
1936      // Otherwise, see if "A EqP B" simplifies.
1937      if (MaxRecurse)
1938        if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
1939          return V;
1940      break;
1941    case CmpInst::ICMP_NE:
1942    case CmpInst::ICMP_SGT: {
1943      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
1944      // Equivalent to "A InvEqP B".  This may be the same as the condition
1945      // tested in the max/min; if so, we can just return that.
1946      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
1947        return V;
1948      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
1949        return V;
1950      // Otherwise, see if "A InvEqP B" simplifies.
1951      if (MaxRecurse)
1952        if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
1953          return V;
1954      break;
1955    }
1956    case CmpInst::ICMP_SGE:
1957      // Always true.
1958      return Constant::getAllOnesValue(ITy);
1959    case CmpInst::ICMP_SLT:
1960      // Always false.
1961      return Constant::getNullValue(ITy);
1962    }
1963  }
1964
1965  // Unsigned variants on "max(a,b)>=a -> true".
1966  P = CmpInst::BAD_ICMP_PREDICATE;
1967  if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1968    if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
1969    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1970    // We analyze this as umax(A, B) pred A.
1971    P = Pred;
1972  } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
1973             (A == LHS || B == LHS)) {
1974    if (A != LHS) std::swap(A, B); // A pred umax(A, B).
1975    EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1976    // We analyze this as umax(A, B) swapped-pred A.
1977    P = CmpInst::getSwappedPredicate(Pred);
1978  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
1979             (A == RHS || B == RHS)) {
1980    if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
1981    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
1982    // We analyze this as umax(-A, -B) swapped-pred -A.
1983    // Note that we do not need to actually form -A or -B thanks to EqP.
1984    P = CmpInst::getSwappedPredicate(Pred);
1985  } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
1986             (A == LHS || B == LHS)) {
1987    if (A != LHS) std::swap(A, B); // A pred umin(A, B).
1988    EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
1989    // We analyze this as umax(-A, -B) pred -A.
1990    // Note that we do not need to actually form -A or -B thanks to EqP.
1991    P = Pred;
1992  }
1993  if (P != CmpInst::BAD_ICMP_PREDICATE) {
1994    // Cases correspond to "max(A, B) p A".
1995    switch (P) {
1996    default:
1997      break;
1998    case CmpInst::ICMP_EQ:
1999    case CmpInst::ICMP_ULE:
2000      // Equivalent to "A EqP B".  This may be the same as the condition tested
2001      // in the max/min; if so, we can just return that.
2002      if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2003        return V;
2004      if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2005        return V;
2006      // Otherwise, see if "A EqP B" simplifies.
2007      if (MaxRecurse)
2008        if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2009          return V;
2010      break;
2011    case CmpInst::ICMP_NE:
2012    case CmpInst::ICMP_UGT: {
2013      CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2014      // Equivalent to "A InvEqP B".  This may be the same as the condition
2015      // tested in the max/min; if so, we can just return that.
2016      if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2017        return V;
2018      if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2019        return V;
2020      // Otherwise, see if "A InvEqP B" simplifies.
2021      if (MaxRecurse)
2022        if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2023          return V;
2024      break;
2025    }
2026    case CmpInst::ICMP_UGE:
2027      // Always true.
2028      return Constant::getAllOnesValue(ITy);
2029    case CmpInst::ICMP_ULT:
2030      // Always false.
2031      return Constant::getNullValue(ITy);
2032    }
2033  }
2034
2035  // Variants on "max(x,y) >= min(x,z)".
2036  Value *C, *D;
2037  if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2038      match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2039      (A == C || A == D || B == C || B == D)) {
2040    // max(x, ?) pred min(x, ?).
2041    if (Pred == CmpInst::ICMP_SGE)
2042      // Always true.
2043      return Constant::getAllOnesValue(ITy);
2044    if (Pred == CmpInst::ICMP_SLT)
2045      // Always false.
2046      return Constant::getNullValue(ITy);
2047  } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2048             match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2049             (A == C || A == D || B == C || B == D)) {
2050    // min(x, ?) pred max(x, ?).
2051    if (Pred == CmpInst::ICMP_SLE)
2052      // Always true.
2053      return Constant::getAllOnesValue(ITy);
2054    if (Pred == CmpInst::ICMP_SGT)
2055      // Always false.
2056      return Constant::getNullValue(ITy);
2057  } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2058             match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2059             (A == C || A == D || B == C || B == D)) {
2060    // max(x, ?) pred min(x, ?).
2061    if (Pred == CmpInst::ICMP_UGE)
2062      // Always true.
2063      return Constant::getAllOnesValue(ITy);
2064    if (Pred == CmpInst::ICMP_ULT)
2065      // Always false.
2066      return Constant::getNullValue(ITy);
2067  } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2068             match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2069             (A == C || A == D || B == C || B == D)) {
2070    // min(x, ?) pred max(x, ?).
2071    if (Pred == CmpInst::ICMP_ULE)
2072      // Always true.
2073      return Constant::getAllOnesValue(ITy);
2074    if (Pred == CmpInst::ICMP_UGT)
2075      // Always false.
2076      return Constant::getNullValue(ITy);
2077  }
2078
2079  // If the comparison is with the result of a select instruction, check whether
2080  // comparing with either branch of the select always yields the same value.
2081  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2082    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2083      return V;
2084
2085  // If the comparison is with the result of a phi instruction, check whether
2086  // doing the compare with each incoming phi value yields a common result.
2087  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2088    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2089      return V;
2090
2091  return 0;
2092}
2093
2094Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2095                              const TargetData *TD, const DominatorTree *DT) {
2096  return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2097}
2098
2099/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2100/// fold the result.  If not, this returns null.
2101static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2102                               const TargetData *TD, const DominatorTree *DT,
2103                               unsigned MaxRecurse) {
2104  CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2105  assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2106
2107  if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2108    if (Constant *CRHS = dyn_cast<Constant>(RHS))
2109      return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
2110
2111    // If we have a constant, make sure it is on the RHS.
2112    std::swap(LHS, RHS);
2113    Pred = CmpInst::getSwappedPredicate(Pred);
2114  }
2115
2116  // Fold trivial predicates.
2117  if (Pred == FCmpInst::FCMP_FALSE)
2118    return ConstantInt::get(GetCompareTy(LHS), 0);
2119  if (Pred == FCmpInst::FCMP_TRUE)
2120    return ConstantInt::get(GetCompareTy(LHS), 1);
2121
2122  if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2123    return UndefValue::get(GetCompareTy(LHS));
2124
2125  // fcmp x,x -> true/false.  Not all compares are foldable.
2126  if (LHS == RHS) {
2127    if (CmpInst::isTrueWhenEqual(Pred))
2128      return ConstantInt::get(GetCompareTy(LHS), 1);
2129    if (CmpInst::isFalseWhenEqual(Pred))
2130      return ConstantInt::get(GetCompareTy(LHS), 0);
2131  }
2132
2133  // Handle fcmp with constant RHS
2134  if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2135    // If the constant is a nan, see if we can fold the comparison based on it.
2136    if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2137      if (CFP->getValueAPF().isNaN()) {
2138        if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2139          return ConstantInt::getFalse(CFP->getContext());
2140        assert(FCmpInst::isUnordered(Pred) &&
2141               "Comparison must be either ordered or unordered!");
2142        // True if unordered.
2143        return ConstantInt::getTrue(CFP->getContext());
2144      }
2145      // Check whether the constant is an infinity.
2146      if (CFP->getValueAPF().isInfinity()) {
2147        if (CFP->getValueAPF().isNegative()) {
2148          switch (Pred) {
2149          case FCmpInst::FCMP_OLT:
2150            // No value is ordered and less than negative infinity.
2151            return ConstantInt::getFalse(CFP->getContext());
2152          case FCmpInst::FCMP_UGE:
2153            // All values are unordered with or at least negative infinity.
2154            return ConstantInt::getTrue(CFP->getContext());
2155          default:
2156            break;
2157          }
2158        } else {
2159          switch (Pred) {
2160          case FCmpInst::FCMP_OGT:
2161            // No value is ordered and greater than infinity.
2162            return ConstantInt::getFalse(CFP->getContext());
2163          case FCmpInst::FCMP_ULE:
2164            // All values are unordered with and at most infinity.
2165            return ConstantInt::getTrue(CFP->getContext());
2166          default:
2167            break;
2168          }
2169        }
2170      }
2171    }
2172  }
2173
2174  // If the comparison is with the result of a select instruction, check whether
2175  // comparing with either branch of the select always yields the same value.
2176  if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2177    if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2178      return V;
2179
2180  // If the comparison is with the result of a phi instruction, check whether
2181  // doing the compare with each incoming phi value yields a common result.
2182  if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2183    if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2184      return V;
2185
2186  return 0;
2187}
2188
2189Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2190                              const TargetData *TD, const DominatorTree *DT) {
2191  return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2192}
2193
2194/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2195/// the result.  If not, this returns null.
2196Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2197                                const TargetData *TD, const DominatorTree *) {
2198  // select true, X, Y  -> X
2199  // select false, X, Y -> Y
2200  if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2201    return CB->getZExtValue() ? TrueVal : FalseVal;
2202
2203  // select C, X, X -> X
2204  if (TrueVal == FalseVal)
2205    return TrueVal;
2206
2207  if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2208    return FalseVal;
2209  if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2210    return TrueVal;
2211  if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2212    if (isa<Constant>(TrueVal))
2213      return TrueVal;
2214    return FalseVal;
2215  }
2216
2217  return 0;
2218}
2219
2220/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2221/// fold the result.  If not, this returns null.
2222Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
2223                             const TargetData *TD, const DominatorTree *) {
2224  // The type of the GEP pointer operand.
2225  const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
2226
2227  // getelementptr P -> P.
2228  if (NumOps == 1)
2229    return Ops[0];
2230
2231  if (isa<UndefValue>(Ops[0])) {
2232    // Compute the (pointer) type returned by the GEP instruction.
2233    const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
2234                                                             NumOps-1);
2235    const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2236    return UndefValue::get(GEPTy);
2237  }
2238
2239  if (NumOps == 2) {
2240    // getelementptr P, 0 -> P.
2241    if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2242      if (C->isZero())
2243        return Ops[0];
2244    // getelementptr P, N -> P if P points to a type of zero size.
2245    if (TD) {
2246      const Type *Ty = PtrTy->getElementType();
2247      if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2248        return Ops[0];
2249    }
2250  }
2251
2252  // Check to see if this is constant foldable.
2253  for (unsigned i = 0; i != NumOps; ++i)
2254    if (!isa<Constant>(Ops[i]))
2255      return 0;
2256
2257  return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
2258                                        (Constant *const*)Ops+1, NumOps-1);
2259}
2260
2261/// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2262static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2263  // If all of the PHI's incoming values are the same then replace the PHI node
2264  // with the common value.
2265  Value *CommonValue = 0;
2266  bool HasUndefInput = false;
2267  for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2268    Value *Incoming = PN->getIncomingValue(i);
2269    // If the incoming value is the phi node itself, it can safely be skipped.
2270    if (Incoming == PN) continue;
2271    if (isa<UndefValue>(Incoming)) {
2272      // Remember that we saw an undef value, but otherwise ignore them.
2273      HasUndefInput = true;
2274      continue;
2275    }
2276    if (CommonValue && Incoming != CommonValue)
2277      return 0;  // Not the same, bail out.
2278    CommonValue = Incoming;
2279  }
2280
2281  // If CommonValue is null then all of the incoming values were either undef or
2282  // equal to the phi node itself.
2283  if (!CommonValue)
2284    return UndefValue::get(PN->getType());
2285
2286  // If we have a PHI node like phi(X, undef, X), where X is defined by some
2287  // instruction, we cannot return X as the result of the PHI node unless it
2288  // dominates the PHI block.
2289  if (HasUndefInput)
2290    return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2291
2292  return CommonValue;
2293}
2294
2295
2296//=== Helper functions for higher up the class hierarchy.
2297
2298/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2299/// fold the result.  If not, this returns null.
2300static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2301                            const TargetData *TD, const DominatorTree *DT,
2302                            unsigned MaxRecurse) {
2303  switch (Opcode) {
2304  case Instruction::Add:
2305    return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2306                           TD, DT, MaxRecurse);
2307  case Instruction::Sub:
2308    return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2309                           TD, DT, MaxRecurse);
2310  case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
2311  case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2312  case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
2313  case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
2314  case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2315  case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2316  case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
2317  case Instruction::Shl:
2318    return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2319                           TD, DT, MaxRecurse);
2320  case Instruction::LShr:
2321    return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2322  case Instruction::AShr:
2323    return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2324  case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
2325  case Instruction::Or:  return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
2326  case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
2327  default:
2328    if (Constant *CLHS = dyn_cast<Constant>(LHS))
2329      if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2330        Constant *COps[] = {CLHS, CRHS};
2331        return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
2332      }
2333
2334    // If the operation is associative, try some generic simplifications.
2335    if (Instruction::isAssociative(Opcode))
2336      if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2337                                              MaxRecurse))
2338        return V;
2339
2340    // If the operation is with the result of a select instruction, check whether
2341    // operating on either branch of the select always yields the same value.
2342    if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2343      if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
2344                                           MaxRecurse))
2345        return V;
2346
2347    // If the operation is with the result of a phi instruction, check whether
2348    // operating on all incoming values of the phi always yields the same value.
2349    if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2350      if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
2351        return V;
2352
2353    return 0;
2354  }
2355}
2356
2357Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2358                           const TargetData *TD, const DominatorTree *DT) {
2359  return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
2360}
2361
2362/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2363/// fold the result.
2364static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2365                              const TargetData *TD, const DominatorTree *DT,
2366                              unsigned MaxRecurse) {
2367  if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2368    return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2369  return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2370}
2371
2372Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2373                             const TargetData *TD, const DominatorTree *DT) {
2374  return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2375}
2376
2377/// SimplifyInstruction - See if we can compute a simplified version of this
2378/// instruction.  If not, this returns null.
2379Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2380                                 const DominatorTree *DT) {
2381  Value *Result;
2382
2383  switch (I->getOpcode()) {
2384  default:
2385    Result = ConstantFoldInstruction(I, TD);
2386    break;
2387  case Instruction::Add:
2388    Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2389                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2390                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2391                             TD, DT);
2392    break;
2393  case Instruction::Sub:
2394    Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2395                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2396                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2397                             TD, DT);
2398    break;
2399  case Instruction::Mul:
2400    Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2401    break;
2402  case Instruction::SDiv:
2403    Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2404    break;
2405  case Instruction::UDiv:
2406    Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2407    break;
2408  case Instruction::FDiv:
2409    Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2410    break;
2411  case Instruction::SRem:
2412    Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2413    break;
2414  case Instruction::URem:
2415    Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2416    break;
2417  case Instruction::FRem:
2418    Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2419    break;
2420  case Instruction::Shl:
2421    Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2422                             cast<BinaryOperator>(I)->hasNoSignedWrap(),
2423                             cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2424                             TD, DT);
2425    break;
2426  case Instruction::LShr:
2427    Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2428                              cast<BinaryOperator>(I)->isExact(),
2429                              TD, DT);
2430    break;
2431  case Instruction::AShr:
2432    Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2433                              cast<BinaryOperator>(I)->isExact(),
2434                              TD, DT);
2435    break;
2436  case Instruction::And:
2437    Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2438    break;
2439  case Instruction::Or:
2440    Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2441    break;
2442  case Instruction::Xor:
2443    Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2444    break;
2445  case Instruction::ICmp:
2446    Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2447                              I->getOperand(0), I->getOperand(1), TD, DT);
2448    break;
2449  case Instruction::FCmp:
2450    Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2451                              I->getOperand(0), I->getOperand(1), TD, DT);
2452    break;
2453  case Instruction::Select:
2454    Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2455                                I->getOperand(2), TD, DT);
2456    break;
2457  case Instruction::GetElementPtr: {
2458    SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2459    Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
2460    break;
2461  }
2462  case Instruction::PHI:
2463    Result = SimplifyPHINode(cast<PHINode>(I), DT);
2464    break;
2465  }
2466
2467  /// If called on unreachable code, the above logic may report that the
2468  /// instruction simplified to itself.  Make life easier for users by
2469  /// detecting that case here, returning a safe value instead.
2470  return Result == I ? UndefValue::get(I->getType()) : Result;
2471}
2472
2473/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2474/// delete the From instruction.  In addition to a basic RAUW, this does a
2475/// recursive simplification of the newly formed instructions.  This catches
2476/// things where one simplification exposes other opportunities.  This only
2477/// simplifies and deletes scalar operations, it does not change the CFG.
2478///
2479void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2480                                     const TargetData *TD,
2481                                     const DominatorTree *DT) {
2482  assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2483
2484  // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2485  // we can know if it gets deleted out from under us or replaced in a
2486  // recursive simplification.
2487  WeakVH FromHandle(From);
2488  WeakVH ToHandle(To);
2489
2490  while (!From->use_empty()) {
2491    // Update the instruction to use the new value.
2492    Use &TheUse = From->use_begin().getUse();
2493    Instruction *User = cast<Instruction>(TheUse.getUser());
2494    TheUse = To;
2495
2496    // Check to see if the instruction can be folded due to the operand
2497    // replacement.  For example changing (or X, Y) into (or X, -1) can replace
2498    // the 'or' with -1.
2499    Value *SimplifiedVal;
2500    {
2501      // Sanity check to make sure 'User' doesn't dangle across
2502      // SimplifyInstruction.
2503      AssertingVH<> UserHandle(User);
2504
2505      SimplifiedVal = SimplifyInstruction(User, TD, DT);
2506      if (SimplifiedVal == 0) continue;
2507    }
2508
2509    // Recursively simplify this user to the new value.
2510    ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
2511    From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2512    To = ToHandle;
2513
2514    assert(ToHandle && "To value deleted by recursive simplification?");
2515
2516    // If the recursive simplification ended up revisiting and deleting
2517    // 'From' then we're done.
2518    if (From == 0)
2519      return;
2520  }
2521
2522  // If 'From' has value handles referring to it, do a real RAUW to update them.
2523  From->replaceAllUsesWith(To);
2524
2525  From->eraseFromParent();
2526}
2527