d8d8a09804ef074cf7b56966bc61e82c71432d78
[oota-llvm.git] / lib / Analysis / InstructionSimplify.cpp
1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions.  This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x").  All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "instsimplify"
21 #include "llvm/Analysis/InstructionSimplify.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/IR/ConstantRange.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Dominators.h"
30 #include "llvm/IR/GetElementPtrTypeIterator.h"
31 #include "llvm/IR/GlobalAlias.h"
32 #include "llvm/IR/Operator.h"
33 #include "llvm/IR/PatternMatch.h"
34 #include "llvm/IR/ValueHandle.h"
35 using namespace llvm;
36 using namespace llvm::PatternMatch;
37
38 enum { RecursionLimit = 3 };
39
40 STATISTIC(NumExpand,  "Number of expansions");
41 STATISTIC(NumFactor , "Number of factorizations");
42 STATISTIC(NumReassoc, "Number of reassociations");
43
44 struct Query {
45   const DataLayout *DL;
46   const TargetLibraryInfo *TLI;
47   const DominatorTree *DT;
48
49   Query(const DataLayout *DL, const TargetLibraryInfo *tli,
50         const DominatorTree *dt) : DL(DL), TLI(tli), DT(dt) {}
51 };
52
53 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
55                             unsigned);
56 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
57                               unsigned);
58 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
60 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
61
62 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
63 /// a vector with every element false, as appropriate for the type.
64 static Constant *getFalse(Type *Ty) {
65   assert(Ty->getScalarType()->isIntegerTy(1) &&
66          "Expected i1 type or a vector of i1!");
67   return Constant::getNullValue(Ty);
68 }
69
70 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
71 /// a vector with every element true, as appropriate for the type.
72 static Constant *getTrue(Type *Ty) {
73   assert(Ty->getScalarType()->isIntegerTy(1) &&
74          "Expected i1 type or a vector of i1!");
75   return Constant::getAllOnesValue(Ty);
76 }
77
78 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
80                           Value *RHS) {
81   CmpInst *Cmp = dyn_cast<CmpInst>(V);
82   if (!Cmp)
83     return false;
84   CmpInst::Predicate CPred = Cmp->getPredicate();
85   Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86   if (CPred == Pred && CLHS == LHS && CRHS == RHS)
87     return true;
88   return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89     CRHS == LHS;
90 }
91
92 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
93 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94   Instruction *I = dyn_cast<Instruction>(V);
95   if (!I)
96     // Arguments and constants dominate all instructions.
97     return true;
98
99   // If we are processing instructions (and/or basic blocks) that have not been
100   // fully added to a function, the parent nodes may still be null. Simply
101   // return the conservative answer in these cases.
102   if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
103     return false;
104
105   // If we have a DominatorTree then do a precise test.
106   if (DT) {
107     if (!DT->isReachableFromEntry(P->getParent()))
108       return true;
109     if (!DT->isReachableFromEntry(I->getParent()))
110       return false;
111     return DT->dominates(I, P);
112   }
113
114   // Otherwise, if the instruction is in the entry block, and is not an invoke,
115   // then it obviously dominates all phi nodes.
116   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
117       !isa<InvokeInst>(I))
118     return true;
119
120   return false;
121 }
122
123 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124 /// it into "(A op B) op' (A op C)".  Here "op" is given by Opcode and "op'" is
125 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127 /// Returns the simplified value, or null if no simplification was performed.
128 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
129                           unsigned OpcToExpand, const Query &Q,
130                           unsigned MaxRecurse) {
131   Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
132   // Recursion is always used, so bail out at once if we already hit the limit.
133   if (!MaxRecurse--)
134     return 0;
135
136   // Check whether the expression has the form "(A op' B) op C".
137   if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138     if (Op0->getOpcode() == OpcodeToExpand) {
139       // It does!  Try turning it into "(A op C) op' (B op C)".
140       Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141       // Do "A op C" and "B op C" both simplify?
142       if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143         if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
144           // They do! Return "L op' R" if it simplifies or is already available.
145           // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
146           if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147                                      && L == B && R == A)) {
148             ++NumExpand;
149             return LHS;
150           }
151           // Otherwise return "L op' R" if it simplifies.
152           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
153             ++NumExpand;
154             return V;
155           }
156         }
157     }
158
159   // Check whether the expression has the form "A op (B op' C)".
160   if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161     if (Op1->getOpcode() == OpcodeToExpand) {
162       // It does!  Try turning it into "(A op B) op' (A op C)".
163       Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164       // Do "A op B" and "A op C" both simplify?
165       if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166         if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
167           // They do! Return "L op' R" if it simplifies or is already available.
168           // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
169           if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170                                      && L == C && R == B)) {
171             ++NumExpand;
172             return RHS;
173           }
174           // Otherwise return "L op' R" if it simplifies.
175           if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
176             ++NumExpand;
177             return V;
178           }
179         }
180     }
181
182   return 0;
183 }
184
185 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
186 /// using the operation OpCodeToExtract.  For example, when Opcode is Add and
187 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
188 /// Returns the simplified value, or null if no simplification was performed.
189 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
190                              unsigned OpcToExtract, const Query &Q,
191                              unsigned MaxRecurse) {
192   Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
193   // Recursion is always used, so bail out at once if we already hit the limit.
194   if (!MaxRecurse--)
195     return 0;
196
197   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
198   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
199
200   if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
201       !Op1 || Op1->getOpcode() != OpcodeToExtract)
202     return 0;
203
204   // The expression has the form "(A op' B) op (C op' D)".
205   Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
206   Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
207
208   // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
209   // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
210   // commutative case, "(A op' B) op (C op' A)"?
211   if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
212     Value *DD = A == C ? D : C;
213     // Form "A op' (B op DD)" if it simplifies completely.
214     // Does "B op DD" simplify?
215     if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
216       // It does!  Return "A op' V" if it simplifies or is already available.
217       // If V equals B then "A op' V" is just the LHS.  If V equals DD then
218       // "A op' V" is just the RHS.
219       if (V == B || V == DD) {
220         ++NumFactor;
221         return V == B ? LHS : RHS;
222       }
223       // Otherwise return "A op' V" if it simplifies.
224       if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
225         ++NumFactor;
226         return W;
227       }
228     }
229   }
230
231   // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
232   // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
233   // commutative case, "(A op' B) op (B op' D)"?
234   if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
235     Value *CC = B == D ? C : D;
236     // Form "(A op CC) op' B" if it simplifies completely..
237     // Does "A op CC" simplify?
238     if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
239       // It does!  Return "V op' B" if it simplifies or is already available.
240       // If V equals A then "V op' B" is just the LHS.  If V equals CC then
241       // "V op' B" is just the RHS.
242       if (V == A || V == CC) {
243         ++NumFactor;
244         return V == A ? LHS : RHS;
245       }
246       // Otherwise return "V op' B" if it simplifies.
247       if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
248         ++NumFactor;
249         return W;
250       }
251     }
252   }
253
254   return 0;
255 }
256
257 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
258 /// operations.  Returns the simpler value, or null if none was found.
259 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
260                                        const Query &Q, unsigned MaxRecurse) {
261   Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
262   assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
263
264   // Recursion is always used, so bail out at once if we already hit the limit.
265   if (!MaxRecurse--)
266     return 0;
267
268   BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
269   BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
270
271   // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
272   if (Op0 && Op0->getOpcode() == Opcode) {
273     Value *A = Op0->getOperand(0);
274     Value *B = Op0->getOperand(1);
275     Value *C = RHS;
276
277     // Does "B op C" simplify?
278     if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
279       // It does!  Return "A op V" if it simplifies or is already available.
280       // If V equals B then "A op V" is just the LHS.
281       if (V == B) return LHS;
282       // Otherwise return "A op V" if it simplifies.
283       if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
284         ++NumReassoc;
285         return W;
286       }
287     }
288   }
289
290   // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
291   if (Op1 && Op1->getOpcode() == Opcode) {
292     Value *A = LHS;
293     Value *B = Op1->getOperand(0);
294     Value *C = Op1->getOperand(1);
295
296     // Does "A op B" simplify?
297     if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
298       // It does!  Return "V op C" if it simplifies or is already available.
299       // If V equals B then "V op C" is just the RHS.
300       if (V == B) return RHS;
301       // Otherwise return "V op C" if it simplifies.
302       if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
303         ++NumReassoc;
304         return W;
305       }
306     }
307   }
308
309   // The remaining transforms require commutativity as well as associativity.
310   if (!Instruction::isCommutative(Opcode))
311     return 0;
312
313   // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
314   if (Op0 && Op0->getOpcode() == Opcode) {
315     Value *A = Op0->getOperand(0);
316     Value *B = Op0->getOperand(1);
317     Value *C = RHS;
318
319     // Does "C op A" simplify?
320     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
321       // It does!  Return "V op B" if it simplifies or is already available.
322       // If V equals A then "V op B" is just the LHS.
323       if (V == A) return LHS;
324       // Otherwise return "V op B" if it simplifies.
325       if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
326         ++NumReassoc;
327         return W;
328       }
329     }
330   }
331
332   // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
333   if (Op1 && Op1->getOpcode() == Opcode) {
334     Value *A = LHS;
335     Value *B = Op1->getOperand(0);
336     Value *C = Op1->getOperand(1);
337
338     // Does "C op A" simplify?
339     if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
340       // It does!  Return "B op V" if it simplifies or is already available.
341       // If V equals C then "B op V" is just the RHS.
342       if (V == C) return RHS;
343       // Otherwise return "B op V" if it simplifies.
344       if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
345         ++NumReassoc;
346         return W;
347       }
348     }
349   }
350
351   return 0;
352 }
353
354 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
355 /// instruction as an operand, try to simplify the binop by seeing whether
356 /// evaluating it on both branches of the select results in the same value.
357 /// Returns the common value if so, otherwise returns null.
358 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
359                                     const Query &Q, unsigned MaxRecurse) {
360   // Recursion is always used, so bail out at once if we already hit the limit.
361   if (!MaxRecurse--)
362     return 0;
363
364   SelectInst *SI;
365   if (isa<SelectInst>(LHS)) {
366     SI = cast<SelectInst>(LHS);
367   } else {
368     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369     SI = cast<SelectInst>(RHS);
370   }
371
372   // Evaluate the BinOp on the true and false branches of the select.
373   Value *TV;
374   Value *FV;
375   if (SI == LHS) {
376     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
377     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
378   } else {
379     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
380     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
381   }
382
383   // If they simplified to the same value, then return the common value.
384   // If they both failed to simplify then return null.
385   if (TV == FV)
386     return TV;
387
388   // If one branch simplified to undef, return the other one.
389   if (TV && isa<UndefValue>(TV))
390     return FV;
391   if (FV && isa<UndefValue>(FV))
392     return TV;
393
394   // If applying the operation did not change the true and false select values,
395   // then the result of the binop is the select itself.
396   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
397     return SI;
398
399   // If one branch simplified and the other did not, and the simplified
400   // value is equal to the unsimplified one, return the simplified value.
401   // For example, select (cond, X, X & Z) & Z -> X & Z.
402   if ((FV && !TV) || (TV && !FV)) {
403     // Check that the simplified value has the form "X op Y" where "op" is the
404     // same as the original operation.
405     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406     if (Simplified && Simplified->getOpcode() == Opcode) {
407       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408       // We already know that "op" is the same as for the simplified value.  See
409       // if the operands match too.  If so, return the simplified value.
410       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
413       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414           Simplified->getOperand(1) == UnsimplifiedRHS)
415         return Simplified;
416       if (Simplified->isCommutative() &&
417           Simplified->getOperand(1) == UnsimplifiedLHS &&
418           Simplified->getOperand(0) == UnsimplifiedRHS)
419         return Simplified;
420     }
421   }
422
423   return 0;
424 }
425
426 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427 /// try to simplify the comparison by seeing whether both branches of the select
428 /// result in the same value.  Returns the common value if so, otherwise returns
429 /// null.
430 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
431                                   Value *RHS, const Query &Q,
432                                   unsigned MaxRecurse) {
433   // Recursion is always used, so bail out at once if we already hit the limit.
434   if (!MaxRecurse--)
435     return 0;
436
437   // Make sure the select is on the LHS.
438   if (!isa<SelectInst>(LHS)) {
439     std::swap(LHS, RHS);
440     Pred = CmpInst::getSwappedPredicate(Pred);
441   }
442   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443   SelectInst *SI = cast<SelectInst>(LHS);
444   Value *Cond = SI->getCondition();
445   Value *TV = SI->getTrueValue();
446   Value *FV = SI->getFalseValue();
447
448   // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
449   // Does "cmp TV, RHS" simplify?
450   Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
451   if (TCmp == Cond) {
452     // It not only simplified, it simplified to the select condition.  Replace
453     // it with 'true'.
454     TCmp = getTrue(Cond->getType());
455   } else if (!TCmp) {
456     // It didn't simplify.  However if "cmp TV, RHS" is equal to the select
457     // condition then we can replace it with 'true'.  Otherwise give up.
458     if (!isSameCompare(Cond, Pred, TV, RHS))
459       return 0;
460     TCmp = getTrue(Cond->getType());
461   }
462
463   // Does "cmp FV, RHS" simplify?
464   Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
465   if (FCmp == Cond) {
466     // It not only simplified, it simplified to the select condition.  Replace
467     // it with 'false'.
468     FCmp = getFalse(Cond->getType());
469   } else if (!FCmp) {
470     // It didn't simplify.  However if "cmp FV, RHS" is equal to the select
471     // condition then we can replace it with 'false'.  Otherwise give up.
472     if (!isSameCompare(Cond, Pred, FV, RHS))
473       return 0;
474     FCmp = getFalse(Cond->getType());
475   }
476
477   // If both sides simplified to the same value, then use it as the result of
478   // the original comparison.
479   if (TCmp == FCmp)
480     return TCmp;
481
482   // The remaining cases only make sense if the select condition has the same
483   // type as the result of the comparison, so bail out if this is not so.
484   if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
485     return 0;
486   // If the false value simplified to false, then the result of the compare
487   // is equal to "Cond && TCmp".  This also catches the case when the false
488   // value simplified to false and the true value to true, returning "Cond".
489   if (match(FCmp, m_Zero()))
490     if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
491       return V;
492   // If the true value simplified to true, then the result of the compare
493   // is equal to "Cond || FCmp".
494   if (match(TCmp, m_One()))
495     if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
496       return V;
497   // Finally, if the false value simplified to true and the true value to
498   // false, then the result of the compare is equal to "!Cond".
499   if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
500     if (Value *V =
501         SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
502                         Q, MaxRecurse))
503       return V;
504
505   return 0;
506 }
507
508 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510 /// it on the incoming phi values yields the same result for every value.  If so
511 /// returns the common value, otherwise returns null.
512 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
513                                  const Query &Q, unsigned MaxRecurse) {
514   // Recursion is always used, so bail out at once if we already hit the limit.
515   if (!MaxRecurse--)
516     return 0;
517
518   PHINode *PI;
519   if (isa<PHINode>(LHS)) {
520     PI = cast<PHINode>(LHS);
521     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
522     if (!ValueDominatesPHI(RHS, PI, Q.DT))
523       return 0;
524   } else {
525     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
526     PI = cast<PHINode>(RHS);
527     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
528     if (!ValueDominatesPHI(LHS, PI, Q.DT))
529       return 0;
530   }
531
532   // Evaluate the BinOp on the incoming phi values.
533   Value *CommonValue = 0;
534   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
535     Value *Incoming = PI->getIncomingValue(i);
536     // If the incoming value is the phi node itself, it can safely be skipped.
537     if (Incoming == PI) continue;
538     Value *V = PI == LHS ?
539       SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
540       SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
541     // If the operation failed to simplify, or simplified to a different value
542     // to previously, then give up.
543     if (!V || (CommonValue && V != CommonValue))
544       return 0;
545     CommonValue = V;
546   }
547
548   return CommonValue;
549 }
550
551 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
552 /// try to simplify the comparison by seeing whether comparing with all of the
553 /// incoming phi values yields the same result every time.  If so returns the
554 /// common result, otherwise returns null.
555 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
556                                const Query &Q, unsigned MaxRecurse) {
557   // Recursion is always used, so bail out at once if we already hit the limit.
558   if (!MaxRecurse--)
559     return 0;
560
561   // Make sure the phi is on the LHS.
562   if (!isa<PHINode>(LHS)) {
563     std::swap(LHS, RHS);
564     Pred = CmpInst::getSwappedPredicate(Pred);
565   }
566   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
567   PHINode *PI = cast<PHINode>(LHS);
568
569   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
570   if (!ValueDominatesPHI(RHS, PI, Q.DT))
571     return 0;
572
573   // Evaluate the BinOp on the incoming phi values.
574   Value *CommonValue = 0;
575   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
576     Value *Incoming = PI->getIncomingValue(i);
577     // If the incoming value is the phi node itself, it can safely be skipped.
578     if (Incoming == PI) continue;
579     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
580     // If the operation failed to simplify, or simplified to a different value
581     // to previously, then give up.
582     if (!V || (CommonValue && V != CommonValue))
583       return 0;
584     CommonValue = V;
585   }
586
587   return CommonValue;
588 }
589
590 /// SimplifyAddInst - Given operands for an Add, see if we can
591 /// fold the result.  If not, this returns null.
592 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
593                               const Query &Q, unsigned MaxRecurse) {
594   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
595     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596       Constant *Ops[] = { CLHS, CRHS };
597       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
598                                       Q.DL, Q.TLI);
599     }
600
601     // Canonicalize the constant to the RHS.
602     std::swap(Op0, Op1);
603   }
604
605   // X + undef -> undef
606   if (match(Op1, m_Undef()))
607     return Op1;
608
609   // X + 0 -> X
610   if (match(Op1, m_Zero()))
611     return Op0;
612
613   // X + (Y - X) -> Y
614   // (Y - X) + X -> Y
615   // Eg: X + -X -> 0
616   Value *Y = 0;
617   if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
618       match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
619     return Y;
620
621   // X + ~X -> -1   since   ~X = -X-1
622   if (match(Op0, m_Not(m_Specific(Op1))) ||
623       match(Op1, m_Not(m_Specific(Op0))))
624     return Constant::getAllOnesValue(Op0->getType());
625
626   /// i1 add -> xor.
627   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
628     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
629       return V;
630
631   // Try some generic simplifications for associative operations.
632   if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
633                                           MaxRecurse))
634     return V;
635
636   // Mul distributes over Add.  Try some generic simplifications based on this.
637   if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
638                                 Q, MaxRecurse))
639     return V;
640
641   // Threading Add over selects and phi nodes is pointless, so don't bother.
642   // Threading over the select in "A + select(cond, B, C)" means evaluating
643   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
644   // only if B and C are equal.  If B and C are equal then (since we assume
645   // that operands have already been simplified) "select(cond, B, C)" should
646   // have been simplified to the common value of B and C already.  Analysing
647   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
648   // for threading over phi nodes.
649
650   return 0;
651 }
652
653 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
654                              const DataLayout *DL, const TargetLibraryInfo *TLI,
655                              const DominatorTree *DT) {
656   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
657                            RecursionLimit);
658 }
659
660 /// \brief Compute the base pointer and cumulative constant offsets for V.
661 ///
662 /// This strips all constant offsets off of V, leaving it the base pointer, and
663 /// accumulates the total constant offset applied in the returned constant. It
664 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
665 /// no constant offsets applied.
666 ///
667 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
668 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
669 /// folding.
670 static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
671                                                 Value *&V,
672                                                 bool AllowNonInbounds = false) {
673   assert(V->getType()->getScalarType()->isPointerTy());
674
675   // Without DataLayout, just be conservative for now. Theoretically, more could
676   // be done in this case.
677   if (!DL)
678     return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
679
680   Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
681   APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
682
683   // Even though we don't look through PHI nodes, we could be called on an
684   // instruction in an unreachable block, which may be on a cycle.
685   SmallPtrSet<Value *, 4> Visited;
686   Visited.insert(V);
687   do {
688     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
689       if ((!AllowNonInbounds && !GEP->isInBounds()) ||
690           !GEP->accumulateConstantOffset(*DL, Offset))
691         break;
692       V = GEP->getPointerOperand();
693     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
694       V = cast<Operator>(V)->getOperand(0);
695     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
696       if (GA->mayBeOverridden())
697         break;
698       V = GA->getAliasee();
699     } else {
700       break;
701     }
702     assert(V->getType()->getScalarType()->isPointerTy() &&
703            "Unexpected operand type!");
704   } while (Visited.insert(V));
705
706   Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
707   if (V->getType()->isVectorTy())
708     return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
709                                     OffsetIntPtr);
710   return OffsetIntPtr;
711 }
712
713 /// \brief Compute the constant difference between two pointer values.
714 /// If the difference is not a constant, returns zero.
715 static Constant *computePointerDifference(const DataLayout *DL,
716                                           Value *LHS, Value *RHS) {
717   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
718   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
719
720   // If LHS and RHS are not related via constant offsets to the same base
721   // value, there is nothing we can do here.
722   if (LHS != RHS)
723     return 0;
724
725   // Otherwise, the difference of LHS - RHS can be computed as:
726   //    LHS - RHS
727   //  = (LHSOffset + Base) - (RHSOffset + Base)
728   //  = LHSOffset - RHSOffset
729   return ConstantExpr::getSub(LHSOffset, RHSOffset);
730 }
731
732 /// SimplifySubInst - Given operands for a Sub, see if we can
733 /// fold the result.  If not, this returns null.
734 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
735                               const Query &Q, unsigned MaxRecurse) {
736   if (Constant *CLHS = dyn_cast<Constant>(Op0))
737     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
738       Constant *Ops[] = { CLHS, CRHS };
739       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
740                                       Ops, Q.DL, Q.TLI);
741     }
742
743   // X - undef -> undef
744   // undef - X -> undef
745   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
746     return UndefValue::get(Op0->getType());
747
748   // X - 0 -> X
749   if (match(Op1, m_Zero()))
750     return Op0;
751
752   // X - X -> 0
753   if (Op0 == Op1)
754     return Constant::getNullValue(Op0->getType());
755
756   // (X*2) - X -> X
757   // (X<<1) - X -> X
758   Value *X = 0;
759   if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
760       match(Op0, m_Shl(m_Specific(Op1), m_One())))
761     return Op1;
762
763   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
764   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
765   Value *Y = 0, *Z = Op1;
766   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
767     // See if "V === Y - Z" simplifies.
768     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
769       // It does!  Now see if "X + V" simplifies.
770       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
771         // It does, we successfully reassociated!
772         ++NumReassoc;
773         return W;
774       }
775     // See if "V === X - Z" simplifies.
776     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
777       // It does!  Now see if "Y + V" simplifies.
778       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
779         // It does, we successfully reassociated!
780         ++NumReassoc;
781         return W;
782       }
783   }
784
785   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
786   // For example, X - (X + 1) -> -1
787   X = Op0;
788   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
789     // See if "V === X - Y" simplifies.
790     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
791       // It does!  Now see if "V - Z" simplifies.
792       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
793         // It does, we successfully reassociated!
794         ++NumReassoc;
795         return W;
796       }
797     // See if "V === X - Z" simplifies.
798     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
799       // It does!  Now see if "V - Y" simplifies.
800       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
801         // It does, we successfully reassociated!
802         ++NumReassoc;
803         return W;
804       }
805   }
806
807   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
808   // For example, X - (X - Y) -> Y.
809   Z = Op0;
810   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
811     // See if "V === Z - X" simplifies.
812     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
813       // It does!  Now see if "V + Y" simplifies.
814       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
815         // It does, we successfully reassociated!
816         ++NumReassoc;
817         return W;
818       }
819
820   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
821   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
822       match(Op1, m_Trunc(m_Value(Y))))
823     if (X->getType() == Y->getType())
824       // See if "V === X - Y" simplifies.
825       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
826         // It does!  Now see if "trunc V" simplifies.
827         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
828           // It does, return the simplified "trunc V".
829           return W;
830
831   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
832   if (match(Op0, m_PtrToInt(m_Value(X))) &&
833       match(Op1, m_PtrToInt(m_Value(Y))))
834     if (Constant *Result = computePointerDifference(Q.DL, X, Y))
835       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
836
837   // Mul distributes over Sub.  Try some generic simplifications based on this.
838   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
839                                 Q, MaxRecurse))
840     return V;
841
842   // i1 sub -> xor.
843   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
844     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
845       return V;
846
847   // Threading Sub over selects and phi nodes is pointless, so don't bother.
848   // Threading over the select in "A - select(cond, B, C)" means evaluating
849   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
850   // only if B and C are equal.  If B and C are equal then (since we assume
851   // that operands have already been simplified) "select(cond, B, C)" should
852   // have been simplified to the common value of B and C already.  Analysing
853   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
854   // for threading over phi nodes.
855
856   return 0;
857 }
858
859 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
860                              const DataLayout *DL, const TargetLibraryInfo *TLI,
861                              const DominatorTree *DT) {
862   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
863                            RecursionLimit);
864 }
865
866 /// Given operands for an FAdd, see if we can fold the result.  If not, this
867 /// returns null.
868 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
869                               const Query &Q, unsigned MaxRecurse) {
870   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
871     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
872       Constant *Ops[] = { CLHS, CRHS };
873       return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
874                                       Ops, Q.DL, Q.TLI);
875     }
876
877     // Canonicalize the constant to the RHS.
878     std::swap(Op0, Op1);
879   }
880
881   // fadd X, -0 ==> X
882   if (match(Op1, m_NegZero()))
883     return Op0;
884
885   // fadd X, 0 ==> X, when we know X is not -0
886   if (match(Op1, m_Zero()) &&
887       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
888     return Op0;
889
890   // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
891   //   where nnan and ninf have to occur at least once somewhere in this
892   //   expression
893   Value *SubOp = 0;
894   if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
895     SubOp = Op1;
896   else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
897     SubOp = Op0;
898   if (SubOp) {
899     Instruction *FSub = cast<Instruction>(SubOp);
900     if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
901         (FMF.noInfs() || FSub->hasNoInfs()))
902       return Constant::getNullValue(Op0->getType());
903   }
904
905   return 0;
906 }
907
908 /// Given operands for an FSub, see if we can fold the result.  If not, this
909 /// returns null.
910 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
911                               const Query &Q, unsigned MaxRecurse) {
912   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
913     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
914       Constant *Ops[] = { CLHS, CRHS };
915       return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
916                                       Ops, Q.DL, Q.TLI);
917     }
918   }
919
920   // fsub X, 0 ==> X
921   if (match(Op1, m_Zero()))
922     return Op0;
923
924   // fsub X, -0 ==> X, when we know X is not -0
925   if (match(Op1, m_NegZero()) &&
926       (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
927     return Op0;
928
929   // fsub 0, (fsub -0.0, X) ==> X
930   Value *X;
931   if (match(Op0, m_AnyZero())) {
932     if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
933       return X;
934     if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
935       return X;
936   }
937
938   // fsub nnan ninf x, x ==> 0.0
939   if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
940     return Constant::getNullValue(Op0->getType());
941
942   return 0;
943 }
944
945 /// Given the operands for an FMul, see if we can fold the result
946 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
947                                FastMathFlags FMF,
948                                const Query &Q,
949                                unsigned MaxRecurse) {
950  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
951     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
952       Constant *Ops[] = { CLHS, CRHS };
953       return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
954                                       Ops, Q.DL, Q.TLI);
955     }
956
957     // Canonicalize the constant to the RHS.
958     std::swap(Op0, Op1);
959  }
960
961  // fmul X, 1.0 ==> X
962  if (match(Op1, m_FPOne()))
963    return Op0;
964
965  // fmul nnan nsz X, 0 ==> 0
966  if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
967    return Op1;
968
969  return 0;
970 }
971
972 /// SimplifyMulInst - Given operands for a Mul, see if we can
973 /// fold the result.  If not, this returns null.
974 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
975                               unsigned MaxRecurse) {
976   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
977     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
978       Constant *Ops[] = { CLHS, CRHS };
979       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
980                                       Ops, Q.DL, Q.TLI);
981     }
982
983     // Canonicalize the constant to the RHS.
984     std::swap(Op0, Op1);
985   }
986
987   // X * undef -> 0
988   if (match(Op1, m_Undef()))
989     return Constant::getNullValue(Op0->getType());
990
991   // X * 0 -> 0
992   if (match(Op1, m_Zero()))
993     return Op1;
994
995   // X * 1 -> X
996   if (match(Op1, m_One()))
997     return Op0;
998
999   // (X / Y) * Y -> X if the division is exact.
1000   Value *X = 0;
1001   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
1002       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
1003     return X;
1004
1005   // i1 mul -> and.
1006   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
1007     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
1008       return V;
1009
1010   // Try some generic simplifications for associative operations.
1011   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
1012                                           MaxRecurse))
1013     return V;
1014
1015   // Mul distributes over Add.  Try some generic simplifications based on this.
1016   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
1017                              Q, MaxRecurse))
1018     return V;
1019
1020   // If the operation is with the result of a select instruction, check whether
1021   // operating on either branch of the select always yields the same value.
1022   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1023     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
1024                                          MaxRecurse))
1025       return V;
1026
1027   // If the operation is with the result of a phi instruction, check whether
1028   // operating on all incoming values of the phi always yields the same value.
1029   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1030     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
1031                                       MaxRecurse))
1032       return V;
1033
1034   return 0;
1035 }
1036
1037 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1038                              const DataLayout *DL, const TargetLibraryInfo *TLI,
1039                              const DominatorTree *DT) {
1040   return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
1041 }
1042
1043 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1044                              const DataLayout *DL, const TargetLibraryInfo *TLI,
1045                              const DominatorTree *DT) {
1046   return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
1047 }
1048
1049 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1050                               FastMathFlags FMF,
1051                               const DataLayout *DL,
1052                               const TargetLibraryInfo *TLI,
1053                               const DominatorTree *DT) {
1054   return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
1055 }
1056
1057 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
1058                              const TargetLibraryInfo *TLI,
1059                              const DominatorTree *DT) {
1060   return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1061 }
1062
1063 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1064 /// fold the result.  If not, this returns null.
1065 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1066                           const Query &Q, unsigned MaxRecurse) {
1067   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1068     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1069       Constant *Ops[] = { C0, C1 };
1070       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1071     }
1072   }
1073
1074   bool isSigned = Opcode == Instruction::SDiv;
1075
1076   // X / undef -> undef
1077   if (match(Op1, m_Undef()))
1078     return Op1;
1079
1080   // undef / X -> 0
1081   if (match(Op0, m_Undef()))
1082     return Constant::getNullValue(Op0->getType());
1083
1084   // 0 / X -> 0, we don't need to preserve faults!
1085   if (match(Op0, m_Zero()))
1086     return Op0;
1087
1088   // X / 1 -> X
1089   if (match(Op1, m_One()))
1090     return Op0;
1091
1092   if (Op0->getType()->isIntegerTy(1))
1093     // It can't be division by zero, hence it must be division by one.
1094     return Op0;
1095
1096   // X / X -> 1
1097   if (Op0 == Op1)
1098     return ConstantInt::get(Op0->getType(), 1);
1099
1100   // (X * Y) / Y -> X if the multiplication does not overflow.
1101   Value *X = 0, *Y = 0;
1102   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1103     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1104     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1105     // If the Mul knows it does not overflow, then we are good to go.
1106     if ((isSigned && Mul->hasNoSignedWrap()) ||
1107         (!isSigned && Mul->hasNoUnsignedWrap()))
1108       return X;
1109     // If X has the form X = A / Y then X * Y cannot overflow.
1110     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1111       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1112         return X;
1113   }
1114
1115   // (X rem Y) / Y -> 0
1116   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1117       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1118     return Constant::getNullValue(Op0->getType());
1119
1120   // If the operation is with the result of a select instruction, check whether
1121   // operating on either branch of the select always yields the same value.
1122   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1123     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1124       return V;
1125
1126   // If the operation is with the result of a phi instruction, check whether
1127   // operating on all incoming values of the phi always yields the same value.
1128   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1129     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1130       return V;
1131
1132   return 0;
1133 }
1134
1135 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1136 /// fold the result.  If not, this returns null.
1137 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1138                                unsigned MaxRecurse) {
1139   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1140     return V;
1141
1142   return 0;
1143 }
1144
1145 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1146                               const TargetLibraryInfo *TLI,
1147                               const DominatorTree *DT) {
1148   return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1149 }
1150
1151 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1152 /// fold the result.  If not, this returns null.
1153 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1154                                unsigned MaxRecurse) {
1155   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1156     return V;
1157
1158   return 0;
1159 }
1160
1161 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1162                               const TargetLibraryInfo *TLI,
1163                               const DominatorTree *DT) {
1164   return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1165 }
1166
1167 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1168                                unsigned) {
1169   // undef / X -> undef    (the undef could be a snan).
1170   if (match(Op0, m_Undef()))
1171     return Op0;
1172
1173   // X / undef -> undef
1174   if (match(Op1, m_Undef()))
1175     return Op1;
1176
1177   return 0;
1178 }
1179
1180 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1181                               const TargetLibraryInfo *TLI,
1182                               const DominatorTree *DT) {
1183   return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1184 }
1185
1186 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1187 /// fold the result.  If not, this returns null.
1188 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1189                           const Query &Q, unsigned MaxRecurse) {
1190   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1191     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1192       Constant *Ops[] = { C0, C1 };
1193       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1194     }
1195   }
1196
1197   // X % undef -> undef
1198   if (match(Op1, m_Undef()))
1199     return Op1;
1200
1201   // undef % X -> 0
1202   if (match(Op0, m_Undef()))
1203     return Constant::getNullValue(Op0->getType());
1204
1205   // 0 % X -> 0, we don't need to preserve faults!
1206   if (match(Op0, m_Zero()))
1207     return Op0;
1208
1209   // X % 0 -> undef, we don't need to preserve faults!
1210   if (match(Op1, m_Zero()))
1211     return UndefValue::get(Op0->getType());
1212
1213   // X % 1 -> 0
1214   if (match(Op1, m_One()))
1215     return Constant::getNullValue(Op0->getType());
1216
1217   if (Op0->getType()->isIntegerTy(1))
1218     // It can't be remainder by zero, hence it must be remainder by one.
1219     return Constant::getNullValue(Op0->getType());
1220
1221   // X % X -> 0
1222   if (Op0 == Op1)
1223     return Constant::getNullValue(Op0->getType());
1224
1225   // If the operation is with the result of a select instruction, check whether
1226   // operating on either branch of the select always yields the same value.
1227   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1228     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1229       return V;
1230
1231   // If the operation is with the result of a phi instruction, check whether
1232   // operating on all incoming values of the phi always yields the same value.
1233   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1234     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1235       return V;
1236
1237   return 0;
1238 }
1239
1240 /// SimplifySRemInst - Given operands for an SRem, see if we can
1241 /// fold the result.  If not, this returns null.
1242 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1243                                unsigned MaxRecurse) {
1244   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1245     return V;
1246
1247   return 0;
1248 }
1249
1250 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1251                               const TargetLibraryInfo *TLI,
1252                               const DominatorTree *DT) {
1253   return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1254 }
1255
1256 /// SimplifyURemInst - Given operands for a URem, see if we can
1257 /// fold the result.  If not, this returns null.
1258 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1259                                unsigned MaxRecurse) {
1260   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1261     return V;
1262
1263   return 0;
1264 }
1265
1266 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1267                               const TargetLibraryInfo *TLI,
1268                               const DominatorTree *DT) {
1269   return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1270 }
1271
1272 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1273                                unsigned) {
1274   // undef % X -> undef    (the undef could be a snan).
1275   if (match(Op0, m_Undef()))
1276     return Op0;
1277
1278   // X % undef -> undef
1279   if (match(Op1, m_Undef()))
1280     return Op1;
1281
1282   return 0;
1283 }
1284
1285 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1286                               const TargetLibraryInfo *TLI,
1287                               const DominatorTree *DT) {
1288   return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1289 }
1290
1291 /// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1292 static bool isUndefShift(Value *Amount) {
1293   Constant *C = dyn_cast<Constant>(Amount);
1294   if (!C)
1295     return false;
1296
1297   // X shift by undef -> undef because it may shift by the bitwidth.
1298   if (isa<UndefValue>(C))
1299     return true;
1300
1301   // Shifting by the bitwidth or more is undefined.
1302   if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1303     if (CI->getValue().getLimitedValue() >=
1304         CI->getType()->getScalarSizeInBits())
1305       return true;
1306
1307   // If all lanes of a vector shift are undefined the whole shift is.
1308   if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1309     for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1310       if (!isUndefShift(C->getAggregateElement(I)))
1311         return false;
1312     return true;
1313   }
1314
1315   return false;
1316 }
1317
1318 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1319 /// fold the result.  If not, this returns null.
1320 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1321                             const Query &Q, unsigned MaxRecurse) {
1322   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1323     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1324       Constant *Ops[] = { C0, C1 };
1325       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1326     }
1327   }
1328
1329   // 0 shift by X -> 0
1330   if (match(Op0, m_Zero()))
1331     return Op0;
1332
1333   // X shift by 0 -> X
1334   if (match(Op1, m_Zero()))
1335     return Op0;
1336
1337   // Fold undefined shifts.
1338   if (isUndefShift(Op1))
1339     return UndefValue::get(Op0->getType());
1340
1341   // If the operation is with the result of a select instruction, check whether
1342   // operating on either branch of the select always yields the same value.
1343   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1344     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1345       return V;
1346
1347   // If the operation is with the result of a phi instruction, check whether
1348   // operating on all incoming values of the phi always yields the same value.
1349   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1350     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1351       return V;
1352
1353   return 0;
1354 }
1355
1356 /// SimplifyShlInst - Given operands for an Shl, see if we can
1357 /// fold the result.  If not, this returns null.
1358 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1359                               const Query &Q, unsigned MaxRecurse) {
1360   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1361     return V;
1362
1363   // undef << X -> 0
1364   if (match(Op0, m_Undef()))
1365     return Constant::getNullValue(Op0->getType());
1366
1367   // (X >> A) << A -> X
1368   Value *X;
1369   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1370     return X;
1371   return 0;
1372 }
1373
1374 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1375                              const DataLayout *DL, const TargetLibraryInfo *TLI,
1376                              const DominatorTree *DT) {
1377   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
1378                            RecursionLimit);
1379 }
1380
1381 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1382 /// fold the result.  If not, this returns null.
1383 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1384                                const Query &Q, unsigned MaxRecurse) {
1385   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1386     return V;
1387
1388   // X >> X -> 0
1389   if (Op0 == Op1)
1390     return Constant::getNullValue(Op0->getType());
1391
1392   // undef >>l X -> 0
1393   if (match(Op0, m_Undef()))
1394     return Constant::getNullValue(Op0->getType());
1395
1396   // (X << A) >> A -> X
1397   Value *X;
1398   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1399       cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1400     return X;
1401
1402   return 0;
1403 }
1404
1405 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1406                               const DataLayout *DL,
1407                               const TargetLibraryInfo *TLI,
1408                               const DominatorTree *DT) {
1409   return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
1410                             RecursionLimit);
1411 }
1412
1413 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1414 /// fold the result.  If not, this returns null.
1415 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1416                                const Query &Q, unsigned MaxRecurse) {
1417   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1418     return V;
1419
1420   // X >> X -> 0
1421   if (Op0 == Op1)
1422     return Constant::getNullValue(Op0->getType());
1423
1424   // all ones >>a X -> all ones
1425   if (match(Op0, m_AllOnes()))
1426     return Op0;
1427
1428   // undef >>a X -> all ones
1429   if (match(Op0, m_Undef()))
1430     return Constant::getAllOnesValue(Op0->getType());
1431
1432   // (X << A) >> A -> X
1433   Value *X;
1434   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1435       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1436     return X;
1437
1438   return 0;
1439 }
1440
1441 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1442                               const DataLayout *DL,
1443                               const TargetLibraryInfo *TLI,
1444                               const DominatorTree *DT) {
1445   return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
1446                             RecursionLimit);
1447 }
1448
1449 /// SimplifyAndInst - Given operands for an And, see if we can
1450 /// fold the result.  If not, this returns null.
1451 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1452                               unsigned MaxRecurse) {
1453   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1454     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1455       Constant *Ops[] = { CLHS, CRHS };
1456       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1457                                       Ops, Q.DL, Q.TLI);
1458     }
1459
1460     // Canonicalize the constant to the RHS.
1461     std::swap(Op0, Op1);
1462   }
1463
1464   // X & undef -> 0
1465   if (match(Op1, m_Undef()))
1466     return Constant::getNullValue(Op0->getType());
1467
1468   // X & X = X
1469   if (Op0 == Op1)
1470     return Op0;
1471
1472   // X & 0 = 0
1473   if (match(Op1, m_Zero()))
1474     return Op1;
1475
1476   // X & -1 = X
1477   if (match(Op1, m_AllOnes()))
1478     return Op0;
1479
1480   // A & ~A  =  ~A & A  =  0
1481   if (match(Op0, m_Not(m_Specific(Op1))) ||
1482       match(Op1, m_Not(m_Specific(Op0))))
1483     return Constant::getNullValue(Op0->getType());
1484
1485   // (A | ?) & A = A
1486   Value *A = 0, *B = 0;
1487   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1488       (A == Op1 || B == Op1))
1489     return Op1;
1490
1491   // A & (A | ?) = A
1492   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1493       (A == Op0 || B == Op0))
1494     return Op0;
1495
1496   // A & (-A) = A if A is a power of two or zero.
1497   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1498       match(Op1, m_Neg(m_Specific(Op0)))) {
1499     if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
1500       return Op0;
1501     if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
1502       return Op1;
1503   }
1504
1505   // Try some generic simplifications for associative operations.
1506   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1507                                           MaxRecurse))
1508     return V;
1509
1510   // And distributes over Or.  Try some generic simplifications based on this.
1511   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1512                              Q, MaxRecurse))
1513     return V;
1514
1515   // And distributes over Xor.  Try some generic simplifications based on this.
1516   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1517                              Q, MaxRecurse))
1518     return V;
1519
1520   // Or distributes over And.  Try some generic simplifications based on this.
1521   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1522                                 Q, MaxRecurse))
1523     return V;
1524
1525   // If the operation is with the result of a select instruction, check whether
1526   // operating on either branch of the select always yields the same value.
1527   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1528     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1529                                          MaxRecurse))
1530       return V;
1531
1532   // If the operation is with the result of a phi instruction, check whether
1533   // operating on all incoming values of the phi always yields the same value.
1534   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1535     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1536                                       MaxRecurse))
1537       return V;
1538
1539   return 0;
1540 }
1541
1542 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
1543                              const TargetLibraryInfo *TLI,
1544                              const DominatorTree *DT) {
1545   return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1546 }
1547
1548 /// SimplifyOrInst - Given operands for an Or, see if we can
1549 /// fold the result.  If not, this returns null.
1550 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1551                              unsigned MaxRecurse) {
1552   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1553     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1554       Constant *Ops[] = { CLHS, CRHS };
1555       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1556                                       Ops, Q.DL, Q.TLI);
1557     }
1558
1559     // Canonicalize the constant to the RHS.
1560     std::swap(Op0, Op1);
1561   }
1562
1563   // X | undef -> -1
1564   if (match(Op1, m_Undef()))
1565     return Constant::getAllOnesValue(Op0->getType());
1566
1567   // X | X = X
1568   if (Op0 == Op1)
1569     return Op0;
1570
1571   // X | 0 = X
1572   if (match(Op1, m_Zero()))
1573     return Op0;
1574
1575   // X | -1 = -1
1576   if (match(Op1, m_AllOnes()))
1577     return Op1;
1578
1579   // A | ~A  =  ~A | A  =  -1
1580   if (match(Op0, m_Not(m_Specific(Op1))) ||
1581       match(Op1, m_Not(m_Specific(Op0))))
1582     return Constant::getAllOnesValue(Op0->getType());
1583
1584   // (A & ?) | A = A
1585   Value *A = 0, *B = 0;
1586   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1587       (A == Op1 || B == Op1))
1588     return Op1;
1589
1590   // A | (A & ?) = A
1591   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1592       (A == Op0 || B == Op0))
1593     return Op0;
1594
1595   // ~(A & ?) | A = -1
1596   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1597       (A == Op1 || B == Op1))
1598     return Constant::getAllOnesValue(Op1->getType());
1599
1600   // A | ~(A & ?) = -1
1601   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1602       (A == Op0 || B == Op0))
1603     return Constant::getAllOnesValue(Op0->getType());
1604
1605   // Try some generic simplifications for associative operations.
1606   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1607                                           MaxRecurse))
1608     return V;
1609
1610   // Or distributes over And.  Try some generic simplifications based on this.
1611   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1612                              MaxRecurse))
1613     return V;
1614
1615   // And distributes over Or.  Try some generic simplifications based on this.
1616   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1617                                 Q, MaxRecurse))
1618     return V;
1619
1620   // If the operation is with the result of a select instruction, check whether
1621   // operating on either branch of the select always yields the same value.
1622   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1623     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1624                                          MaxRecurse))
1625       return V;
1626
1627   // If the operation is with the result of a phi instruction, check whether
1628   // operating on all incoming values of the phi always yields the same value.
1629   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1630     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1631       return V;
1632
1633   return 0;
1634 }
1635
1636 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
1637                             const TargetLibraryInfo *TLI,
1638                             const DominatorTree *DT) {
1639   return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1640 }
1641
1642 /// SimplifyXorInst - Given operands for a Xor, see if we can
1643 /// fold the result.  If not, this returns null.
1644 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1645                               unsigned MaxRecurse) {
1646   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1647     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1648       Constant *Ops[] = { CLHS, CRHS };
1649       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1650                                       Ops, Q.DL, Q.TLI);
1651     }
1652
1653     // Canonicalize the constant to the RHS.
1654     std::swap(Op0, Op1);
1655   }
1656
1657   // A ^ undef -> undef
1658   if (match(Op1, m_Undef()))
1659     return Op1;
1660
1661   // A ^ 0 = A
1662   if (match(Op1, m_Zero()))
1663     return Op0;
1664
1665   // A ^ A = 0
1666   if (Op0 == Op1)
1667     return Constant::getNullValue(Op0->getType());
1668
1669   // A ^ ~A  =  ~A ^ A  =  -1
1670   if (match(Op0, m_Not(m_Specific(Op1))) ||
1671       match(Op1, m_Not(m_Specific(Op0))))
1672     return Constant::getAllOnesValue(Op0->getType());
1673
1674   // Try some generic simplifications for associative operations.
1675   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1676                                           MaxRecurse))
1677     return V;
1678
1679   // And distributes over Xor.  Try some generic simplifications based on this.
1680   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1681                                 Q, MaxRecurse))
1682     return V;
1683
1684   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1685   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1686   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1687   // only if B and C are equal.  If B and C are equal then (since we assume
1688   // that operands have already been simplified) "select(cond, B, C)" should
1689   // have been simplified to the common value of B and C already.  Analysing
1690   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1691   // for threading over phi nodes.
1692
1693   return 0;
1694 }
1695
1696 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
1697                              const TargetLibraryInfo *TLI,
1698                              const DominatorTree *DT) {
1699   return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
1700 }
1701
1702 static Type *GetCompareTy(Value *Op) {
1703   return CmpInst::makeCmpResultType(Op->getType());
1704 }
1705
1706 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1707 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1708 /// otherwise return null.  Helper function for analyzing max/min idioms.
1709 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1710                                          Value *LHS, Value *RHS) {
1711   SelectInst *SI = dyn_cast<SelectInst>(V);
1712   if (!SI)
1713     return 0;
1714   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1715   if (!Cmp)
1716     return 0;
1717   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1718   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1719     return Cmp;
1720   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1721       LHS == CmpRHS && RHS == CmpLHS)
1722     return Cmp;
1723   return 0;
1724 }
1725
1726 // A significant optimization not implemented here is assuming that alloca
1727 // addresses are not equal to incoming argument values. They don't *alias*,
1728 // as we say, but that doesn't mean they aren't equal, so we take a
1729 // conservative approach.
1730 //
1731 // This is inspired in part by C++11 5.10p1:
1732 //   "Two pointers of the same type compare equal if and only if they are both
1733 //    null, both point to the same function, or both represent the same
1734 //    address."
1735 //
1736 // This is pretty permissive.
1737 //
1738 // It's also partly due to C11 6.5.9p6:
1739 //   "Two pointers compare equal if and only if both are null pointers, both are
1740 //    pointers to the same object (including a pointer to an object and a
1741 //    subobject at its beginning) or function, both are pointers to one past the
1742 //    last element of the same array object, or one is a pointer to one past the
1743 //    end of one array object and the other is a pointer to the start of a
1744 //    different array object that happens to immediately follow the first array
1745 //    object in the address space.)
1746 //
1747 // C11's version is more restrictive, however there's no reason why an argument
1748 // couldn't be a one-past-the-end value for a stack object in the caller and be
1749 // equal to the beginning of a stack object in the callee.
1750 //
1751 // If the C and C++ standards are ever made sufficiently restrictive in this
1752 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1753 // this optimization.
1754 static Constant *computePointerICmp(const DataLayout *DL,
1755                                     const TargetLibraryInfo *TLI,
1756                                     CmpInst::Predicate Pred,
1757                                     Value *LHS, Value *RHS) {
1758   // First, skip past any trivial no-ops.
1759   LHS = LHS->stripPointerCasts();
1760   RHS = RHS->stripPointerCasts();
1761
1762   // A non-null pointer is not equal to a null pointer.
1763   if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1764       (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1765     return ConstantInt::get(GetCompareTy(LHS),
1766                             !CmpInst::isTrueWhenEqual(Pred));
1767
1768   // We can only fold certain predicates on pointer comparisons.
1769   switch (Pred) {
1770   default:
1771     return 0;
1772
1773     // Equality comaprisons are easy to fold.
1774   case CmpInst::ICMP_EQ:
1775   case CmpInst::ICMP_NE:
1776     break;
1777
1778     // We can only handle unsigned relational comparisons because 'inbounds' on
1779     // a GEP only protects against unsigned wrapping.
1780   case CmpInst::ICMP_UGT:
1781   case CmpInst::ICMP_UGE:
1782   case CmpInst::ICMP_ULT:
1783   case CmpInst::ICMP_ULE:
1784     // However, we have to switch them to their signed variants to handle
1785     // negative indices from the base pointer.
1786     Pred = ICmpInst::getSignedPredicate(Pred);
1787     break;
1788   }
1789
1790   // Strip off any constant offsets so that we can reason about them.
1791   // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1792   // here and compare base addresses like AliasAnalysis does, however there are
1793   // numerous hazards. AliasAnalysis and its utilities rely on special rules
1794   // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1795   // doesn't need to guarantee pointer inequality when it says NoAlias.
1796   Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1797   Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
1798
1799   // If LHS and RHS are related via constant offsets to the same base
1800   // value, we can replace it with an icmp which just compares the offsets.
1801   if (LHS == RHS)
1802     return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1803
1804   // Various optimizations for (in)equality comparisons.
1805   if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1806     // Different non-empty allocations that exist at the same time have
1807     // different addresses (if the program can tell). Global variables always
1808     // exist, so they always exist during the lifetime of each other and all
1809     // allocas. Two different allocas usually have different addresses...
1810     //
1811     // However, if there's an @llvm.stackrestore dynamically in between two
1812     // allocas, they may have the same address. It's tempting to reduce the
1813     // scope of the problem by only looking at *static* allocas here. That would
1814     // cover the majority of allocas while significantly reducing the likelihood
1815     // of having an @llvm.stackrestore pop up in the middle. However, it's not
1816     // actually impossible for an @llvm.stackrestore to pop up in the middle of
1817     // an entry block. Also, if we have a block that's not attached to a
1818     // function, we can't tell if it's "static" under the current definition.
1819     // Theoretically, this problem could be fixed by creating a new kind of
1820     // instruction kind specifically for static allocas. Such a new instruction
1821     // could be required to be at the top of the entry block, thus preventing it
1822     // from being subject to a @llvm.stackrestore. Instcombine could even
1823     // convert regular allocas into these special allocas. It'd be nifty.
1824     // However, until then, this problem remains open.
1825     //
1826     // So, we'll assume that two non-empty allocas have different addresses
1827     // for now.
1828     //
1829     // With all that, if the offsets are within the bounds of their allocations
1830     // (and not one-past-the-end! so we can't use inbounds!), and their
1831     // allocations aren't the same, the pointers are not equal.
1832     //
1833     // Note that it's not necessary to check for LHS being a global variable
1834     // address, due to canonicalization and constant folding.
1835     if (isa<AllocaInst>(LHS) &&
1836         (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
1837       ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1838       ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
1839       uint64_t LHSSize, RHSSize;
1840       if (LHSOffsetCI && RHSOffsetCI &&
1841           getObjectSize(LHS, LHSSize, DL, TLI) &&
1842           getObjectSize(RHS, RHSSize, DL, TLI)) {
1843         const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1844         const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
1845         if (!LHSOffsetValue.isNegative() &&
1846             !RHSOffsetValue.isNegative() &&
1847             LHSOffsetValue.ult(LHSSize) &&
1848             RHSOffsetValue.ult(RHSSize)) {
1849           return ConstantInt::get(GetCompareTy(LHS),
1850                                   !CmpInst::isTrueWhenEqual(Pred));
1851         }
1852       }
1853
1854       // Repeat the above check but this time without depending on DataLayout
1855       // or being able to compute a precise size.
1856       if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1857           !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1858           LHSOffset->isNullValue() &&
1859           RHSOffset->isNullValue())
1860         return ConstantInt::get(GetCompareTy(LHS),
1861                                 !CmpInst::isTrueWhenEqual(Pred));
1862     }
1863
1864     // Even if an non-inbounds GEP occurs along the path we can still optimize
1865     // equality comparisons concerning the result. We avoid walking the whole
1866     // chain again by starting where the last calls to
1867     // stripAndComputeConstantOffsets left off and accumulate the offsets.
1868     Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1869     Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
1870     if (LHS == RHS)
1871       return ConstantExpr::getICmp(Pred,
1872                                    ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1873                                    ConstantExpr::getAdd(RHSOffset, RHSNoBound));
1874   }
1875
1876   // Otherwise, fail.
1877   return 0;
1878 }
1879
1880 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1881 /// fold the result.  If not, this returns null.
1882 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1883                                const Query &Q, unsigned MaxRecurse) {
1884   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1885   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1886
1887   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1888     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1889       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
1890
1891     // If we have a constant, make sure it is on the RHS.
1892     std::swap(LHS, RHS);
1893     Pred = CmpInst::getSwappedPredicate(Pred);
1894   }
1895
1896   Type *ITy = GetCompareTy(LHS); // The return type.
1897   Type *OpTy = LHS->getType();   // The operand type.
1898
1899   // icmp X, X -> true/false
1900   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1901   // because X could be 0.
1902   if (LHS == RHS || isa<UndefValue>(RHS))
1903     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1904
1905   // Special case logic when the operands have i1 type.
1906   if (OpTy->getScalarType()->isIntegerTy(1)) {
1907     switch (Pred) {
1908     default: break;
1909     case ICmpInst::ICMP_EQ:
1910       // X == 1 -> X
1911       if (match(RHS, m_One()))
1912         return LHS;
1913       break;
1914     case ICmpInst::ICMP_NE:
1915       // X != 0 -> X
1916       if (match(RHS, m_Zero()))
1917         return LHS;
1918       break;
1919     case ICmpInst::ICMP_UGT:
1920       // X >u 0 -> X
1921       if (match(RHS, m_Zero()))
1922         return LHS;
1923       break;
1924     case ICmpInst::ICMP_UGE:
1925       // X >=u 1 -> X
1926       if (match(RHS, m_One()))
1927         return LHS;
1928       break;
1929     case ICmpInst::ICMP_SLT:
1930       // X <s 0 -> X
1931       if (match(RHS, m_Zero()))
1932         return LHS;
1933       break;
1934     case ICmpInst::ICMP_SLE:
1935       // X <=s -1 -> X
1936       if (match(RHS, m_One()))
1937         return LHS;
1938       break;
1939     }
1940   }
1941
1942   // If we are comparing with zero then try hard since this is a common case.
1943   if (match(RHS, m_Zero())) {
1944     bool LHSKnownNonNegative, LHSKnownNegative;
1945     switch (Pred) {
1946     default: llvm_unreachable("Unknown ICmp predicate!");
1947     case ICmpInst::ICMP_ULT:
1948       return getFalse(ITy);
1949     case ICmpInst::ICMP_UGE:
1950       return getTrue(ITy);
1951     case ICmpInst::ICMP_EQ:
1952     case ICmpInst::ICMP_ULE:
1953       if (isKnownNonZero(LHS, Q.DL))
1954         return getFalse(ITy);
1955       break;
1956     case ICmpInst::ICMP_NE:
1957     case ICmpInst::ICMP_UGT:
1958       if (isKnownNonZero(LHS, Q.DL))
1959         return getTrue(ITy);
1960       break;
1961     case ICmpInst::ICMP_SLT:
1962       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1963       if (LHSKnownNegative)
1964         return getTrue(ITy);
1965       if (LHSKnownNonNegative)
1966         return getFalse(ITy);
1967       break;
1968     case ICmpInst::ICMP_SLE:
1969       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1970       if (LHSKnownNegative)
1971         return getTrue(ITy);
1972       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
1973         return getFalse(ITy);
1974       break;
1975     case ICmpInst::ICMP_SGE:
1976       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1977       if (LHSKnownNegative)
1978         return getFalse(ITy);
1979       if (LHSKnownNonNegative)
1980         return getTrue(ITy);
1981       break;
1982     case ICmpInst::ICMP_SGT:
1983       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
1984       if (LHSKnownNegative)
1985         return getFalse(ITy);
1986       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
1987         return getTrue(ITy);
1988       break;
1989     }
1990   }
1991
1992   // See if we are doing a comparison with a constant integer.
1993   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1994     // Rule out tautological comparisons (eg., ult 0 or uge 0).
1995     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1996     if (RHS_CR.isEmptySet())
1997       return ConstantInt::getFalse(CI->getContext());
1998     if (RHS_CR.isFullSet())
1999       return ConstantInt::getTrue(CI->getContext());
2000
2001     // Many binary operators with constant RHS have easy to compute constant
2002     // range.  Use them to check whether the comparison is a tautology.
2003     uint32_t Width = CI->getBitWidth();
2004     APInt Lower = APInt(Width, 0);
2005     APInt Upper = APInt(Width, 0);
2006     ConstantInt *CI2;
2007     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2008       // 'urem x, CI2' produces [0, CI2).
2009       Upper = CI2->getValue();
2010     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2011       // 'srem x, CI2' produces (-|CI2|, |CI2|).
2012       Upper = CI2->getValue().abs();
2013       Lower = (-Upper) + 1;
2014     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2015       // 'udiv CI2, x' produces [0, CI2].
2016       Upper = CI2->getValue() + 1;
2017     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2018       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2019       APInt NegOne = APInt::getAllOnesValue(Width);
2020       if (!CI2->isZero())
2021         Upper = NegOne.udiv(CI2->getValue()) + 1;
2022     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2023       // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
2024       APInt IntMin = APInt::getSignedMinValue(Width);
2025       APInt IntMax = APInt::getSignedMaxValue(Width);
2026       APInt Val = CI2->getValue().abs();
2027       if (!Val.isMinValue()) {
2028         Lower = IntMin.sdiv(Val);
2029         Upper = IntMax.sdiv(Val) + 1;
2030       }
2031     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2032       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2033       APInt NegOne = APInt::getAllOnesValue(Width);
2034       if (CI2->getValue().ult(Width))
2035         Upper = NegOne.lshr(CI2->getValue()) + 1;
2036     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2037       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2038       APInt IntMin = APInt::getSignedMinValue(Width);
2039       APInt IntMax = APInt::getSignedMaxValue(Width);
2040       if (CI2->getValue().ult(Width)) {
2041         Lower = IntMin.ashr(CI2->getValue());
2042         Upper = IntMax.ashr(CI2->getValue()) + 1;
2043       }
2044     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2045       // 'or x, CI2' produces [CI2, UINT_MAX].
2046       Lower = CI2->getValue();
2047     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2048       // 'and x, CI2' produces [0, CI2].
2049       Upper = CI2->getValue() + 1;
2050     }
2051     if (Lower != Upper) {
2052       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2053       if (RHS_CR.contains(LHS_CR))
2054         return ConstantInt::getTrue(RHS->getContext());
2055       if (RHS_CR.inverse().contains(LHS_CR))
2056         return ConstantInt::getFalse(RHS->getContext());
2057     }
2058   }
2059
2060   // Compare of cast, for example (zext X) != 0 -> X != 0
2061   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2062     Instruction *LI = cast<CastInst>(LHS);
2063     Value *SrcOp = LI->getOperand(0);
2064     Type *SrcTy = SrcOp->getType();
2065     Type *DstTy = LI->getType();
2066
2067     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2068     // if the integer type is the same size as the pointer type.
2069     if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2070         Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2071       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2072         // Transfer the cast to the constant.
2073         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2074                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
2075                                         Q, MaxRecurse-1))
2076           return V;
2077       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2078         if (RI->getOperand(0)->getType() == SrcTy)
2079           // Compare without the cast.
2080           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2081                                           Q, MaxRecurse-1))
2082             return V;
2083       }
2084     }
2085
2086     if (isa<ZExtInst>(LHS)) {
2087       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2088       // same type.
2089       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2090         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2091           // Compare X and Y.  Note that signed predicates become unsigned.
2092           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2093                                           SrcOp, RI->getOperand(0), Q,
2094                                           MaxRecurse-1))
2095             return V;
2096       }
2097       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2098       // too.  If not, then try to deduce the result of the comparison.
2099       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2100         // Compute the constant that would happen if we truncated to SrcTy then
2101         // reextended to DstTy.
2102         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2103         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2104
2105         // If the re-extended constant didn't change then this is effectively
2106         // also a case of comparing two zero-extended values.
2107         if (RExt == CI && MaxRecurse)
2108           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2109                                         SrcOp, Trunc, Q, MaxRecurse-1))
2110             return V;
2111
2112         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2113         // there.  Use this to work out the result of the comparison.
2114         if (RExt != CI) {
2115           switch (Pred) {
2116           default: llvm_unreachable("Unknown ICmp predicate!");
2117           // LHS <u RHS.
2118           case ICmpInst::ICMP_EQ:
2119           case ICmpInst::ICMP_UGT:
2120           case ICmpInst::ICMP_UGE:
2121             return ConstantInt::getFalse(CI->getContext());
2122
2123           case ICmpInst::ICMP_NE:
2124           case ICmpInst::ICMP_ULT:
2125           case ICmpInst::ICMP_ULE:
2126             return ConstantInt::getTrue(CI->getContext());
2127
2128           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
2129           // is non-negative then LHS <s RHS.
2130           case ICmpInst::ICMP_SGT:
2131           case ICmpInst::ICMP_SGE:
2132             return CI->getValue().isNegative() ?
2133               ConstantInt::getTrue(CI->getContext()) :
2134               ConstantInt::getFalse(CI->getContext());
2135
2136           case ICmpInst::ICMP_SLT:
2137           case ICmpInst::ICMP_SLE:
2138             return CI->getValue().isNegative() ?
2139               ConstantInt::getFalse(CI->getContext()) :
2140               ConstantInt::getTrue(CI->getContext());
2141           }
2142         }
2143       }
2144     }
2145
2146     if (isa<SExtInst>(LHS)) {
2147       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2148       // same type.
2149       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2150         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2151           // Compare X and Y.  Note that the predicate does not change.
2152           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2153                                           Q, MaxRecurse-1))
2154             return V;
2155       }
2156       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2157       // too.  If not, then try to deduce the result of the comparison.
2158       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2159         // Compute the constant that would happen if we truncated to SrcTy then
2160         // reextended to DstTy.
2161         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2162         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2163
2164         // If the re-extended constant didn't change then this is effectively
2165         // also a case of comparing two sign-extended values.
2166         if (RExt == CI && MaxRecurse)
2167           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2168             return V;
2169
2170         // Otherwise the upper bits of LHS are all equal, while RHS has varying
2171         // bits there.  Use this to work out the result of the comparison.
2172         if (RExt != CI) {
2173           switch (Pred) {
2174           default: llvm_unreachable("Unknown ICmp predicate!");
2175           case ICmpInst::ICMP_EQ:
2176             return ConstantInt::getFalse(CI->getContext());
2177           case ICmpInst::ICMP_NE:
2178             return ConstantInt::getTrue(CI->getContext());
2179
2180           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
2181           // LHS >s RHS.
2182           case ICmpInst::ICMP_SGT:
2183           case ICmpInst::ICMP_SGE:
2184             return CI->getValue().isNegative() ?
2185               ConstantInt::getTrue(CI->getContext()) :
2186               ConstantInt::getFalse(CI->getContext());
2187           case ICmpInst::ICMP_SLT:
2188           case ICmpInst::ICMP_SLE:
2189             return CI->getValue().isNegative() ?
2190               ConstantInt::getFalse(CI->getContext()) :
2191               ConstantInt::getTrue(CI->getContext());
2192
2193           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2194           // LHS >u RHS.
2195           case ICmpInst::ICMP_UGT:
2196           case ICmpInst::ICMP_UGE:
2197             // Comparison is true iff the LHS <s 0.
2198             if (MaxRecurse)
2199               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2200                                               Constant::getNullValue(SrcTy),
2201                                               Q, MaxRecurse-1))
2202                 return V;
2203             break;
2204           case ICmpInst::ICMP_ULT:
2205           case ICmpInst::ICMP_ULE:
2206             // Comparison is true iff the LHS >=s 0.
2207             if (MaxRecurse)
2208               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2209                                               Constant::getNullValue(SrcTy),
2210                                               Q, MaxRecurse-1))
2211                 return V;
2212             break;
2213           }
2214         }
2215       }
2216     }
2217   }
2218
2219   // Special logic for binary operators.
2220   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2221   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2222   if (MaxRecurse && (LBO || RBO)) {
2223     // Analyze the case when either LHS or RHS is an add instruction.
2224     Value *A = 0, *B = 0, *C = 0, *D = 0;
2225     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2226     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2227     if (LBO && LBO->getOpcode() == Instruction::Add) {
2228       A = LBO->getOperand(0); B = LBO->getOperand(1);
2229       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2230         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2231         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2232     }
2233     if (RBO && RBO->getOpcode() == Instruction::Add) {
2234       C = RBO->getOperand(0); D = RBO->getOperand(1);
2235       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2236         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2237         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2238     }
2239
2240     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2241     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2242       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2243                                       Constant::getNullValue(RHS->getType()),
2244                                       Q, MaxRecurse-1))
2245         return V;
2246
2247     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2248     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2249       if (Value *V = SimplifyICmpInst(Pred,
2250                                       Constant::getNullValue(LHS->getType()),
2251                                       C == LHS ? D : C, Q, MaxRecurse-1))
2252         return V;
2253
2254     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2255     if (A && C && (A == C || A == D || B == C || B == D) &&
2256         NoLHSWrapProblem && NoRHSWrapProblem) {
2257       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2258       Value *Y, *Z;
2259       if (A == C) {
2260         // C + B == C + D  ->  B == D
2261         Y = B;
2262         Z = D;
2263       } else if (A == D) {
2264         // D + B == C + D  ->  B == C
2265         Y = B;
2266         Z = C;
2267       } else if (B == C) {
2268         // A + C == C + D  ->  A == D
2269         Y = A;
2270         Z = D;
2271       } else {
2272         assert(B == D);
2273         // A + D == C + D  ->  A == C
2274         Y = A;
2275         Z = C;
2276       }
2277       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2278         return V;
2279     }
2280   }
2281
2282   // icmp pred (urem X, Y), Y
2283   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2284     bool KnownNonNegative, KnownNegative;
2285     switch (Pred) {
2286     default:
2287       break;
2288     case ICmpInst::ICMP_SGT:
2289     case ICmpInst::ICMP_SGE:
2290       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
2291       if (!KnownNonNegative)
2292         break;
2293       // fall-through
2294     case ICmpInst::ICMP_EQ:
2295     case ICmpInst::ICMP_UGT:
2296     case ICmpInst::ICMP_UGE:
2297       return getFalse(ITy);
2298     case ICmpInst::ICMP_SLT:
2299     case ICmpInst::ICMP_SLE:
2300       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
2301       if (!KnownNonNegative)
2302         break;
2303       // fall-through
2304     case ICmpInst::ICMP_NE:
2305     case ICmpInst::ICMP_ULT:
2306     case ICmpInst::ICMP_ULE:
2307       return getTrue(ITy);
2308     }
2309   }
2310
2311   // icmp pred X, (urem Y, X)
2312   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2313     bool KnownNonNegative, KnownNegative;
2314     switch (Pred) {
2315     default:
2316       break;
2317     case ICmpInst::ICMP_SGT:
2318     case ICmpInst::ICMP_SGE:
2319       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
2320       if (!KnownNonNegative)
2321         break;
2322       // fall-through
2323     case ICmpInst::ICMP_NE:
2324     case ICmpInst::ICMP_UGT:
2325     case ICmpInst::ICMP_UGE:
2326       return getTrue(ITy);
2327     case ICmpInst::ICMP_SLT:
2328     case ICmpInst::ICMP_SLE:
2329       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
2330       if (!KnownNonNegative)
2331         break;
2332       // fall-through
2333     case ICmpInst::ICMP_EQ:
2334     case ICmpInst::ICMP_ULT:
2335     case ICmpInst::ICMP_ULE:
2336       return getFalse(ITy);
2337     }
2338   }
2339
2340   // x udiv y <=u x.
2341   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2342     // icmp pred (X /u Y), X
2343     if (Pred == ICmpInst::ICMP_UGT)
2344       return getFalse(ITy);
2345     if (Pred == ICmpInst::ICMP_ULE)
2346       return getTrue(ITy);
2347   }
2348
2349   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2350       LBO->getOperand(1) == RBO->getOperand(1)) {
2351     switch (LBO->getOpcode()) {
2352     default: break;
2353     case Instruction::UDiv:
2354     case Instruction::LShr:
2355       if (ICmpInst::isSigned(Pred))
2356         break;
2357       // fall-through
2358     case Instruction::SDiv:
2359     case Instruction::AShr:
2360       if (!LBO->isExact() || !RBO->isExact())
2361         break;
2362       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2363                                       RBO->getOperand(0), Q, MaxRecurse-1))
2364         return V;
2365       break;
2366     case Instruction::Shl: {
2367       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2368       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2369       if (!NUW && !NSW)
2370         break;
2371       if (!NSW && ICmpInst::isSigned(Pred))
2372         break;
2373       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2374                                       RBO->getOperand(0), Q, MaxRecurse-1))
2375         return V;
2376       break;
2377     }
2378     }
2379   }
2380
2381   // Simplify comparisons involving max/min.
2382   Value *A, *B;
2383   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2384   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2385
2386   // Signed variants on "max(a,b)>=a -> true".
2387   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2388     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2389     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2390     // We analyze this as smax(A, B) pred A.
2391     P = Pred;
2392   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2393              (A == LHS || B == LHS)) {
2394     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2395     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2396     // We analyze this as smax(A, B) swapped-pred A.
2397     P = CmpInst::getSwappedPredicate(Pred);
2398   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2399              (A == RHS || B == RHS)) {
2400     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2401     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2402     // We analyze this as smax(-A, -B) swapped-pred -A.
2403     // Note that we do not need to actually form -A or -B thanks to EqP.
2404     P = CmpInst::getSwappedPredicate(Pred);
2405   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2406              (A == LHS || B == LHS)) {
2407     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2408     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2409     // We analyze this as smax(-A, -B) pred -A.
2410     // Note that we do not need to actually form -A or -B thanks to EqP.
2411     P = Pred;
2412   }
2413   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2414     // Cases correspond to "max(A, B) p A".
2415     switch (P) {
2416     default:
2417       break;
2418     case CmpInst::ICMP_EQ:
2419     case CmpInst::ICMP_SLE:
2420       // Equivalent to "A EqP B".  This may be the same as the condition tested
2421       // in the max/min; if so, we can just return that.
2422       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2423         return V;
2424       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2425         return V;
2426       // Otherwise, see if "A EqP B" simplifies.
2427       if (MaxRecurse)
2428         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2429           return V;
2430       break;
2431     case CmpInst::ICMP_NE:
2432     case CmpInst::ICMP_SGT: {
2433       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2434       // Equivalent to "A InvEqP B".  This may be the same as the condition
2435       // tested in the max/min; if so, we can just return that.
2436       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2437         return V;
2438       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2439         return V;
2440       // Otherwise, see if "A InvEqP B" simplifies.
2441       if (MaxRecurse)
2442         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2443           return V;
2444       break;
2445     }
2446     case CmpInst::ICMP_SGE:
2447       // Always true.
2448       return getTrue(ITy);
2449     case CmpInst::ICMP_SLT:
2450       // Always false.
2451       return getFalse(ITy);
2452     }
2453   }
2454
2455   // Unsigned variants on "max(a,b)>=a -> true".
2456   P = CmpInst::BAD_ICMP_PREDICATE;
2457   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2458     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2459     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2460     // We analyze this as umax(A, B) pred A.
2461     P = Pred;
2462   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2463              (A == LHS || B == LHS)) {
2464     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2465     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2466     // We analyze this as umax(A, B) swapped-pred A.
2467     P = CmpInst::getSwappedPredicate(Pred);
2468   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2469              (A == RHS || B == RHS)) {
2470     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2471     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2472     // We analyze this as umax(-A, -B) swapped-pred -A.
2473     // Note that we do not need to actually form -A or -B thanks to EqP.
2474     P = CmpInst::getSwappedPredicate(Pred);
2475   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2476              (A == LHS || B == LHS)) {
2477     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2478     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2479     // We analyze this as umax(-A, -B) pred -A.
2480     // Note that we do not need to actually form -A or -B thanks to EqP.
2481     P = Pred;
2482   }
2483   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2484     // Cases correspond to "max(A, B) p A".
2485     switch (P) {
2486     default:
2487       break;
2488     case CmpInst::ICMP_EQ:
2489     case CmpInst::ICMP_ULE:
2490       // Equivalent to "A EqP B".  This may be the same as the condition tested
2491       // in the max/min; if so, we can just return that.
2492       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2493         return V;
2494       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2495         return V;
2496       // Otherwise, see if "A EqP B" simplifies.
2497       if (MaxRecurse)
2498         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2499           return V;
2500       break;
2501     case CmpInst::ICMP_NE:
2502     case CmpInst::ICMP_UGT: {
2503       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2504       // Equivalent to "A InvEqP B".  This may be the same as the condition
2505       // tested in the max/min; if so, we can just return that.
2506       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2507         return V;
2508       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2509         return V;
2510       // Otherwise, see if "A InvEqP B" simplifies.
2511       if (MaxRecurse)
2512         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2513           return V;
2514       break;
2515     }
2516     case CmpInst::ICMP_UGE:
2517       // Always true.
2518       return getTrue(ITy);
2519     case CmpInst::ICMP_ULT:
2520       // Always false.
2521       return getFalse(ITy);
2522     }
2523   }
2524
2525   // Variants on "max(x,y) >= min(x,z)".
2526   Value *C, *D;
2527   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2528       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2529       (A == C || A == D || B == C || B == D)) {
2530     // max(x, ?) pred min(x, ?).
2531     if (Pred == CmpInst::ICMP_SGE)
2532       // Always true.
2533       return getTrue(ITy);
2534     if (Pred == CmpInst::ICMP_SLT)
2535       // Always false.
2536       return getFalse(ITy);
2537   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2538              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2539              (A == C || A == D || B == C || B == D)) {
2540     // min(x, ?) pred max(x, ?).
2541     if (Pred == CmpInst::ICMP_SLE)
2542       // Always true.
2543       return getTrue(ITy);
2544     if (Pred == CmpInst::ICMP_SGT)
2545       // Always false.
2546       return getFalse(ITy);
2547   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2548              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2549              (A == C || A == D || B == C || B == D)) {
2550     // max(x, ?) pred min(x, ?).
2551     if (Pred == CmpInst::ICMP_UGE)
2552       // Always true.
2553       return getTrue(ITy);
2554     if (Pred == CmpInst::ICMP_ULT)
2555       // Always false.
2556       return getFalse(ITy);
2557   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2558              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2559              (A == C || A == D || B == C || B == D)) {
2560     // min(x, ?) pred max(x, ?).
2561     if (Pred == CmpInst::ICMP_ULE)
2562       // Always true.
2563       return getTrue(ITy);
2564     if (Pred == CmpInst::ICMP_UGT)
2565       // Always false.
2566       return getFalse(ITy);
2567   }
2568
2569   // Simplify comparisons of related pointers using a powerful, recursive
2570   // GEP-walk when we have target data available..
2571   if (LHS->getType()->isPointerTy())
2572     if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
2573       return C;
2574
2575   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2576     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2577       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2578           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2579           (ICmpInst::isEquality(Pred) ||
2580            (GLHS->isInBounds() && GRHS->isInBounds() &&
2581             Pred == ICmpInst::getSignedPredicate(Pred)))) {
2582         // The bases are equal and the indices are constant.  Build a constant
2583         // expression GEP with the same indices and a null base pointer to see
2584         // what constant folding can make out of it.
2585         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2586         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2587         Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2588
2589         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2590         Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2591         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2592       }
2593     }
2594   }
2595
2596   // If the comparison is with the result of a select instruction, check whether
2597   // comparing with either branch of the select always yields the same value.
2598   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2599     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2600       return V;
2601
2602   // If the comparison is with the result of a phi instruction, check whether
2603   // doing the compare with each incoming phi value yields a common result.
2604   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2605     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2606       return V;
2607
2608   return 0;
2609 }
2610
2611 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2612                               const DataLayout *DL,
2613                               const TargetLibraryInfo *TLI,
2614                               const DominatorTree *DT) {
2615   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
2616                             RecursionLimit);
2617 }
2618
2619 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2620 /// fold the result.  If not, this returns null.
2621 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2622                                const Query &Q, unsigned MaxRecurse) {
2623   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2624   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2625
2626   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2627     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2628       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2629
2630     // If we have a constant, make sure it is on the RHS.
2631     std::swap(LHS, RHS);
2632     Pred = CmpInst::getSwappedPredicate(Pred);
2633   }
2634
2635   // Fold trivial predicates.
2636   if (Pred == FCmpInst::FCMP_FALSE)
2637     return ConstantInt::get(GetCompareTy(LHS), 0);
2638   if (Pred == FCmpInst::FCMP_TRUE)
2639     return ConstantInt::get(GetCompareTy(LHS), 1);
2640
2641   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2642     return UndefValue::get(GetCompareTy(LHS));
2643
2644   // fcmp x,x -> true/false.  Not all compares are foldable.
2645   if (LHS == RHS) {
2646     if (CmpInst::isTrueWhenEqual(Pred))
2647       return ConstantInt::get(GetCompareTy(LHS), 1);
2648     if (CmpInst::isFalseWhenEqual(Pred))
2649       return ConstantInt::get(GetCompareTy(LHS), 0);
2650   }
2651
2652   // Handle fcmp with constant RHS
2653   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2654     // If the constant is a nan, see if we can fold the comparison based on it.
2655     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2656       if (CFP->getValueAPF().isNaN()) {
2657         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2658           return ConstantInt::getFalse(CFP->getContext());
2659         assert(FCmpInst::isUnordered(Pred) &&
2660                "Comparison must be either ordered or unordered!");
2661         // True if unordered.
2662         return ConstantInt::getTrue(CFP->getContext());
2663       }
2664       // Check whether the constant is an infinity.
2665       if (CFP->getValueAPF().isInfinity()) {
2666         if (CFP->getValueAPF().isNegative()) {
2667           switch (Pred) {
2668           case FCmpInst::FCMP_OLT:
2669             // No value is ordered and less than negative infinity.
2670             return ConstantInt::getFalse(CFP->getContext());
2671           case FCmpInst::FCMP_UGE:
2672             // All values are unordered with or at least negative infinity.
2673             return ConstantInt::getTrue(CFP->getContext());
2674           default:
2675             break;
2676           }
2677         } else {
2678           switch (Pred) {
2679           case FCmpInst::FCMP_OGT:
2680             // No value is ordered and greater than infinity.
2681             return ConstantInt::getFalse(CFP->getContext());
2682           case FCmpInst::FCMP_ULE:
2683             // All values are unordered with and at most infinity.
2684             return ConstantInt::getTrue(CFP->getContext());
2685           default:
2686             break;
2687           }
2688         }
2689       }
2690     }
2691   }
2692
2693   // If the comparison is with the result of a select instruction, check whether
2694   // comparing with either branch of the select always yields the same value.
2695   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2696     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2697       return V;
2698
2699   // If the comparison is with the result of a phi instruction, check whether
2700   // doing the compare with each incoming phi value yields a common result.
2701   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2702     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2703       return V;
2704
2705   return 0;
2706 }
2707
2708 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2709                               const DataLayout *DL,
2710                               const TargetLibraryInfo *TLI,
2711                               const DominatorTree *DT) {
2712   return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
2713                             RecursionLimit);
2714 }
2715
2716 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2717 /// the result.  If not, this returns null.
2718 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2719                                  Value *FalseVal, const Query &Q,
2720                                  unsigned MaxRecurse) {
2721   // select true, X, Y  -> X
2722   // select false, X, Y -> Y
2723   if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2724     if (CB->isAllOnesValue())
2725       return TrueVal;
2726     if (CB->isNullValue())
2727       return FalseVal;
2728   }
2729
2730   // select C, X, X -> X
2731   if (TrueVal == FalseVal)
2732     return TrueVal;
2733
2734   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2735     if (isa<Constant>(TrueVal))
2736       return TrueVal;
2737     return FalseVal;
2738   }
2739   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2740     return FalseVal;
2741   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2742     return TrueVal;
2743
2744   return 0;
2745 }
2746
2747 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2748                                 const DataLayout *DL,
2749                                 const TargetLibraryInfo *TLI,
2750                                 const DominatorTree *DT) {
2751   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (DL, TLI, DT),
2752                               RecursionLimit);
2753 }
2754
2755 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2756 /// fold the result.  If not, this returns null.
2757 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2758   // The type of the GEP pointer operand.
2759   PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
2760
2761   // getelementptr P -> P.
2762   if (Ops.size() == 1)
2763     return Ops[0];
2764
2765   if (isa<UndefValue>(Ops[0])) {
2766     // Compute the (pointer) type returned by the GEP instruction.
2767     Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2768     Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2769     if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
2770       GEPTy = VectorType::get(GEPTy, VT->getNumElements());
2771     return UndefValue::get(GEPTy);
2772   }
2773
2774   if (Ops.size() == 2) {
2775     // getelementptr P, 0 -> P.
2776     if (match(Ops[1], m_Zero()))
2777       return Ops[0];
2778     // getelementptr P, N -> P if P points to a type of zero size.
2779     if (Q.DL) {
2780       Type *Ty = PtrTy->getElementType();
2781       if (Ty->isSized() && Q.DL->getTypeAllocSize(Ty) == 0)
2782         return Ops[0];
2783     }
2784   }
2785
2786   // Check to see if this is constant foldable.
2787   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2788     if (!isa<Constant>(Ops[i]))
2789       return 0;
2790
2791   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2792 }
2793
2794 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
2795                              const TargetLibraryInfo *TLI,
2796                              const DominatorTree *DT) {
2797   return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT), RecursionLimit);
2798 }
2799
2800 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2801 /// can fold the result.  If not, this returns null.
2802 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2803                                       ArrayRef<unsigned> Idxs, const Query &Q,
2804                                       unsigned) {
2805   if (Constant *CAgg = dyn_cast<Constant>(Agg))
2806     if (Constant *CVal = dyn_cast<Constant>(Val))
2807       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2808
2809   // insertvalue x, undef, n -> x
2810   if (match(Val, m_Undef()))
2811     return Agg;
2812
2813   // insertvalue x, (extractvalue y, n), n
2814   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2815     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2816         EV->getIndices() == Idxs) {
2817       // insertvalue undef, (extractvalue y, n), n -> y
2818       if (match(Agg, m_Undef()))
2819         return EV->getAggregateOperand();
2820
2821       // insertvalue y, (extractvalue y, n), n -> y
2822       if (Agg == EV->getAggregateOperand())
2823         return Agg;
2824     }
2825
2826   return 0;
2827 }
2828
2829 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2830                                      ArrayRef<unsigned> Idxs,
2831                                      const DataLayout *DL,
2832                                      const TargetLibraryInfo *TLI,
2833                                      const DominatorTree *DT) {
2834   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (DL, TLI, DT),
2835                                    RecursionLimit);
2836 }
2837
2838 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2839 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
2840   // If all of the PHI's incoming values are the same then replace the PHI node
2841   // with the common value.
2842   Value *CommonValue = 0;
2843   bool HasUndefInput = false;
2844   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2845     Value *Incoming = PN->getIncomingValue(i);
2846     // If the incoming value is the phi node itself, it can safely be skipped.
2847     if (Incoming == PN) continue;
2848     if (isa<UndefValue>(Incoming)) {
2849       // Remember that we saw an undef value, but otherwise ignore them.
2850       HasUndefInput = true;
2851       continue;
2852     }
2853     if (CommonValue && Incoming != CommonValue)
2854       return 0;  // Not the same, bail out.
2855     CommonValue = Incoming;
2856   }
2857
2858   // If CommonValue is null then all of the incoming values were either undef or
2859   // equal to the phi node itself.
2860   if (!CommonValue)
2861     return UndefValue::get(PN->getType());
2862
2863   // If we have a PHI node like phi(X, undef, X), where X is defined by some
2864   // instruction, we cannot return X as the result of the PHI node unless it
2865   // dominates the PHI block.
2866   if (HasUndefInput)
2867     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
2868
2869   return CommonValue;
2870 }
2871
2872 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2873   if (Constant *C = dyn_cast<Constant>(Op))
2874     return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
2875
2876   return 0;
2877 }
2878
2879 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
2880                                const TargetLibraryInfo *TLI,
2881                                const DominatorTree *DT) {
2882   return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT), RecursionLimit);
2883 }
2884
2885 //=== Helper functions for higher up the class hierarchy.
2886
2887 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2888 /// fold the result.  If not, this returns null.
2889 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2890                             const Query &Q, unsigned MaxRecurse) {
2891   switch (Opcode) {
2892   case Instruction::Add:
2893     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2894                            Q, MaxRecurse);
2895   case Instruction::FAdd:
2896     return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2897
2898   case Instruction::Sub:
2899     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2900                            Q, MaxRecurse);
2901   case Instruction::FSub:
2902     return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2903
2904   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2905   case Instruction::FMul:
2906     return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2907   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2908   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2909   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2910   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2911   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2912   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
2913   case Instruction::Shl:
2914     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2915                            Q, MaxRecurse);
2916   case Instruction::LShr:
2917     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2918   case Instruction::AShr:
2919     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2920   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2921   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2922   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
2923   default:
2924     if (Constant *CLHS = dyn_cast<Constant>(LHS))
2925       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2926         Constant *COps[] = {CLHS, CRHS};
2927         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
2928                                         Q.TLI);
2929       }
2930
2931     // If the operation is associative, try some generic simplifications.
2932     if (Instruction::isAssociative(Opcode))
2933       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
2934         return V;
2935
2936     // If the operation is with the result of a select instruction check whether
2937     // operating on either branch of the select always yields the same value.
2938     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2939       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
2940         return V;
2941
2942     // If the operation is with the result of a phi instruction, check whether
2943     // operating on all incoming values of the phi always yields the same value.
2944     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2945       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
2946         return V;
2947
2948     return 0;
2949   }
2950 }
2951
2952 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2953                            const DataLayout *DL, const TargetLibraryInfo *TLI,
2954                            const DominatorTree *DT) {
2955   return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT), RecursionLimit);
2956 }
2957
2958 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2959 /// fold the result.
2960 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2961                               const Query &Q, unsigned MaxRecurse) {
2962   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2963     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2964   return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2965 }
2966
2967 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2968                              const DataLayout *DL, const TargetLibraryInfo *TLI,
2969                              const DominatorTree *DT) {
2970   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
2971                            RecursionLimit);
2972 }
2973
2974 static bool IsIdempotent(Intrinsic::ID ID) {
2975   switch (ID) {
2976   default: return false;
2977
2978   // Unary idempotent: f(f(x)) = f(x)
2979   case Intrinsic::fabs:
2980   case Intrinsic::floor:
2981   case Intrinsic::ceil:
2982   case Intrinsic::trunc:
2983   case Intrinsic::rint:
2984   case Intrinsic::nearbyint:
2985   case Intrinsic::round:
2986     return true;
2987   }
2988 }
2989
2990 template <typename IterTy>
2991 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
2992                                 const Query &Q, unsigned MaxRecurse) {
2993   // Perform idempotent optimizations
2994   if (!IsIdempotent(IID))
2995     return 0;
2996
2997   // Unary Ops
2998   if (std::distance(ArgBegin, ArgEnd) == 1)
2999     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3000       if (II->getIntrinsicID() == IID)
3001         return II;
3002
3003   return 0;
3004 }
3005
3006 template <typename IterTy>
3007 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
3008                            const Query &Q, unsigned MaxRecurse) {
3009   Type *Ty = V->getType();
3010   if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3011     Ty = PTy->getElementType();
3012   FunctionType *FTy = cast<FunctionType>(Ty);
3013
3014   // call undef -> undef
3015   if (isa<UndefValue>(V))
3016     return UndefValue::get(FTy->getReturnType());
3017
3018   Function *F = dyn_cast<Function>(V);
3019   if (!F)
3020     return 0;
3021
3022   if (unsigned IID = F->getIntrinsicID())
3023     if (Value *Ret =
3024         SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3025       return Ret;
3026
3027   if (!canConstantFoldCallTo(F))
3028     return 0;
3029
3030   SmallVector<Constant *, 4> ConstantArgs;
3031   ConstantArgs.reserve(ArgEnd - ArgBegin);
3032   for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3033     Constant *C = dyn_cast<Constant>(*I);
3034     if (!C)
3035       return 0;
3036     ConstantArgs.push_back(C);
3037   }
3038
3039   return ConstantFoldCall(F, ConstantArgs, Q.TLI);
3040 }
3041
3042 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
3043                           User::op_iterator ArgEnd, const DataLayout *DL,
3044                           const TargetLibraryInfo *TLI,
3045                           const DominatorTree *DT) {
3046   return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT),
3047                         RecursionLimit);
3048 }
3049
3050 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
3051                           const DataLayout *DL, const TargetLibraryInfo *TLI,
3052                           const DominatorTree *DT) {
3053   return ::SimplifyCall(V, Args.begin(), Args.end(), Query(DL, TLI, DT),
3054                         RecursionLimit);
3055 }
3056
3057 /// SimplifyInstruction - See if we can compute a simplified version of this
3058 /// instruction.  If not, this returns null.
3059 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
3060                                  const TargetLibraryInfo *TLI,
3061                                  const DominatorTree *DT) {
3062   Value *Result;
3063
3064   switch (I->getOpcode()) {
3065   default:
3066     Result = ConstantFoldInstruction(I, DL, TLI);
3067     break;
3068   case Instruction::FAdd:
3069     Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3070                               I->getFastMathFlags(), DL, TLI, DT);
3071     break;
3072   case Instruction::Add:
3073     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3074                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3075                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3076                              DL, TLI, DT);
3077     break;
3078   case Instruction::FSub:
3079     Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3080                               I->getFastMathFlags(), DL, TLI, DT);
3081     break;
3082   case Instruction::Sub:
3083     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3084                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3085                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3086                              DL, TLI, DT);
3087     break;
3088   case Instruction::FMul:
3089     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3090                               I->getFastMathFlags(), DL, TLI, DT);
3091     break;
3092   case Instruction::Mul:
3093     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3094     break;
3095   case Instruction::SDiv:
3096     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3097     break;
3098   case Instruction::UDiv:
3099     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3100     break;
3101   case Instruction::FDiv:
3102     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3103     break;
3104   case Instruction::SRem:
3105     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3106     break;
3107   case Instruction::URem:
3108     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3109     break;
3110   case Instruction::FRem:
3111     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3112     break;
3113   case Instruction::Shl:
3114     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3115                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
3116                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3117                              DL, TLI, DT);
3118     break;
3119   case Instruction::LShr:
3120     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3121                               cast<BinaryOperator>(I)->isExact(),
3122                               DL, TLI, DT);
3123     break;
3124   case Instruction::AShr:
3125     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3126                               cast<BinaryOperator>(I)->isExact(),
3127                               DL, TLI, DT);
3128     break;
3129   case Instruction::And:
3130     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3131     break;
3132   case Instruction::Or:
3133     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3134     break;
3135   case Instruction::Xor:
3136     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3137     break;
3138   case Instruction::ICmp:
3139     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
3140                               I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3141     break;
3142   case Instruction::FCmp:
3143     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
3144                               I->getOperand(0), I->getOperand(1), DL, TLI, DT);
3145     break;
3146   case Instruction::Select:
3147     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
3148                                 I->getOperand(2), DL, TLI, DT);
3149     break;
3150   case Instruction::GetElementPtr: {
3151     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
3152     Result = SimplifyGEPInst(Ops, DL, TLI, DT);
3153     break;
3154   }
3155   case Instruction::InsertValue: {
3156     InsertValueInst *IV = cast<InsertValueInst>(I);
3157     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3158                                      IV->getInsertedValueOperand(),
3159                                      IV->getIndices(), DL, TLI, DT);
3160     break;
3161   }
3162   case Instruction::PHI:
3163     Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT));
3164     break;
3165   case Instruction::Call: {
3166     CallSite CS(cast<CallInst>(I));
3167     Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3168                           DL, TLI, DT);
3169     break;
3170   }
3171   case Instruction::Trunc:
3172     Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT);
3173     break;
3174   }
3175
3176   /// If called on unreachable code, the above logic may report that the
3177   /// instruction simplified to itself.  Make life easier for users by
3178   /// detecting that case here, returning a safe value instead.
3179   return Result == I ? UndefValue::get(I->getType()) : Result;
3180 }
3181
3182 /// \brief Implementation of recursive simplification through an instructions
3183 /// uses.
3184 ///
3185 /// This is the common implementation of the recursive simplification routines.
3186 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3187 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3188 /// instructions to process and attempt to simplify it using
3189 /// InstructionSimplify.
3190 ///
3191 /// This routine returns 'true' only when *it* simplifies something. The passed
3192 /// in simplified value does not count toward this.
3193 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
3194                                               const DataLayout *DL,
3195                                               const TargetLibraryInfo *TLI,
3196                                               const DominatorTree *DT) {
3197   bool Simplified = false;
3198   SmallSetVector<Instruction *, 8> Worklist;
3199
3200   // If we have an explicit value to collapse to, do that round of the
3201   // simplification loop by hand initially.
3202   if (SimpleV) {
3203     for (User *U : I->users())
3204       if (U != I)
3205         Worklist.insert(cast<Instruction>(U));
3206
3207     // Replace the instruction with its simplified value.
3208     I->replaceAllUsesWith(SimpleV);
3209
3210     // Gracefully handle edge cases where the instruction is not wired into any
3211     // parent block.
3212     if (I->getParent())
3213       I->eraseFromParent();
3214   } else {
3215     Worklist.insert(I);
3216   }
3217
3218   // Note that we must test the size on each iteration, the worklist can grow.
3219   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3220     I = Worklist[Idx];
3221
3222     // See if this instruction simplifies.
3223     SimpleV = SimplifyInstruction(I, DL, TLI, DT);
3224     if (!SimpleV)
3225       continue;
3226
3227     Simplified = true;
3228
3229     // Stash away all the uses of the old instruction so we can check them for
3230     // recursive simplifications after a RAUW. This is cheaper than checking all
3231     // uses of To on the recursive step in most cases.
3232     for (User *U : I->users())
3233       Worklist.insert(cast<Instruction>(U));
3234
3235     // Replace the instruction with its simplified value.
3236     I->replaceAllUsesWith(SimpleV);
3237
3238     // Gracefully handle edge cases where the instruction is not wired into any
3239     // parent block.
3240     if (I->getParent())
3241       I->eraseFromParent();
3242   }
3243   return Simplified;
3244 }
3245
3246 bool llvm::recursivelySimplifyInstruction(Instruction *I,
3247                                           const DataLayout *DL,
3248                                           const TargetLibraryInfo *TLI,
3249                                           const DominatorTree *DT) {
3250   return replaceAndRecursivelySimplifyImpl(I, 0, DL, TLI, DT);
3251 }
3252
3253 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
3254                                          const DataLayout *DL,
3255                                          const TargetLibraryInfo *TLI,
3256                                          const DominatorTree *DT) {
3257   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3258   assert(SimpleV && "Must provide a simplified value.");
3259   return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT);
3260 }