Holding my nose and moving the accumulation routine to GEPOperator
[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/AliasAnalysis.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/Dominators.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/DataLayout.h"
29 #include "llvm/GlobalAlias.h"
30 #include "llvm/Operator.h"
31 #include "llvm/Support/ConstantRange.h"
32 #include "llvm/Support/GetElementPtrTypeIterator.h"
33 #include "llvm/Support/PatternMatch.h"
34 #include "llvm/Support/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 *TD;
46   const TargetLibraryInfo *TLI;
47   const DominatorTree *DT;
48
49   Query(const DataLayout *td, const TargetLibraryInfo *tli,
50         const DominatorTree *dt) : TD(td), 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.TD, 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 *TD, const TargetLibraryInfo *TLI,
655                              const DominatorTree *DT) {
656   return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, 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 static Constant *stripAndComputeConstantOffsets(const DataLayout &TD,
667                                                 Value *&V) {
668   if (!V->getType()->isPointerTy())
669     return 0;
670
671   unsigned IntPtrWidth = TD.getPointerSizeInBits();
672   APInt Offset = APInt::getNullValue(IntPtrWidth);
673
674   // Even though we don't look through PHI nodes, we could be called on an
675   // instruction in an unreachable block, which may be on a cycle.
676   SmallPtrSet<Value *, 4> Visited;
677   Visited.insert(V);
678   do {
679     if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
680       if (!GEP->isInBounds() || !GEP->accumulateConstantOffset(TD, Offset))
681         break;
682       V = GEP->getPointerOperand();
683     } else if (Operator::getOpcode(V) == Instruction::BitCast) {
684       V = cast<Operator>(V)->getOperand(0);
685     } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
686       if (GA->mayBeOverridden())
687         break;
688       V = GA->getAliasee();
689     } else {
690       break;
691     }
692     assert(V->getType()->isPointerTy() && "Unexpected operand type!");
693   } while (Visited.insert(V));
694
695   Type *IntPtrTy = TD.getIntPtrType(V->getContext());
696   return ConstantInt::get(IntPtrTy, Offset);
697 }
698
699 /// \brief Compute the constant difference between two pointer values.
700 /// If the difference is not a constant, returns zero.
701 static Constant *computePointerDifference(const DataLayout &TD,
702                                           Value *LHS, Value *RHS) {
703   Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
704   if (!LHSOffset)
705     return 0;
706   Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
707   if (!RHSOffset)
708     return 0;
709
710   // If LHS and RHS are not related via constant offsets to the same base
711   // value, there is nothing we can do here.
712   if (LHS != RHS)
713     return 0;
714
715   // Otherwise, the difference of LHS - RHS can be computed as:
716   //    LHS - RHS
717   //  = (LHSOffset + Base) - (RHSOffset + Base)
718   //  = LHSOffset - RHSOffset
719   return ConstantExpr::getSub(LHSOffset, RHSOffset);
720 }
721
722 /// SimplifySubInst - Given operands for a Sub, see if we can
723 /// fold the result.  If not, this returns null.
724 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
725                               const Query &Q, unsigned MaxRecurse) {
726   if (Constant *CLHS = dyn_cast<Constant>(Op0))
727     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
728       Constant *Ops[] = { CLHS, CRHS };
729       return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
730                                       Ops, Q.TD, Q.TLI);
731     }
732
733   // X - undef -> undef
734   // undef - X -> undef
735   if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
736     return UndefValue::get(Op0->getType());
737
738   // X - 0 -> X
739   if (match(Op1, m_Zero()))
740     return Op0;
741
742   // X - X -> 0
743   if (Op0 == Op1)
744     return Constant::getNullValue(Op0->getType());
745
746   // (X*2) - X -> X
747   // (X<<1) - X -> X
748   Value *X = 0;
749   if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
750       match(Op0, m_Shl(m_Specific(Op1), m_One())))
751     return Op1;
752
753   // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
754   // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
755   Value *Y = 0, *Z = Op1;
756   if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
757     // See if "V === Y - Z" simplifies.
758     if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
759       // It does!  Now see if "X + V" simplifies.
760       if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
761         // It does, we successfully reassociated!
762         ++NumReassoc;
763         return W;
764       }
765     // See if "V === X - Z" simplifies.
766     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
767       // It does!  Now see if "Y + V" simplifies.
768       if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
769         // It does, we successfully reassociated!
770         ++NumReassoc;
771         return W;
772       }
773   }
774
775   // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
776   // For example, X - (X + 1) -> -1
777   X = Op0;
778   if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
779     // See if "V === X - Y" simplifies.
780     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
781       // It does!  Now see if "V - Z" simplifies.
782       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
783         // It does, we successfully reassociated!
784         ++NumReassoc;
785         return W;
786       }
787     // See if "V === X - Z" simplifies.
788     if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
789       // It does!  Now see if "V - Y" simplifies.
790       if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
791         // It does, we successfully reassociated!
792         ++NumReassoc;
793         return W;
794       }
795   }
796
797   // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
798   // For example, X - (X - Y) -> Y.
799   Z = Op0;
800   if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
801     // See if "V === Z - X" simplifies.
802     if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
803       // It does!  Now see if "V + Y" simplifies.
804       if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
805         // It does, we successfully reassociated!
806         ++NumReassoc;
807         return W;
808       }
809
810   // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
811   if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
812       match(Op1, m_Trunc(m_Value(Y))))
813     if (X->getType() == Y->getType())
814       // See if "V === X - Y" simplifies.
815       if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
816         // It does!  Now see if "trunc V" simplifies.
817         if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
818           // It does, return the simplified "trunc V".
819           return W;
820
821   // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
822   if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
823       match(Op1, m_PtrToInt(m_Value(Y))))
824     if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
825       return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
826
827   // Mul distributes over Sub.  Try some generic simplifications based on this.
828   if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
829                                 Q, MaxRecurse))
830     return V;
831
832   // i1 sub -> xor.
833   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
834     if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
835       return V;
836
837   // Threading Sub over selects and phi nodes is pointless, so don't bother.
838   // Threading over the select in "A - select(cond, B, C)" means evaluating
839   // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
840   // only if B and C are equal.  If B and C are equal then (since we assume
841   // that operands have already been simplified) "select(cond, B, C)" should
842   // have been simplified to the common value of B and C already.  Analysing
843   // "A-B" and "A-C" thus gains nothing, but costs compile time.  Similarly
844   // for threading over phi nodes.
845
846   return 0;
847 }
848
849 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
850                              const DataLayout *TD, const TargetLibraryInfo *TLI,
851                              const DominatorTree *DT) {
852   return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
853                            RecursionLimit);
854 }
855
856 /// Given the operands for an FMul, see if we can fold the result
857 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
858                                FastMathFlags FMF,
859                                const Query &Q,
860                                unsigned MaxRecurse) {
861  if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
862     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
863       Constant *Ops[] = { CLHS, CRHS };
864       return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
865                                       Ops, Q.TD, Q.TLI);
866     }
867  }
868
869  // Check for some fast-math optimizations
870  if (FMF.noNaNs()) {
871    if (FMF.noSignedZeros()) {
872      // fmul N S 0, x ==> 0
873      if (match(Op0, m_Zero()))
874        return Op0;
875      if (match(Op1, m_Zero()))
876        return Op1;
877    }
878  }
879
880  return 0;
881 }
882
883 /// SimplifyMulInst - Given operands for a Mul, see if we can
884 /// fold the result.  If not, this returns null.
885 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
886                               unsigned MaxRecurse) {
887   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
888     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
889       Constant *Ops[] = { CLHS, CRHS };
890       return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
891                                       Ops, Q.TD, Q.TLI);
892     }
893
894     // Canonicalize the constant to the RHS.
895     std::swap(Op0, Op1);
896   }
897
898   // X * undef -> 0
899   if (match(Op1, m_Undef()))
900     return Constant::getNullValue(Op0->getType());
901
902   // X * 0 -> 0
903   if (match(Op1, m_Zero()))
904     return Op1;
905
906   // X * 1 -> X
907   if (match(Op1, m_One()))
908     return Op0;
909
910   // (X / Y) * Y -> X if the division is exact.
911   Value *X = 0;
912   if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
913       match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))   // Y * (X / Y)
914     return X;
915
916   // i1 mul -> and.
917   if (MaxRecurse && Op0->getType()->isIntegerTy(1))
918     if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
919       return V;
920
921   // Try some generic simplifications for associative operations.
922   if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
923                                           MaxRecurse))
924     return V;
925
926   // Mul distributes over Add.  Try some generic simplifications based on this.
927   if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
928                              Q, MaxRecurse))
929     return V;
930
931   // If the operation is with the result of a select instruction, check whether
932   // operating on either branch of the select always yields the same value.
933   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
934     if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
935                                          MaxRecurse))
936       return V;
937
938   // If the operation is with the result of a phi instruction, check whether
939   // operating on all incoming values of the phi always yields the same value.
940   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
941     if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
942                                       MaxRecurse))
943       return V;
944
945   return 0;
946 }
947
948 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
949                               FastMathFlags FMF,
950                               const DataLayout *TD,
951                               const TargetLibraryInfo *TLI,
952                               const DominatorTree *DT) {
953   return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
954 }
955
956 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
957                              const TargetLibraryInfo *TLI,
958                              const DominatorTree *DT) {
959   return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
960 }
961
962 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
963 /// fold the result.  If not, this returns null.
964 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
965                           const Query &Q, unsigned MaxRecurse) {
966   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
967     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
968       Constant *Ops[] = { C0, C1 };
969       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
970     }
971   }
972
973   bool isSigned = Opcode == Instruction::SDiv;
974
975   // X / undef -> undef
976   if (match(Op1, m_Undef()))
977     return Op1;
978
979   // undef / X -> 0
980   if (match(Op0, m_Undef()))
981     return Constant::getNullValue(Op0->getType());
982
983   // 0 / X -> 0, we don't need to preserve faults!
984   if (match(Op0, m_Zero()))
985     return Op0;
986
987   // X / 1 -> X
988   if (match(Op1, m_One()))
989     return Op0;
990
991   if (Op0->getType()->isIntegerTy(1))
992     // It can't be division by zero, hence it must be division by one.
993     return Op0;
994
995   // X / X -> 1
996   if (Op0 == Op1)
997     return ConstantInt::get(Op0->getType(), 1);
998
999   // (X * Y) / Y -> X if the multiplication does not overflow.
1000   Value *X = 0, *Y = 0;
1001   if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1002     if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1003     OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1004     // If the Mul knows it does not overflow, then we are good to go.
1005     if ((isSigned && Mul->hasNoSignedWrap()) ||
1006         (!isSigned && Mul->hasNoUnsignedWrap()))
1007       return X;
1008     // If X has the form X = A / Y then X * Y cannot overflow.
1009     if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1010       if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1011         return X;
1012   }
1013
1014   // (X rem Y) / Y -> 0
1015   if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1016       (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1017     return Constant::getNullValue(Op0->getType());
1018
1019   // If the operation is with the result of a select instruction, check whether
1020   // operating on either branch of the select always yields the same value.
1021   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1022     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1023       return V;
1024
1025   // If the operation is with the result of a phi instruction, check whether
1026   // operating on all incoming values of the phi always yields the same value.
1027   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1028     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1029       return V;
1030
1031   return 0;
1032 }
1033
1034 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1035 /// fold the result.  If not, this returns null.
1036 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1037                                unsigned MaxRecurse) {
1038   if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1039     return V;
1040
1041   return 0;
1042 }
1043
1044 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1045                               const TargetLibraryInfo *TLI,
1046                               const DominatorTree *DT) {
1047   return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1048 }
1049
1050 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1051 /// fold the result.  If not, this returns null.
1052 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1053                                unsigned MaxRecurse) {
1054   if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1055     return V;
1056
1057   return 0;
1058 }
1059
1060 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1061                               const TargetLibraryInfo *TLI,
1062                               const DominatorTree *DT) {
1063   return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1064 }
1065
1066 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1067                                unsigned) {
1068   // undef / X -> undef    (the undef could be a snan).
1069   if (match(Op0, m_Undef()))
1070     return Op0;
1071
1072   // X / undef -> undef
1073   if (match(Op1, m_Undef()))
1074     return Op1;
1075
1076   return 0;
1077 }
1078
1079 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
1080                               const TargetLibraryInfo *TLI,
1081                               const DominatorTree *DT) {
1082   return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1083 }
1084
1085 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1086 /// fold the result.  If not, this returns null.
1087 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1088                           const Query &Q, unsigned MaxRecurse) {
1089   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1090     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1091       Constant *Ops[] = { C0, C1 };
1092       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1093     }
1094   }
1095
1096   // X % undef -> undef
1097   if (match(Op1, m_Undef()))
1098     return Op1;
1099
1100   // undef % X -> 0
1101   if (match(Op0, m_Undef()))
1102     return Constant::getNullValue(Op0->getType());
1103
1104   // 0 % X -> 0, we don't need to preserve faults!
1105   if (match(Op0, m_Zero()))
1106     return Op0;
1107
1108   // X % 0 -> undef, we don't need to preserve faults!
1109   if (match(Op1, m_Zero()))
1110     return UndefValue::get(Op0->getType());
1111
1112   // X % 1 -> 0
1113   if (match(Op1, m_One()))
1114     return Constant::getNullValue(Op0->getType());
1115
1116   if (Op0->getType()->isIntegerTy(1))
1117     // It can't be remainder by zero, hence it must be remainder by one.
1118     return Constant::getNullValue(Op0->getType());
1119
1120   // X % X -> 0
1121   if (Op0 == Op1)
1122     return Constant::getNullValue(Op0->getType());
1123
1124   // If the operation is with the result of a select instruction, check whether
1125   // operating on either branch of the select always yields the same value.
1126   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1127     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1128       return V;
1129
1130   // If the operation is with the result of a phi instruction, check whether
1131   // operating on all incoming values of the phi always yields the same value.
1132   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1133     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1134       return V;
1135
1136   return 0;
1137 }
1138
1139 /// SimplifySRemInst - Given operands for an SRem, see if we can
1140 /// fold the result.  If not, this returns null.
1141 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1142                                unsigned MaxRecurse) {
1143   if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1144     return V;
1145
1146   return 0;
1147 }
1148
1149 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1150                               const TargetLibraryInfo *TLI,
1151                               const DominatorTree *DT) {
1152   return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1153 }
1154
1155 /// SimplifyURemInst - Given operands for a URem, see if we can
1156 /// fold the result.  If not, this returns null.
1157 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1158                                unsigned MaxRecurse) {
1159   if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1160     return V;
1161
1162   return 0;
1163 }
1164
1165 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1166                               const TargetLibraryInfo *TLI,
1167                               const DominatorTree *DT) {
1168   return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1169 }
1170
1171 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1172                                unsigned) {
1173   // undef % X -> undef    (the undef could be a snan).
1174   if (match(Op0, m_Undef()))
1175     return Op0;
1176
1177   // X % undef -> undef
1178   if (match(Op1, m_Undef()))
1179     return Op1;
1180
1181   return 0;
1182 }
1183
1184 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
1185                               const TargetLibraryInfo *TLI,
1186                               const DominatorTree *DT) {
1187   return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1188 }
1189
1190 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1191 /// fold the result.  If not, this returns null.
1192 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1193                             const Query &Q, unsigned MaxRecurse) {
1194   if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1195     if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1196       Constant *Ops[] = { C0, C1 };
1197       return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1198     }
1199   }
1200
1201   // 0 shift by X -> 0
1202   if (match(Op0, m_Zero()))
1203     return Op0;
1204
1205   // X shift by 0 -> X
1206   if (match(Op1, m_Zero()))
1207     return Op0;
1208
1209   // X shift by undef -> undef because it may shift by the bitwidth.
1210   if (match(Op1, m_Undef()))
1211     return Op1;
1212
1213   // Shifting by the bitwidth or more is undefined.
1214   if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1215     if (CI->getValue().getLimitedValue() >=
1216         Op0->getType()->getScalarSizeInBits())
1217       return UndefValue::get(Op0->getType());
1218
1219   // If the operation is with the result of a select instruction, check whether
1220   // operating on either branch of the select always yields the same value.
1221   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1222     if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1223       return V;
1224
1225   // If the operation is with the result of a phi instruction, check whether
1226   // operating on all incoming values of the phi always yields the same value.
1227   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1228     if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1229       return V;
1230
1231   return 0;
1232 }
1233
1234 /// SimplifyShlInst - Given operands for an Shl, see if we can
1235 /// fold the result.  If not, this returns null.
1236 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1237                               const Query &Q, unsigned MaxRecurse) {
1238   if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1239     return V;
1240
1241   // undef << X -> 0
1242   if (match(Op0, m_Undef()))
1243     return Constant::getNullValue(Op0->getType());
1244
1245   // (X >> A) << A -> X
1246   Value *X;
1247   if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1248     return X;
1249   return 0;
1250 }
1251
1252 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1253                              const DataLayout *TD, const TargetLibraryInfo *TLI,
1254                              const DominatorTree *DT) {
1255   return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1256                            RecursionLimit);
1257 }
1258
1259 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1260 /// fold the result.  If not, this returns null.
1261 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1262                                const Query &Q, unsigned MaxRecurse) {
1263   if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1264     return V;
1265
1266   // undef >>l X -> 0
1267   if (match(Op0, m_Undef()))
1268     return Constant::getNullValue(Op0->getType());
1269
1270   // (X << A) >> A -> X
1271   Value *X;
1272   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1273       cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1274     return X;
1275
1276   return 0;
1277 }
1278
1279 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1280                               const DataLayout *TD,
1281                               const TargetLibraryInfo *TLI,
1282                               const DominatorTree *DT) {
1283   return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1284                             RecursionLimit);
1285 }
1286
1287 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1288 /// fold the result.  If not, this returns null.
1289 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1290                                const Query &Q, unsigned MaxRecurse) {
1291   if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1292     return V;
1293
1294   // all ones >>a X -> all ones
1295   if (match(Op0, m_AllOnes()))
1296     return Op0;
1297
1298   // undef >>a X -> all ones
1299   if (match(Op0, m_Undef()))
1300     return Constant::getAllOnesValue(Op0->getType());
1301
1302   // (X << A) >> A -> X
1303   Value *X;
1304   if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1305       cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1306     return X;
1307
1308   return 0;
1309 }
1310
1311 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1312                               const DataLayout *TD,
1313                               const TargetLibraryInfo *TLI,
1314                               const DominatorTree *DT) {
1315   return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1316                             RecursionLimit);
1317 }
1318
1319 /// SimplifyAndInst - Given operands for an And, see if we can
1320 /// fold the result.  If not, this returns null.
1321 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1322                               unsigned MaxRecurse) {
1323   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1324     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1325       Constant *Ops[] = { CLHS, CRHS };
1326       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1327                                       Ops, Q.TD, Q.TLI);
1328     }
1329
1330     // Canonicalize the constant to the RHS.
1331     std::swap(Op0, Op1);
1332   }
1333
1334   // X & undef -> 0
1335   if (match(Op1, m_Undef()))
1336     return Constant::getNullValue(Op0->getType());
1337
1338   // X & X = X
1339   if (Op0 == Op1)
1340     return Op0;
1341
1342   // X & 0 = 0
1343   if (match(Op1, m_Zero()))
1344     return Op1;
1345
1346   // X & -1 = X
1347   if (match(Op1, m_AllOnes()))
1348     return Op0;
1349
1350   // A & ~A  =  ~A & A  =  0
1351   if (match(Op0, m_Not(m_Specific(Op1))) ||
1352       match(Op1, m_Not(m_Specific(Op0))))
1353     return Constant::getNullValue(Op0->getType());
1354
1355   // (A | ?) & A = A
1356   Value *A = 0, *B = 0;
1357   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1358       (A == Op1 || B == Op1))
1359     return Op1;
1360
1361   // A & (A | ?) = A
1362   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1363       (A == Op0 || B == Op0))
1364     return Op0;
1365
1366   // A & (-A) = A if A is a power of two or zero.
1367   if (match(Op0, m_Neg(m_Specific(Op1))) ||
1368       match(Op1, m_Neg(m_Specific(Op0)))) {
1369     if (isPowerOfTwo(Op0, Q.TD, /*OrZero*/true))
1370       return Op0;
1371     if (isPowerOfTwo(Op1, Q.TD, /*OrZero*/true))
1372       return Op1;
1373   }
1374
1375   // Try some generic simplifications for associative operations.
1376   if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1377                                           MaxRecurse))
1378     return V;
1379
1380   // And distributes over Or.  Try some generic simplifications based on this.
1381   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1382                              Q, MaxRecurse))
1383     return V;
1384
1385   // And distributes over Xor.  Try some generic simplifications based on this.
1386   if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1387                              Q, MaxRecurse))
1388     return V;
1389
1390   // Or distributes over And.  Try some generic simplifications based on this.
1391   if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1392                                 Q, MaxRecurse))
1393     return V;
1394
1395   // If the operation is with the result of a select instruction, check whether
1396   // operating on either branch of the select always yields the same value.
1397   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1398     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1399                                          MaxRecurse))
1400       return V;
1401
1402   // If the operation is with the result of a phi instruction, check whether
1403   // operating on all incoming values of the phi always yields the same value.
1404   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1405     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1406                                       MaxRecurse))
1407       return V;
1408
1409   return 0;
1410 }
1411
1412 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
1413                              const TargetLibraryInfo *TLI,
1414                              const DominatorTree *DT) {
1415   return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1416 }
1417
1418 /// SimplifyOrInst - Given operands for an Or, see if we can
1419 /// fold the result.  If not, this returns null.
1420 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1421                              unsigned MaxRecurse) {
1422   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1423     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1424       Constant *Ops[] = { CLHS, CRHS };
1425       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1426                                       Ops, Q.TD, Q.TLI);
1427     }
1428
1429     // Canonicalize the constant to the RHS.
1430     std::swap(Op0, Op1);
1431   }
1432
1433   // X | undef -> -1
1434   if (match(Op1, m_Undef()))
1435     return Constant::getAllOnesValue(Op0->getType());
1436
1437   // X | X = X
1438   if (Op0 == Op1)
1439     return Op0;
1440
1441   // X | 0 = X
1442   if (match(Op1, m_Zero()))
1443     return Op0;
1444
1445   // X | -1 = -1
1446   if (match(Op1, m_AllOnes()))
1447     return Op1;
1448
1449   // A | ~A  =  ~A | A  =  -1
1450   if (match(Op0, m_Not(m_Specific(Op1))) ||
1451       match(Op1, m_Not(m_Specific(Op0))))
1452     return Constant::getAllOnesValue(Op0->getType());
1453
1454   // (A & ?) | A = A
1455   Value *A = 0, *B = 0;
1456   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1457       (A == Op1 || B == Op1))
1458     return Op1;
1459
1460   // A | (A & ?) = A
1461   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1462       (A == Op0 || B == Op0))
1463     return Op0;
1464
1465   // ~(A & ?) | A = -1
1466   if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1467       (A == Op1 || B == Op1))
1468     return Constant::getAllOnesValue(Op1->getType());
1469
1470   // A | ~(A & ?) = -1
1471   if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1472       (A == Op0 || B == Op0))
1473     return Constant::getAllOnesValue(Op0->getType());
1474
1475   // Try some generic simplifications for associative operations.
1476   if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1477                                           MaxRecurse))
1478     return V;
1479
1480   // Or distributes over And.  Try some generic simplifications based on this.
1481   if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1482                              MaxRecurse))
1483     return V;
1484
1485   // And distributes over Or.  Try some generic simplifications based on this.
1486   if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1487                                 Q, MaxRecurse))
1488     return V;
1489
1490   // If the operation is with the result of a select instruction, check whether
1491   // operating on either branch of the select always yields the same value.
1492   if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1493     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1494                                          MaxRecurse))
1495       return V;
1496
1497   // If the operation is with the result of a phi instruction, check whether
1498   // operating on all incoming values of the phi always yields the same value.
1499   if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1500     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1501       return V;
1502
1503   return 0;
1504 }
1505
1506 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
1507                             const TargetLibraryInfo *TLI,
1508                             const DominatorTree *DT) {
1509   return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1510 }
1511
1512 /// SimplifyXorInst - Given operands for a Xor, see if we can
1513 /// fold the result.  If not, this returns null.
1514 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1515                               unsigned MaxRecurse) {
1516   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1517     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1518       Constant *Ops[] = { CLHS, CRHS };
1519       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1520                                       Ops, Q.TD, Q.TLI);
1521     }
1522
1523     // Canonicalize the constant to the RHS.
1524     std::swap(Op0, Op1);
1525   }
1526
1527   // A ^ undef -> undef
1528   if (match(Op1, m_Undef()))
1529     return Op1;
1530
1531   // A ^ 0 = A
1532   if (match(Op1, m_Zero()))
1533     return Op0;
1534
1535   // A ^ A = 0
1536   if (Op0 == Op1)
1537     return Constant::getNullValue(Op0->getType());
1538
1539   // A ^ ~A  =  ~A ^ A  =  -1
1540   if (match(Op0, m_Not(m_Specific(Op1))) ||
1541       match(Op1, m_Not(m_Specific(Op0))))
1542     return Constant::getAllOnesValue(Op0->getType());
1543
1544   // Try some generic simplifications for associative operations.
1545   if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1546                                           MaxRecurse))
1547     return V;
1548
1549   // And distributes over Xor.  Try some generic simplifications based on this.
1550   if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1551                                 Q, MaxRecurse))
1552     return V;
1553
1554   // Threading Xor over selects and phi nodes is pointless, so don't bother.
1555   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1556   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1557   // only if B and C are equal.  If B and C are equal then (since we assume
1558   // that operands have already been simplified) "select(cond, B, C)" should
1559   // have been simplified to the common value of B and C already.  Analysing
1560   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
1561   // for threading over phi nodes.
1562
1563   return 0;
1564 }
1565
1566 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
1567                              const TargetLibraryInfo *TLI,
1568                              const DominatorTree *DT) {
1569   return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1570 }
1571
1572 static Type *GetCompareTy(Value *Op) {
1573   return CmpInst::makeCmpResultType(Op->getType());
1574 }
1575
1576 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1577 /// equivalent to the comparison "LHS Pred RHS".  Return such a value if found,
1578 /// otherwise return null.  Helper function for analyzing max/min idioms.
1579 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1580                                          Value *LHS, Value *RHS) {
1581   SelectInst *SI = dyn_cast<SelectInst>(V);
1582   if (!SI)
1583     return 0;
1584   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1585   if (!Cmp)
1586     return 0;
1587   Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1588   if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1589     return Cmp;
1590   if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1591       LHS == CmpRHS && RHS == CmpLHS)
1592     return Cmp;
1593   return 0;
1594 }
1595
1596 static Constant *computePointerICmp(const DataLayout &TD,
1597                                     CmpInst::Predicate Pred,
1598                                     Value *LHS, Value *RHS) {
1599   // We can only fold certain predicates on pointer comparisons.
1600   switch (Pred) {
1601   default:
1602     return 0;
1603
1604     // Equality comaprisons are easy to fold.
1605   case CmpInst::ICMP_EQ:
1606   case CmpInst::ICMP_NE:
1607     break;
1608
1609     // We can only handle unsigned relational comparisons because 'inbounds' on
1610     // a GEP only protects against unsigned wrapping.
1611   case CmpInst::ICMP_UGT:
1612   case CmpInst::ICMP_UGE:
1613   case CmpInst::ICMP_ULT:
1614   case CmpInst::ICMP_ULE:
1615     // However, we have to switch them to their signed variants to handle
1616     // negative indices from the base pointer.
1617     Pred = ICmpInst::getSignedPredicate(Pred);
1618     break;
1619   }
1620
1621   Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
1622   if (!LHSOffset)
1623     return 0;
1624   Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
1625   if (!RHSOffset)
1626     return 0;
1627
1628   // If LHS and RHS are not related via constant offsets to the same base
1629   // value, there is nothing we can do here.
1630   if (LHS != RHS)
1631     return 0;
1632
1633   return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1634 }
1635
1636 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1637 /// fold the result.  If not, this returns null.
1638 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1639                                const Query &Q, unsigned MaxRecurse) {
1640   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1641   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1642
1643   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1644     if (Constant *CRHS = dyn_cast<Constant>(RHS))
1645       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
1646
1647     // If we have a constant, make sure it is on the RHS.
1648     std::swap(LHS, RHS);
1649     Pred = CmpInst::getSwappedPredicate(Pred);
1650   }
1651
1652   Type *ITy = GetCompareTy(LHS); // The return type.
1653   Type *OpTy = LHS->getType();   // The operand type.
1654
1655   // icmp X, X -> true/false
1656   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
1657   // because X could be 0.
1658   if (LHS == RHS || isa<UndefValue>(RHS))
1659     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1660
1661   // Special case logic when the operands have i1 type.
1662   if (OpTy->getScalarType()->isIntegerTy(1)) {
1663     switch (Pred) {
1664     default: break;
1665     case ICmpInst::ICMP_EQ:
1666       // X == 1 -> X
1667       if (match(RHS, m_One()))
1668         return LHS;
1669       break;
1670     case ICmpInst::ICMP_NE:
1671       // X != 0 -> X
1672       if (match(RHS, m_Zero()))
1673         return LHS;
1674       break;
1675     case ICmpInst::ICMP_UGT:
1676       // X >u 0 -> X
1677       if (match(RHS, m_Zero()))
1678         return LHS;
1679       break;
1680     case ICmpInst::ICMP_UGE:
1681       // X >=u 1 -> X
1682       if (match(RHS, m_One()))
1683         return LHS;
1684       break;
1685     case ICmpInst::ICMP_SLT:
1686       // X <s 0 -> X
1687       if (match(RHS, m_Zero()))
1688         return LHS;
1689       break;
1690     case ICmpInst::ICMP_SLE:
1691       // X <=s -1 -> X
1692       if (match(RHS, m_One()))
1693         return LHS;
1694       break;
1695     }
1696   }
1697
1698   // icmp <object*>, <object*/null> - Different identified objects have
1699   // different addresses (unless null), and what's more the address of an
1700   // identified local is never equal to another argument (again, barring null).
1701   // Note that generalizing to the case where LHS is a global variable address
1702   // or null is pointless, since if both LHS and RHS are constants then we
1703   // already constant folded the compare, and if only one of them is then we
1704   // moved it to RHS already.
1705   Value *LHSPtr = LHS->stripPointerCasts();
1706   Value *RHSPtr = RHS->stripPointerCasts();
1707   if (LHSPtr == RHSPtr)
1708     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1709
1710   // Be more aggressive about stripping pointer adjustments when checking a
1711   // comparison of an alloca address to another object.  We can rip off all
1712   // inbounds GEP operations, even if they are variable.
1713   LHSPtr = LHSPtr->stripInBoundsOffsets();
1714   if (llvm::isIdentifiedObject(LHSPtr)) {
1715     RHSPtr = RHSPtr->stripInBoundsOffsets();
1716     if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1717       // If both sides are different identified objects, they aren't equal
1718       // unless they're null.
1719       if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
1720           Pred == CmpInst::ICMP_EQ)
1721         return ConstantInt::get(ITy, false);
1722
1723       // A local identified object (alloca or noalias call) can't equal any
1724       // incoming argument, unless they're both null or they belong to
1725       // different functions. The latter happens during inlining.
1726       if (Instruction *LHSInst = dyn_cast<Instruction>(LHSPtr))
1727         if (Argument *RHSArg = dyn_cast<Argument>(RHSPtr))
1728           if (LHSInst->getParent()->getParent() == RHSArg->getParent() &&
1729               Pred == CmpInst::ICMP_EQ)
1730             return ConstantInt::get(ITy, false);
1731     }
1732
1733     // Assume that the constant null is on the right.
1734     if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
1735       if (Pred == CmpInst::ICMP_EQ)
1736         return ConstantInt::get(ITy, false);
1737       else if (Pred == CmpInst::ICMP_NE)
1738         return ConstantInt::get(ITy, true);
1739     }
1740   } else if (Argument *LHSArg = dyn_cast<Argument>(LHSPtr)) {
1741     RHSPtr = RHSPtr->stripInBoundsOffsets();
1742     // An alloca can't be equal to an argument unless they come from separate
1743     // functions via inlining.
1744     if (AllocaInst *RHSInst = dyn_cast<AllocaInst>(RHSPtr)) {
1745       if (LHSArg->getParent() == RHSInst->getParent()->getParent()) {
1746         if (Pred == CmpInst::ICMP_EQ)
1747           return ConstantInt::get(ITy, false);
1748         else if (Pred == CmpInst::ICMP_NE)
1749           return ConstantInt::get(ITy, true);
1750       }
1751     }
1752   }
1753
1754   // If we are comparing with zero then try hard since this is a common case.
1755   if (match(RHS, m_Zero())) {
1756     bool LHSKnownNonNegative, LHSKnownNegative;
1757     switch (Pred) {
1758     default: llvm_unreachable("Unknown ICmp predicate!");
1759     case ICmpInst::ICMP_ULT:
1760       return getFalse(ITy);
1761     case ICmpInst::ICMP_UGE:
1762       return getTrue(ITy);
1763     case ICmpInst::ICMP_EQ:
1764     case ICmpInst::ICMP_ULE:
1765       if (isKnownNonZero(LHS, Q.TD))
1766         return getFalse(ITy);
1767       break;
1768     case ICmpInst::ICMP_NE:
1769     case ICmpInst::ICMP_UGT:
1770       if (isKnownNonZero(LHS, Q.TD))
1771         return getTrue(ITy);
1772       break;
1773     case ICmpInst::ICMP_SLT:
1774       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1775       if (LHSKnownNegative)
1776         return getTrue(ITy);
1777       if (LHSKnownNonNegative)
1778         return getFalse(ITy);
1779       break;
1780     case ICmpInst::ICMP_SLE:
1781       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1782       if (LHSKnownNegative)
1783         return getTrue(ITy);
1784       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1785         return getFalse(ITy);
1786       break;
1787     case ICmpInst::ICMP_SGE:
1788       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1789       if (LHSKnownNegative)
1790         return getFalse(ITy);
1791       if (LHSKnownNonNegative)
1792         return getTrue(ITy);
1793       break;
1794     case ICmpInst::ICMP_SGT:
1795       ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1796       if (LHSKnownNegative)
1797         return getFalse(ITy);
1798       if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1799         return getTrue(ITy);
1800       break;
1801     }
1802   }
1803
1804   // See if we are doing a comparison with a constant integer.
1805   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1806     // Rule out tautological comparisons (eg., ult 0 or uge 0).
1807     ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1808     if (RHS_CR.isEmptySet())
1809       return ConstantInt::getFalse(CI->getContext());
1810     if (RHS_CR.isFullSet())
1811       return ConstantInt::getTrue(CI->getContext());
1812
1813     // Many binary operators with constant RHS have easy to compute constant
1814     // range.  Use them to check whether the comparison is a tautology.
1815     uint32_t Width = CI->getBitWidth();
1816     APInt Lower = APInt(Width, 0);
1817     APInt Upper = APInt(Width, 0);
1818     ConstantInt *CI2;
1819     if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1820       // 'urem x, CI2' produces [0, CI2).
1821       Upper = CI2->getValue();
1822     } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1823       // 'srem x, CI2' produces (-|CI2|, |CI2|).
1824       Upper = CI2->getValue().abs();
1825       Lower = (-Upper) + 1;
1826     } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1827       // 'udiv CI2, x' produces [0, CI2].
1828       Upper = CI2->getValue() + 1;
1829     } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1830       // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1831       APInt NegOne = APInt::getAllOnesValue(Width);
1832       if (!CI2->isZero())
1833         Upper = NegOne.udiv(CI2->getValue()) + 1;
1834     } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1835       // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1836       APInt IntMin = APInt::getSignedMinValue(Width);
1837       APInt IntMax = APInt::getSignedMaxValue(Width);
1838       APInt Val = CI2->getValue().abs();
1839       if (!Val.isMinValue()) {
1840         Lower = IntMin.sdiv(Val);
1841         Upper = IntMax.sdiv(Val) + 1;
1842       }
1843     } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1844       // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1845       APInt NegOne = APInt::getAllOnesValue(Width);
1846       if (CI2->getValue().ult(Width))
1847         Upper = NegOne.lshr(CI2->getValue()) + 1;
1848     } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1849       // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1850       APInt IntMin = APInt::getSignedMinValue(Width);
1851       APInt IntMax = APInt::getSignedMaxValue(Width);
1852       if (CI2->getValue().ult(Width)) {
1853         Lower = IntMin.ashr(CI2->getValue());
1854         Upper = IntMax.ashr(CI2->getValue()) + 1;
1855       }
1856     } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1857       // 'or x, CI2' produces [CI2, UINT_MAX].
1858       Lower = CI2->getValue();
1859     } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1860       // 'and x, CI2' produces [0, CI2].
1861       Upper = CI2->getValue() + 1;
1862     }
1863     if (Lower != Upper) {
1864       ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1865       if (RHS_CR.contains(LHS_CR))
1866         return ConstantInt::getTrue(RHS->getContext());
1867       if (RHS_CR.inverse().contains(LHS_CR))
1868         return ConstantInt::getFalse(RHS->getContext());
1869     }
1870   }
1871
1872   // Compare of cast, for example (zext X) != 0 -> X != 0
1873   if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1874     Instruction *LI = cast<CastInst>(LHS);
1875     Value *SrcOp = LI->getOperand(0);
1876     Type *SrcTy = SrcOp->getType();
1877     Type *DstTy = LI->getType();
1878
1879     // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1880     // if the integer type is the same size as the pointer type.
1881     if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
1882         Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1883       if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1884         // Transfer the cast to the constant.
1885         if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1886                                         ConstantExpr::getIntToPtr(RHSC, SrcTy),
1887                                         Q, MaxRecurse-1))
1888           return V;
1889       } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1890         if (RI->getOperand(0)->getType() == SrcTy)
1891           // Compare without the cast.
1892           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1893                                           Q, MaxRecurse-1))
1894             return V;
1895       }
1896     }
1897
1898     if (isa<ZExtInst>(LHS)) {
1899       // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1900       // same type.
1901       if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1902         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1903           // Compare X and Y.  Note that signed predicates become unsigned.
1904           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1905                                           SrcOp, RI->getOperand(0), Q,
1906                                           MaxRecurse-1))
1907             return V;
1908       }
1909       // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1910       // too.  If not, then try to deduce the result of the comparison.
1911       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1912         // Compute the constant that would happen if we truncated to SrcTy then
1913         // reextended to DstTy.
1914         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1915         Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1916
1917         // If the re-extended constant didn't change then this is effectively
1918         // also a case of comparing two zero-extended values.
1919         if (RExt == CI && MaxRecurse)
1920           if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1921                                         SrcOp, Trunc, Q, MaxRecurse-1))
1922             return V;
1923
1924         // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1925         // there.  Use this to work out the result of the comparison.
1926         if (RExt != CI) {
1927           switch (Pred) {
1928           default: llvm_unreachable("Unknown ICmp predicate!");
1929           // LHS <u RHS.
1930           case ICmpInst::ICMP_EQ:
1931           case ICmpInst::ICMP_UGT:
1932           case ICmpInst::ICMP_UGE:
1933             return ConstantInt::getFalse(CI->getContext());
1934
1935           case ICmpInst::ICMP_NE:
1936           case ICmpInst::ICMP_ULT:
1937           case ICmpInst::ICMP_ULE:
1938             return ConstantInt::getTrue(CI->getContext());
1939
1940           // LHS is non-negative.  If RHS is negative then LHS >s LHS.  If RHS
1941           // is non-negative then LHS <s RHS.
1942           case ICmpInst::ICMP_SGT:
1943           case ICmpInst::ICMP_SGE:
1944             return CI->getValue().isNegative() ?
1945               ConstantInt::getTrue(CI->getContext()) :
1946               ConstantInt::getFalse(CI->getContext());
1947
1948           case ICmpInst::ICMP_SLT:
1949           case ICmpInst::ICMP_SLE:
1950             return CI->getValue().isNegative() ?
1951               ConstantInt::getFalse(CI->getContext()) :
1952               ConstantInt::getTrue(CI->getContext());
1953           }
1954         }
1955       }
1956     }
1957
1958     if (isa<SExtInst>(LHS)) {
1959       // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1960       // same type.
1961       if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1962         if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1963           // Compare X and Y.  Note that the predicate does not change.
1964           if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1965                                           Q, MaxRecurse-1))
1966             return V;
1967       }
1968       // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1969       // too.  If not, then try to deduce the result of the comparison.
1970       else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1971         // Compute the constant that would happen if we truncated to SrcTy then
1972         // reextended to DstTy.
1973         Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1974         Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1975
1976         // If the re-extended constant didn't change then this is effectively
1977         // also a case of comparing two sign-extended values.
1978         if (RExt == CI && MaxRecurse)
1979           if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
1980             return V;
1981
1982         // Otherwise the upper bits of LHS are all equal, while RHS has varying
1983         // bits there.  Use this to work out the result of the comparison.
1984         if (RExt != CI) {
1985           switch (Pred) {
1986           default: llvm_unreachable("Unknown ICmp predicate!");
1987           case ICmpInst::ICMP_EQ:
1988             return ConstantInt::getFalse(CI->getContext());
1989           case ICmpInst::ICMP_NE:
1990             return ConstantInt::getTrue(CI->getContext());
1991
1992           // If RHS is non-negative then LHS <s RHS.  If RHS is negative then
1993           // LHS >s RHS.
1994           case ICmpInst::ICMP_SGT:
1995           case ICmpInst::ICMP_SGE:
1996             return CI->getValue().isNegative() ?
1997               ConstantInt::getTrue(CI->getContext()) :
1998               ConstantInt::getFalse(CI->getContext());
1999           case ICmpInst::ICMP_SLT:
2000           case ICmpInst::ICMP_SLE:
2001             return CI->getValue().isNegative() ?
2002               ConstantInt::getFalse(CI->getContext()) :
2003               ConstantInt::getTrue(CI->getContext());
2004
2005           // If LHS is non-negative then LHS <u RHS.  If LHS is negative then
2006           // LHS >u RHS.
2007           case ICmpInst::ICMP_UGT:
2008           case ICmpInst::ICMP_UGE:
2009             // Comparison is true iff the LHS <s 0.
2010             if (MaxRecurse)
2011               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2012                                               Constant::getNullValue(SrcTy),
2013                                               Q, MaxRecurse-1))
2014                 return V;
2015             break;
2016           case ICmpInst::ICMP_ULT:
2017           case ICmpInst::ICMP_ULE:
2018             // Comparison is true iff the LHS >=s 0.
2019             if (MaxRecurse)
2020               if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2021                                               Constant::getNullValue(SrcTy),
2022                                               Q, MaxRecurse-1))
2023                 return V;
2024             break;
2025           }
2026         }
2027       }
2028     }
2029   }
2030
2031   // Special logic for binary operators.
2032   BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2033   BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2034   if (MaxRecurse && (LBO || RBO)) {
2035     // Analyze the case when either LHS or RHS is an add instruction.
2036     Value *A = 0, *B = 0, *C = 0, *D = 0;
2037     // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2038     bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2039     if (LBO && LBO->getOpcode() == Instruction::Add) {
2040       A = LBO->getOperand(0); B = LBO->getOperand(1);
2041       NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2042         (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2043         (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2044     }
2045     if (RBO && RBO->getOpcode() == Instruction::Add) {
2046       C = RBO->getOperand(0); D = RBO->getOperand(1);
2047       NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2048         (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2049         (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2050     }
2051
2052     // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2053     if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2054       if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2055                                       Constant::getNullValue(RHS->getType()),
2056                                       Q, MaxRecurse-1))
2057         return V;
2058
2059     // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2060     if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2061       if (Value *V = SimplifyICmpInst(Pred,
2062                                       Constant::getNullValue(LHS->getType()),
2063                                       C == LHS ? D : C, Q, MaxRecurse-1))
2064         return V;
2065
2066     // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2067     if (A && C && (A == C || A == D || B == C || B == D) &&
2068         NoLHSWrapProblem && NoRHSWrapProblem) {
2069       // Determine Y and Z in the form icmp (X+Y), (X+Z).
2070       Value *Y, *Z;
2071       if (A == C) {
2072         // C + B == C + D  ->  B == D
2073         Y = B;
2074         Z = D;
2075       } else if (A == D) {
2076         // D + B == C + D  ->  B == C
2077         Y = B;
2078         Z = C;
2079       } else if (B == C) {
2080         // A + C == C + D  ->  A == D
2081         Y = A;
2082         Z = D;
2083       } else {
2084         assert(B == D);
2085         // A + D == C + D  ->  A == C
2086         Y = A;
2087         Z = C;
2088       }
2089       if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2090         return V;
2091     }
2092   }
2093
2094   if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2095     bool KnownNonNegative, KnownNegative;
2096     switch (Pred) {
2097     default:
2098       break;
2099     case ICmpInst::ICMP_SGT:
2100     case ICmpInst::ICMP_SGE:
2101       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2102       if (!KnownNonNegative)
2103         break;
2104       // fall-through
2105     case ICmpInst::ICMP_EQ:
2106     case ICmpInst::ICMP_UGT:
2107     case ICmpInst::ICMP_UGE:
2108       return getFalse(ITy);
2109     case ICmpInst::ICMP_SLT:
2110     case ICmpInst::ICMP_SLE:
2111       ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2112       if (!KnownNonNegative)
2113         break;
2114       // fall-through
2115     case ICmpInst::ICMP_NE:
2116     case ICmpInst::ICMP_ULT:
2117     case ICmpInst::ICMP_ULE:
2118       return getTrue(ITy);
2119     }
2120   }
2121   if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2122     bool KnownNonNegative, KnownNegative;
2123     switch (Pred) {
2124     default:
2125       break;
2126     case ICmpInst::ICMP_SGT:
2127     case ICmpInst::ICMP_SGE:
2128       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2129       if (!KnownNonNegative)
2130         break;
2131       // fall-through
2132     case ICmpInst::ICMP_NE:
2133     case ICmpInst::ICMP_UGT:
2134     case ICmpInst::ICMP_UGE:
2135       return getTrue(ITy);
2136     case ICmpInst::ICMP_SLT:
2137     case ICmpInst::ICMP_SLE:
2138       ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2139       if (!KnownNonNegative)
2140         break;
2141       // fall-through
2142     case ICmpInst::ICMP_EQ:
2143     case ICmpInst::ICMP_ULT:
2144     case ICmpInst::ICMP_ULE:
2145       return getFalse(ITy);
2146     }
2147   }
2148
2149   // x udiv y <=u x.
2150   if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2151     // icmp pred (X /u Y), X
2152     if (Pred == ICmpInst::ICMP_UGT)
2153       return getFalse(ITy);
2154     if (Pred == ICmpInst::ICMP_ULE)
2155       return getTrue(ITy);
2156   }
2157
2158   if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2159       LBO->getOperand(1) == RBO->getOperand(1)) {
2160     switch (LBO->getOpcode()) {
2161     default: break;
2162     case Instruction::UDiv:
2163     case Instruction::LShr:
2164       if (ICmpInst::isSigned(Pred))
2165         break;
2166       // fall-through
2167     case Instruction::SDiv:
2168     case Instruction::AShr:
2169       if (!LBO->isExact() || !RBO->isExact())
2170         break;
2171       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2172                                       RBO->getOperand(0), Q, MaxRecurse-1))
2173         return V;
2174       break;
2175     case Instruction::Shl: {
2176       bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2177       bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2178       if (!NUW && !NSW)
2179         break;
2180       if (!NSW && ICmpInst::isSigned(Pred))
2181         break;
2182       if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2183                                       RBO->getOperand(0), Q, MaxRecurse-1))
2184         return V;
2185       break;
2186     }
2187     }
2188   }
2189
2190   // Simplify comparisons involving max/min.
2191   Value *A, *B;
2192   CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2193   CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2194
2195   // Signed variants on "max(a,b)>=a -> true".
2196   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2197     if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2198     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2199     // We analyze this as smax(A, B) pred A.
2200     P = Pred;
2201   } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2202              (A == LHS || B == LHS)) {
2203     if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2204     EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2205     // We analyze this as smax(A, B) swapped-pred A.
2206     P = CmpInst::getSwappedPredicate(Pred);
2207   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2208              (A == RHS || B == RHS)) {
2209     if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2210     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2211     // We analyze this as smax(-A, -B) swapped-pred -A.
2212     // Note that we do not need to actually form -A or -B thanks to EqP.
2213     P = CmpInst::getSwappedPredicate(Pred);
2214   } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2215              (A == LHS || B == LHS)) {
2216     if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2217     EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2218     // We analyze this as smax(-A, -B) pred -A.
2219     // Note that we do not need to actually form -A or -B thanks to EqP.
2220     P = Pred;
2221   }
2222   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2223     // Cases correspond to "max(A, B) p A".
2224     switch (P) {
2225     default:
2226       break;
2227     case CmpInst::ICMP_EQ:
2228     case CmpInst::ICMP_SLE:
2229       // Equivalent to "A EqP B".  This may be the same as the condition tested
2230       // in the max/min; if so, we can just return that.
2231       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2232         return V;
2233       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2234         return V;
2235       // Otherwise, see if "A EqP B" simplifies.
2236       if (MaxRecurse)
2237         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2238           return V;
2239       break;
2240     case CmpInst::ICMP_NE:
2241     case CmpInst::ICMP_SGT: {
2242       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2243       // Equivalent to "A InvEqP B".  This may be the same as the condition
2244       // tested in the max/min; if so, we can just return that.
2245       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2246         return V;
2247       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2248         return V;
2249       // Otherwise, see if "A InvEqP B" simplifies.
2250       if (MaxRecurse)
2251         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2252           return V;
2253       break;
2254     }
2255     case CmpInst::ICMP_SGE:
2256       // Always true.
2257       return getTrue(ITy);
2258     case CmpInst::ICMP_SLT:
2259       // Always false.
2260       return getFalse(ITy);
2261     }
2262   }
2263
2264   // Unsigned variants on "max(a,b)>=a -> true".
2265   P = CmpInst::BAD_ICMP_PREDICATE;
2266   if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2267     if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2268     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2269     // We analyze this as umax(A, B) pred A.
2270     P = Pred;
2271   } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2272              (A == LHS || B == LHS)) {
2273     if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2274     EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2275     // We analyze this as umax(A, B) swapped-pred A.
2276     P = CmpInst::getSwappedPredicate(Pred);
2277   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2278              (A == RHS || B == RHS)) {
2279     if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2280     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2281     // We analyze this as umax(-A, -B) swapped-pred -A.
2282     // Note that we do not need to actually form -A or -B thanks to EqP.
2283     P = CmpInst::getSwappedPredicate(Pred);
2284   } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2285              (A == LHS || B == LHS)) {
2286     if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2287     EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2288     // We analyze this as umax(-A, -B) pred -A.
2289     // Note that we do not need to actually form -A or -B thanks to EqP.
2290     P = Pred;
2291   }
2292   if (P != CmpInst::BAD_ICMP_PREDICATE) {
2293     // Cases correspond to "max(A, B) p A".
2294     switch (P) {
2295     default:
2296       break;
2297     case CmpInst::ICMP_EQ:
2298     case CmpInst::ICMP_ULE:
2299       // Equivalent to "A EqP B".  This may be the same as the condition tested
2300       // in the max/min; if so, we can just return that.
2301       if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2302         return V;
2303       if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2304         return V;
2305       // Otherwise, see if "A EqP B" simplifies.
2306       if (MaxRecurse)
2307         if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2308           return V;
2309       break;
2310     case CmpInst::ICMP_NE:
2311     case CmpInst::ICMP_UGT: {
2312       CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2313       // Equivalent to "A InvEqP B".  This may be the same as the condition
2314       // tested in the max/min; if so, we can just return that.
2315       if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2316         return V;
2317       if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2318         return V;
2319       // Otherwise, see if "A InvEqP B" simplifies.
2320       if (MaxRecurse)
2321         if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2322           return V;
2323       break;
2324     }
2325     case CmpInst::ICMP_UGE:
2326       // Always true.
2327       return getTrue(ITy);
2328     case CmpInst::ICMP_ULT:
2329       // Always false.
2330       return getFalse(ITy);
2331     }
2332   }
2333
2334   // Variants on "max(x,y) >= min(x,z)".
2335   Value *C, *D;
2336   if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2337       match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2338       (A == C || A == D || B == C || B == D)) {
2339     // max(x, ?) pred min(x, ?).
2340     if (Pred == CmpInst::ICMP_SGE)
2341       // Always true.
2342       return getTrue(ITy);
2343     if (Pred == CmpInst::ICMP_SLT)
2344       // Always false.
2345       return getFalse(ITy);
2346   } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2347              match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2348              (A == C || A == D || B == C || B == D)) {
2349     // min(x, ?) pred max(x, ?).
2350     if (Pred == CmpInst::ICMP_SLE)
2351       // Always true.
2352       return getTrue(ITy);
2353     if (Pred == CmpInst::ICMP_SGT)
2354       // Always false.
2355       return getFalse(ITy);
2356   } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2357              match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2358              (A == C || A == D || B == C || B == D)) {
2359     // max(x, ?) pred min(x, ?).
2360     if (Pred == CmpInst::ICMP_UGE)
2361       // Always true.
2362       return getTrue(ITy);
2363     if (Pred == CmpInst::ICMP_ULT)
2364       // Always false.
2365       return getFalse(ITy);
2366   } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2367              match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2368              (A == C || A == D || B == C || B == D)) {
2369     // min(x, ?) pred max(x, ?).
2370     if (Pred == CmpInst::ICMP_ULE)
2371       // Always true.
2372       return getTrue(ITy);
2373     if (Pred == CmpInst::ICMP_UGT)
2374       // Always false.
2375       return getFalse(ITy);
2376   }
2377
2378   // Simplify comparisons of related pointers using a powerful, recursive
2379   // GEP-walk when we have target data available..
2380   if (Q.TD && LHS->getType()->isPointerTy() && RHS->getType()->isPointerTy())
2381     if (Constant *C = computePointerICmp(*Q.TD, Pred, LHS, RHS))
2382       return C;
2383
2384   if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2385     if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2386       if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2387           GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2388           (ICmpInst::isEquality(Pred) ||
2389            (GLHS->isInBounds() && GRHS->isInBounds() &&
2390             Pred == ICmpInst::getSignedPredicate(Pred)))) {
2391         // The bases are equal and the indices are constant.  Build a constant
2392         // expression GEP with the same indices and a null base pointer to see
2393         // what constant folding can make out of it.
2394         Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2395         SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2396         Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2397
2398         SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2399         Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2400         return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2401       }
2402     }
2403   }
2404
2405   // If the comparison is with the result of a select instruction, check whether
2406   // comparing with either branch of the select always yields the same value.
2407   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2408     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2409       return V;
2410
2411   // If the comparison is with the result of a phi instruction, check whether
2412   // doing the compare with each incoming phi value yields a common result.
2413   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2414     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2415       return V;
2416
2417   return 0;
2418 }
2419
2420 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2421                               const DataLayout *TD,
2422                               const TargetLibraryInfo *TLI,
2423                               const DominatorTree *DT) {
2424   return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2425                             RecursionLimit);
2426 }
2427
2428 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2429 /// fold the result.  If not, this returns null.
2430 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2431                                const Query &Q, unsigned MaxRecurse) {
2432   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2433   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2434
2435   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2436     if (Constant *CRHS = dyn_cast<Constant>(RHS))
2437       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
2438
2439     // If we have a constant, make sure it is on the RHS.
2440     std::swap(LHS, RHS);
2441     Pred = CmpInst::getSwappedPredicate(Pred);
2442   }
2443
2444   // Fold trivial predicates.
2445   if (Pred == FCmpInst::FCMP_FALSE)
2446     return ConstantInt::get(GetCompareTy(LHS), 0);
2447   if (Pred == FCmpInst::FCMP_TRUE)
2448     return ConstantInt::get(GetCompareTy(LHS), 1);
2449
2450   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
2451     return UndefValue::get(GetCompareTy(LHS));
2452
2453   // fcmp x,x -> true/false.  Not all compares are foldable.
2454   if (LHS == RHS) {
2455     if (CmpInst::isTrueWhenEqual(Pred))
2456       return ConstantInt::get(GetCompareTy(LHS), 1);
2457     if (CmpInst::isFalseWhenEqual(Pred))
2458       return ConstantInt::get(GetCompareTy(LHS), 0);
2459   }
2460
2461   // Handle fcmp with constant RHS
2462   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2463     // If the constant is a nan, see if we can fold the comparison based on it.
2464     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2465       if (CFP->getValueAPF().isNaN()) {
2466         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
2467           return ConstantInt::getFalse(CFP->getContext());
2468         assert(FCmpInst::isUnordered(Pred) &&
2469                "Comparison must be either ordered or unordered!");
2470         // True if unordered.
2471         return ConstantInt::getTrue(CFP->getContext());
2472       }
2473       // Check whether the constant is an infinity.
2474       if (CFP->getValueAPF().isInfinity()) {
2475         if (CFP->getValueAPF().isNegative()) {
2476           switch (Pred) {
2477           case FCmpInst::FCMP_OLT:
2478             // No value is ordered and less than negative infinity.
2479             return ConstantInt::getFalse(CFP->getContext());
2480           case FCmpInst::FCMP_UGE:
2481             // All values are unordered with or at least negative infinity.
2482             return ConstantInt::getTrue(CFP->getContext());
2483           default:
2484             break;
2485           }
2486         } else {
2487           switch (Pred) {
2488           case FCmpInst::FCMP_OGT:
2489             // No value is ordered and greater than infinity.
2490             return ConstantInt::getFalse(CFP->getContext());
2491           case FCmpInst::FCMP_ULE:
2492             // All values are unordered with and at most infinity.
2493             return ConstantInt::getTrue(CFP->getContext());
2494           default:
2495             break;
2496           }
2497         }
2498       }
2499     }
2500   }
2501
2502   // If the comparison is with the result of a select instruction, check whether
2503   // comparing with either branch of the select always yields the same value.
2504   if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2505     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2506       return V;
2507
2508   // If the comparison is with the result of a phi instruction, check whether
2509   // doing the compare with each incoming phi value yields a common result.
2510   if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2511     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2512       return V;
2513
2514   return 0;
2515 }
2516
2517 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2518                               const DataLayout *TD,
2519                               const TargetLibraryInfo *TLI,
2520                               const DominatorTree *DT) {
2521   return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2522                             RecursionLimit);
2523 }
2524
2525 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2526 /// the result.  If not, this returns null.
2527 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2528                                  Value *FalseVal, const Query &Q,
2529                                  unsigned MaxRecurse) {
2530   // select true, X, Y  -> X
2531   // select false, X, Y -> Y
2532   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2533     return CB->getZExtValue() ? TrueVal : FalseVal;
2534
2535   // select C, X, X -> X
2536   if (TrueVal == FalseVal)
2537     return TrueVal;
2538
2539   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
2540     if (isa<Constant>(TrueVal))
2541       return TrueVal;
2542     return FalseVal;
2543   }
2544   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
2545     return FalseVal;
2546   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
2547     return TrueVal;
2548
2549   return 0;
2550 }
2551
2552 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2553                                 const DataLayout *TD,
2554                                 const TargetLibraryInfo *TLI,
2555                                 const DominatorTree *DT) {
2556   return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2557                               RecursionLimit);
2558 }
2559
2560 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2561 /// fold the result.  If not, this returns null.
2562 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2563   // The type of the GEP pointer operand.
2564   PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2565   // The GEP pointer operand is not a pointer, it's a vector of pointers.
2566   if (!PtrTy)
2567     return 0;
2568
2569   // getelementptr P -> P.
2570   if (Ops.size() == 1)
2571     return Ops[0];
2572
2573   if (isa<UndefValue>(Ops[0])) {
2574     // Compute the (pointer) type returned by the GEP instruction.
2575     Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2576     Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2577     return UndefValue::get(GEPTy);
2578   }
2579
2580   if (Ops.size() == 2) {
2581     // getelementptr P, 0 -> P.
2582     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2583       if (C->isZero())
2584         return Ops[0];
2585     // getelementptr P, N -> P if P points to a type of zero size.
2586     if (Q.TD) {
2587       Type *Ty = PtrTy->getElementType();
2588       if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
2589         return Ops[0];
2590     }
2591   }
2592
2593   // Check to see if this is constant foldable.
2594   for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2595     if (!isa<Constant>(Ops[i]))
2596       return 0;
2597
2598   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2599 }
2600
2601 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
2602                              const TargetLibraryInfo *TLI,
2603                              const DominatorTree *DT) {
2604   return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2605 }
2606
2607 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2608 /// can fold the result.  If not, this returns null.
2609 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2610                                       ArrayRef<unsigned> Idxs, const Query &Q,
2611                                       unsigned) {
2612   if (Constant *CAgg = dyn_cast<Constant>(Agg))
2613     if (Constant *CVal = dyn_cast<Constant>(Val))
2614       return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2615
2616   // insertvalue x, undef, n -> x
2617   if (match(Val, m_Undef()))
2618     return Agg;
2619
2620   // insertvalue x, (extractvalue y, n), n
2621   if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2622     if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2623         EV->getIndices() == Idxs) {
2624       // insertvalue undef, (extractvalue y, n), n -> y
2625       if (match(Agg, m_Undef()))
2626         return EV->getAggregateOperand();
2627
2628       // insertvalue y, (extractvalue y, n), n -> y
2629       if (Agg == EV->getAggregateOperand())
2630         return Agg;
2631     }
2632
2633   return 0;
2634 }
2635
2636 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2637                                      ArrayRef<unsigned> Idxs,
2638                                      const DataLayout *TD,
2639                                      const TargetLibraryInfo *TLI,
2640                                      const DominatorTree *DT) {
2641   return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2642                                    RecursionLimit);
2643 }
2644
2645 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
2646 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
2647   // If all of the PHI's incoming values are the same then replace the PHI node
2648   // with the common value.
2649   Value *CommonValue = 0;
2650   bool HasUndefInput = false;
2651   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2652     Value *Incoming = PN->getIncomingValue(i);
2653     // If the incoming value is the phi node itself, it can safely be skipped.
2654     if (Incoming == PN) continue;
2655     if (isa<UndefValue>(Incoming)) {
2656       // Remember that we saw an undef value, but otherwise ignore them.
2657       HasUndefInput = true;
2658       continue;
2659     }
2660     if (CommonValue && Incoming != CommonValue)
2661       return 0;  // Not the same, bail out.
2662     CommonValue = Incoming;
2663   }
2664
2665   // If CommonValue is null then all of the incoming values were either undef or
2666   // equal to the phi node itself.
2667   if (!CommonValue)
2668     return UndefValue::get(PN->getType());
2669
2670   // If we have a PHI node like phi(X, undef, X), where X is defined by some
2671   // instruction, we cannot return X as the result of the PHI node unless it
2672   // dominates the PHI block.
2673   if (HasUndefInput)
2674     return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
2675
2676   return CommonValue;
2677 }
2678
2679 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2680   if (Constant *C = dyn_cast<Constant>(Op))
2681     return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2682
2683   return 0;
2684 }
2685
2686 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
2687                                const TargetLibraryInfo *TLI,
2688                                const DominatorTree *DT) {
2689   return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2690 }
2691
2692 //=== Helper functions for higher up the class hierarchy.
2693
2694 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2695 /// fold the result.  If not, this returns null.
2696 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2697                             const Query &Q, unsigned MaxRecurse) {
2698   switch (Opcode) {
2699   case Instruction::Add:
2700     return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2701                            Q, MaxRecurse);
2702   case Instruction::Sub:
2703     return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2704                            Q, MaxRecurse);
2705   case Instruction::Mul:  return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2706   case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2707   case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2708   case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2709   case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2710   case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2711   case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
2712   case Instruction::Shl:
2713     return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2714                            Q, MaxRecurse);
2715   case Instruction::LShr:
2716     return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2717   case Instruction::AShr:
2718     return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2719   case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2720   case Instruction::Or:  return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2721   case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
2722   default:
2723     if (Constant *CLHS = dyn_cast<Constant>(LHS))
2724       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2725         Constant *COps[] = {CLHS, CRHS};
2726         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2727                                         Q.TLI);
2728       }
2729
2730     // If the operation is associative, try some generic simplifications.
2731     if (Instruction::isAssociative(Opcode))
2732       if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
2733         return V;
2734
2735     // If the operation is with the result of a select instruction check whether
2736     // operating on either branch of the select always yields the same value.
2737     if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2738       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
2739         return V;
2740
2741     // If the operation is with the result of a phi instruction, check whether
2742     // operating on all incoming values of the phi always yields the same value.
2743     if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2744       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
2745         return V;
2746
2747     return 0;
2748   }
2749 }
2750
2751 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2752                            const DataLayout *TD, const TargetLibraryInfo *TLI,
2753                            const DominatorTree *DT) {
2754   return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
2755 }
2756
2757 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2758 /// fold the result.
2759 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2760                               const Query &Q, unsigned MaxRecurse) {
2761   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2762     return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2763   return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2764 }
2765
2766 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2767                              const DataLayout *TD, const TargetLibraryInfo *TLI,
2768                              const DominatorTree *DT) {
2769   return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2770                            RecursionLimit);
2771 }
2772
2773 static Value *SimplifyCallInst(CallInst *CI, const Query &) {
2774   // call undef -> undef
2775   if (isa<UndefValue>(CI->getCalledValue()))
2776     return UndefValue::get(CI->getType());
2777
2778   return 0;
2779 }
2780
2781 /// SimplifyInstruction - See if we can compute a simplified version of this
2782 /// instruction.  If not, this returns null.
2783 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
2784                                  const TargetLibraryInfo *TLI,
2785                                  const DominatorTree *DT) {
2786   Value *Result;
2787
2788   switch (I->getOpcode()) {
2789   default:
2790     Result = ConstantFoldInstruction(I, TD, TLI);
2791     break;
2792   case Instruction::Add:
2793     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2794                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2795                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2796                              TD, TLI, DT);
2797     break;
2798   case Instruction::Sub:
2799     Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2800                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2801                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2802                              TD, TLI, DT);
2803     break;
2804   case Instruction::FMul:
2805     Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
2806                               I->getFastMathFlags(), TD, TLI, DT);
2807     break;
2808   case Instruction::Mul:
2809     Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2810     break;
2811   case Instruction::SDiv:
2812     Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2813     break;
2814   case Instruction::UDiv:
2815     Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2816     break;
2817   case Instruction::FDiv:
2818     Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2819     break;
2820   case Instruction::SRem:
2821     Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2822     break;
2823   case Instruction::URem:
2824     Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2825     break;
2826   case Instruction::FRem:
2827     Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2828     break;
2829   case Instruction::Shl:
2830     Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2831                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
2832                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2833                              TD, TLI, DT);
2834     break;
2835   case Instruction::LShr:
2836     Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2837                               cast<BinaryOperator>(I)->isExact(),
2838                               TD, TLI, DT);
2839     break;
2840   case Instruction::AShr:
2841     Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2842                               cast<BinaryOperator>(I)->isExact(),
2843                               TD, TLI, DT);
2844     break;
2845   case Instruction::And:
2846     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2847     break;
2848   case Instruction::Or:
2849     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2850     break;
2851   case Instruction::Xor:
2852     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2853     break;
2854   case Instruction::ICmp:
2855     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2856                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2857     break;
2858   case Instruction::FCmp:
2859     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2860                               I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2861     break;
2862   case Instruction::Select:
2863     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2864                                 I->getOperand(2), TD, TLI, DT);
2865     break;
2866   case Instruction::GetElementPtr: {
2867     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2868     Result = SimplifyGEPInst(Ops, TD, TLI, DT);
2869     break;
2870   }
2871   case Instruction::InsertValue: {
2872     InsertValueInst *IV = cast<InsertValueInst>(I);
2873     Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2874                                      IV->getInsertedValueOperand(),
2875                                      IV->getIndices(), TD, TLI, DT);
2876     break;
2877   }
2878   case Instruction::PHI:
2879     Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
2880     break;
2881   case Instruction::Call:
2882     Result = SimplifyCallInst(cast<CallInst>(I), Query (TD, TLI, DT));
2883     break;
2884   case Instruction::Trunc:
2885     Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
2886     break;
2887   }
2888
2889   /// If called on unreachable code, the above logic may report that the
2890   /// instruction simplified to itself.  Make life easier for users by
2891   /// detecting that case here, returning a safe value instead.
2892   return Result == I ? UndefValue::get(I->getType()) : Result;
2893 }
2894
2895 /// \brief Implementation of recursive simplification through an instructions
2896 /// uses.
2897 ///
2898 /// This is the common implementation of the recursive simplification routines.
2899 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
2900 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
2901 /// instructions to process and attempt to simplify it using
2902 /// InstructionSimplify.
2903 ///
2904 /// This routine returns 'true' only when *it* simplifies something. The passed
2905 /// in simplified value does not count toward this.
2906 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
2907                                               const DataLayout *TD,
2908                                               const TargetLibraryInfo *TLI,
2909                                               const DominatorTree *DT) {
2910   bool Simplified = false;
2911   SmallSetVector<Instruction *, 8> Worklist;
2912
2913   // If we have an explicit value to collapse to, do that round of the
2914   // simplification loop by hand initially.
2915   if (SimpleV) {
2916     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2917          ++UI)
2918       if (*UI != I)
2919         Worklist.insert(cast<Instruction>(*UI));
2920
2921     // Replace the instruction with its simplified value.
2922     I->replaceAllUsesWith(SimpleV);
2923
2924     // Gracefully handle edge cases where the instruction is not wired into any
2925     // parent block.
2926     if (I->getParent())
2927       I->eraseFromParent();
2928   } else {
2929     Worklist.insert(I);
2930   }
2931
2932   // Note that we must test the size on each iteration, the worklist can grow.
2933   for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
2934     I = Worklist[Idx];
2935
2936     // See if this instruction simplifies.
2937     SimpleV = SimplifyInstruction(I, TD, TLI, DT);
2938     if (!SimpleV)
2939       continue;
2940
2941     Simplified = true;
2942
2943     // Stash away all the uses of the old instruction so we can check them for
2944     // recursive simplifications after a RAUW. This is cheaper than checking all
2945     // uses of To on the recursive step in most cases.
2946     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2947          ++UI)
2948       Worklist.insert(cast<Instruction>(*UI));
2949
2950     // Replace the instruction with its simplified value.
2951     I->replaceAllUsesWith(SimpleV);
2952
2953     // Gracefully handle edge cases where the instruction is not wired into any
2954     // parent block.
2955     if (I->getParent())
2956       I->eraseFromParent();
2957   }
2958   return Simplified;
2959 }
2960
2961 bool llvm::recursivelySimplifyInstruction(Instruction *I,
2962                                           const DataLayout *TD,
2963                                           const TargetLibraryInfo *TLI,
2964                                           const DominatorTree *DT) {
2965   return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
2966 }
2967
2968 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
2969                                          const DataLayout *TD,
2970                                          const TargetLibraryInfo *TLI,
2971                                          const DominatorTree *DT) {
2972   assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
2973   assert(SimpleV && "Must provide a simplified value.");
2974   return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
2975 }