75734e8770100c432ceaaff3cad3fdfa38cdcaad
[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").
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Analysis/InstructionSimplify.h"
19 #include "llvm/Analysis/ConstantFolding.h"
20 #include "llvm/Analysis/Dominators.h"
21 #include "llvm/Support/PatternMatch.h"
22 #include "llvm/Support/ValueHandle.h"
23 #include "llvm/Target/TargetData.h"
24 using namespace llvm;
25 using namespace llvm::PatternMatch;
26
27 #define RecursionLimit 3
28
29 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
30                             const DominatorTree *, unsigned);
31 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
32                               const DominatorTree *, unsigned);
33
34 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
35 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
36   Instruction *I = dyn_cast<Instruction>(V);
37   if (!I)
38     // Arguments and constants dominate all instructions.
39     return true;
40
41   // If we have a DominatorTree then do a precise test.
42   if (DT)
43     return DT->dominates(I, P);
44
45   // Otherwise, if the instruction is in the entry block, and is not an invoke,
46   // then it obviously dominates all phi nodes.
47   if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
48       !isa<InvokeInst>(I))
49     return true;
50
51   return false;
52 }
53
54 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
55 /// instruction as an operand, try to simplify the binop by seeing whether
56 /// evaluating it on both branches of the select results in the same value.
57 /// Returns the common value if so, otherwise returns null.
58 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
59                                     const TargetData *TD,
60                                     const DominatorTree *DT,
61                                     unsigned MaxRecurse) {
62   SelectInst *SI;
63   if (isa<SelectInst>(LHS)) {
64     SI = cast<SelectInst>(LHS);
65   } else {
66     assert(isa<SelectInst>(RHS) && "No select instruction operand!");
67     SI = cast<SelectInst>(RHS);
68   }
69
70   // Evaluate the BinOp on the true and false branches of the select.
71   Value *TV;
72   Value *FV;
73   if (SI == LHS) {
74     TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
75     FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
76   } else {
77     TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
78     FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
79   }
80
81   // If they simplified to the same value, then return the common value.
82   // If they both failed to simplify then return null.
83   if (TV == FV)
84     return TV;
85
86   // If one branch simplified to undef, return the other one.
87   if (TV && isa<UndefValue>(TV))
88     return FV;
89   if (FV && isa<UndefValue>(FV))
90     return TV;
91
92   // If applying the operation did not change the true and false select values,
93   // then the result of the binop is the select itself.
94   if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
95     return SI;
96
97   // If one branch simplified and the other did not, and the simplified
98   // value is equal to the unsimplified one, return the simplified value.
99   // For example, select (cond, X, X & Z) & Z -> X & Z.
100   if ((FV && !TV) || (TV && !FV)) {
101     // Check that the simplified value has the form "X op Y" where "op" is the
102     // same as the original operation.
103     Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
104     if (Simplified && Simplified->getOpcode() == Opcode) {
105       // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
106       // We already know that "op" is the same as for the simplified value.  See
107       // if the operands match too.  If so, return the simplified value.
108       Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
109       Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
110       Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
111       if (Simplified->getOperand(0) == UnsimplifiedLHS &&
112           Simplified->getOperand(1) == UnsimplifiedRHS)
113         return Simplified;
114       if (Simplified->isCommutative() &&
115           Simplified->getOperand(1) == UnsimplifiedLHS &&
116           Simplified->getOperand(0) == UnsimplifiedRHS)
117         return Simplified;
118     }
119   }
120
121   return 0;
122 }
123
124 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
125 /// try to simplify the comparison by seeing whether both branches of the select
126 /// result in the same value.  Returns the common value if so, otherwise returns
127 /// null.
128 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
129                                   Value *RHS, const TargetData *TD,
130                                   const DominatorTree *DT,
131                                   unsigned MaxRecurse) {
132   // Make sure the select is on the LHS.
133   if (!isa<SelectInst>(LHS)) {
134     std::swap(LHS, RHS);
135     Pred = CmpInst::getSwappedPredicate(Pred);
136   }
137   assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
138   SelectInst *SI = cast<SelectInst>(LHS);
139
140   // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
141   // Does "cmp TV, RHS" simplify?
142   if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
143                                     MaxRecurse))
144     // It does!  Does "cmp FV, RHS" simplify?
145     if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
146                                       MaxRecurse))
147       // It does!  If they simplified to the same value, then use it as the
148       // result of the original comparison.
149       if (TCmp == FCmp)
150         return TCmp;
151   return 0;
152 }
153
154 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
155 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
156 /// it on the incoming phi values yields the same result for every value.  If so
157 /// returns the common value, otherwise returns null.
158 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
159                                  const TargetData *TD, const DominatorTree *DT,
160                                  unsigned MaxRecurse) {
161   PHINode *PI;
162   if (isa<PHINode>(LHS)) {
163     PI = cast<PHINode>(LHS);
164     // Bail out if RHS and the phi may be mutually interdependent due to a loop.
165     if (!ValueDominatesPHI(RHS, PI, DT))
166       return 0;
167   } else {
168     assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
169     PI = cast<PHINode>(RHS);
170     // Bail out if LHS and the phi may be mutually interdependent due to a loop.
171     if (!ValueDominatesPHI(LHS, PI, DT))
172       return 0;
173   }
174
175   // Evaluate the BinOp on the incoming phi values.
176   Value *CommonValue = 0;
177   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
178     Value *Incoming = PI->getIncomingValue(i);
179     // If the incoming value is the phi node itself, it can safely be skipped.
180     if (Incoming == PI) continue;
181     Value *V = PI == LHS ?
182       SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
183       SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
184     // If the operation failed to simplify, or simplified to a different value
185     // to previously, then give up.
186     if (!V || (CommonValue && V != CommonValue))
187       return 0;
188     CommonValue = V;
189   }
190
191   return CommonValue;
192 }
193
194 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
195 /// try to simplify the comparison by seeing whether comparing with all of the
196 /// incoming phi values yields the same result every time.  If so returns the
197 /// common result, otherwise returns null.
198 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
199                                const TargetData *TD, const DominatorTree *DT,
200                                unsigned MaxRecurse) {
201   // Make sure the phi is on the LHS.
202   if (!isa<PHINode>(LHS)) {
203     std::swap(LHS, RHS);
204     Pred = CmpInst::getSwappedPredicate(Pred);
205   }
206   assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
207   PHINode *PI = cast<PHINode>(LHS);
208
209   // Bail out if RHS and the phi may be mutually interdependent due to a loop.
210   if (!ValueDominatesPHI(RHS, PI, DT))
211     return 0;
212
213   // Evaluate the BinOp on the incoming phi values.
214   Value *CommonValue = 0;
215   for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
216     Value *Incoming = PI->getIncomingValue(i);
217     // If the incoming value is the phi node itself, it can safely be skipped.
218     if (Incoming == PI) continue;
219     Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
220     // If the operation failed to simplify, or simplified to a different value
221     // to previously, then give up.
222     if (!V || (CommonValue && V != CommonValue))
223       return 0;
224     CommonValue = V;
225   }
226
227   return CommonValue;
228 }
229
230 /// SimplifyAddInst - Given operands for an Add, see if we can
231 /// fold the result.  If not, this returns null.
232 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
233                              const TargetData *TD, const DominatorTree *) {
234   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
235     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
236       Constant *Ops[] = { CLHS, CRHS };
237       return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
238                                       Ops, 2, TD);
239     }
240
241     // Canonicalize the constant to the RHS.
242     std::swap(Op0, Op1);
243   }
244
245   if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
246     // X + undef -> undef
247     if (isa<UndefValue>(Op1C))
248       return Op1C;
249
250     // X + 0 --> X
251     if (Op1C->isNullValue())
252       return Op0;
253   }
254
255   // FIXME: Could pull several more out of instcombine.
256
257   // Threading Add over selects and phi nodes is pointless, so don't bother.
258   // Threading over the select in "A + select(cond, B, C)" means evaluating
259   // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
260   // only if B and C are equal.  If B and C are equal then (since we assume
261   // that operands have already been simplified) "select(cond, B, C)" should
262   // have been simplified to the common value of B and C already.  Analysing
263   // "A+B" and "A+C" thus gains nothing, but costs compile time.  Similarly
264   // for threading over phi nodes.
265
266   return 0;
267 }
268
269 /// SimplifyAndInst - Given operands for an And, see if we can
270 /// fold the result.  If not, this returns null.
271 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
272                               const DominatorTree *DT, unsigned MaxRecurse) {
273   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
274     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
275       Constant *Ops[] = { CLHS, CRHS };
276       return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
277                                       Ops, 2, TD);
278     }
279
280     // Canonicalize the constant to the RHS.
281     std::swap(Op0, Op1);
282   }
283
284   // X & undef -> 0
285   if (isa<UndefValue>(Op1))
286     return Constant::getNullValue(Op0->getType());
287
288   // X & X = X
289   if (Op0 == Op1)
290     return Op0;
291
292   // X & 0 = 0
293   if (match(Op1, m_Zero()))
294     return Op1;
295
296   // X & -1 = X
297   if (match(Op1, m_AllOnes()))
298     return Op0;
299
300   // A & ~A  =  ~A & A  =  0
301   Value *A = 0, *B = 0;
302   if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
303       (match(Op1, m_Not(m_Value(A))) && A == Op0))
304     return Constant::getNullValue(Op0->getType());
305
306   // (A | ?) & A = A
307   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
308       (A == Op1 || B == Op1))
309     return Op1;
310
311   // A & (A | ?) = A
312   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
313       (A == Op0 || B == Op0))
314     return Op0;
315
316   // (A & B) & A -> A & B
317   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
318       (A == Op1 || B == Op1))
319     return Op0;
320
321   // A & (A & B) -> A & B
322   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
323       (A == Op0 || B == Op0))
324     return Op1;
325
326   // If the operation is with the result of a select instruction, check whether
327   // operating on either branch of the select always yields the same value.
328   if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
329     if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
330                                          MaxRecurse-1))
331       return V;
332
333   // If the operation is with the result of a phi instruction, check whether
334   // operating on all incoming values of the phi always yields the same value.
335   if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
336     if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
337                                       MaxRecurse-1))
338       return V;
339
340   return 0;
341 }
342
343 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
344                              const DominatorTree *DT) {
345   return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
346 }
347
348 /// SimplifyOrInst - Given operands for an Or, see if we can
349 /// fold the result.  If not, this returns null.
350 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
351                              const DominatorTree *DT, unsigned MaxRecurse) {
352   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
353     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
354       Constant *Ops[] = { CLHS, CRHS };
355       return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
356                                       Ops, 2, TD);
357     }
358
359     // Canonicalize the constant to the RHS.
360     std::swap(Op0, Op1);
361   }
362
363   // X | undef -> -1
364   if (isa<UndefValue>(Op1))
365     return Constant::getAllOnesValue(Op0->getType());
366
367   // X | X = X
368   if (Op0 == Op1)
369     return Op0;
370
371   // X | 0 = X
372   if (match(Op1, m_Zero()))
373     return Op0;
374
375   // X | -1 = -1
376   if (match(Op1, m_AllOnes()))
377     return Op1;
378
379   // A | ~A  =  ~A | A  =  -1
380   Value *A = 0, *B = 0;
381   if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
382       (match(Op1, m_Not(m_Value(A))) && A == Op0))
383     return Constant::getAllOnesValue(Op0->getType());
384
385   // (A & ?) | A = A
386   if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
387       (A == Op1 || B == Op1))
388     return Op1;
389
390   // A | (A & ?) = A
391   if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
392       (A == Op0 || B == Op0))
393     return Op0;
394
395   // (A | B) | A -> A | B
396   if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
397       (A == Op1 || B == Op1))
398     return Op0;
399
400   // A | (A | B) -> A | B
401   if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
402       (A == Op0 || B == Op0))
403     return Op1;
404
405   // If the operation is with the result of a select instruction, check whether
406   // operating on either branch of the select always yields the same value.
407   if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
408     if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
409                                          MaxRecurse-1))
410       return V;
411
412   // If the operation is with the result of a phi instruction, check whether
413   // operating on all incoming values of the phi always yields the same value.
414   if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
415     if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
416                                       MaxRecurse-1))
417       return V;
418
419   return 0;
420 }
421
422 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
423                             const DominatorTree *DT) {
424   return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
425 }
426
427 /// SimplifyXorInst - Given operands for a Xor, see if we can
428 /// fold the result.  If not, this returns null.
429 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
430                               const DominatorTree *DT, unsigned MaxRecurse) {
431   if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
432     if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
433       Constant *Ops[] = { CLHS, CRHS };
434       return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
435                                       Ops, 2, TD);
436     }
437
438     // Canonicalize the constant to the RHS.
439     std::swap(Op0, Op1);
440   }
441
442   // A ^ undef -> undef
443   if (isa<UndefValue>(Op1))
444     return Op1;
445
446   // A ^ 0 = A
447   if (match(Op1, m_Zero()))
448     return Op0;
449
450   // A ^ A = 0
451   if (Op0 == Op1)
452     return Constant::getNullValue(Op0->getType());
453
454   // A ^ ~A  =  ~A ^ A  =  -1
455   Value *A = 0, *B = 0;
456   if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
457       (match(Op1, m_Not(m_Value(A))) && A == Op0))
458     return Constant::getAllOnesValue(Op0->getType());
459
460   // (A ^ B) ^ A = B
461   if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
462       (A == Op1 || B == Op1))
463     return A == Op1 ? B : A;
464
465   // A ^ (A ^ B) = B
466   if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
467       (A == Op0 || B == Op0))
468     return A == Op0 ? B : A;
469
470   // Threading Xor over selects and phi nodes is pointless, so don't bother.
471   // Threading over the select in "A ^ select(cond, B, C)" means evaluating
472   // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
473   // only if B and C are equal.  If B and C are equal then (since we assume
474   // that operands have already been simplified) "select(cond, B, C)" should
475   // have been simplified to the common value of B and C already.  Analysing
476   // "A^B" and "A^C" thus gains nothing, but costs compile time.  Similarly
477   // for threading over phi nodes.
478
479   return 0;
480 }
481
482 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
483                              const DominatorTree *DT) {
484   return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
485 }
486
487 static const Type *GetCompareTy(Value *Op) {
488   return CmpInst::makeCmpResultType(Op->getType());
489 }
490
491 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
492 /// fold the result.  If not, this returns null.
493 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
494                                const TargetData *TD, const DominatorTree *DT,
495                                unsigned MaxRecurse) {
496   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
497   assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
498
499   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
500     if (Constant *CRHS = dyn_cast<Constant>(RHS))
501       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
502
503     // If we have a constant, make sure it is on the RHS.
504     std::swap(LHS, RHS);
505     Pred = CmpInst::getSwappedPredicate(Pred);
506   }
507
508   // ITy - This is the return type of the compare we're considering.
509   const Type *ITy = GetCompareTy(LHS);
510
511   // icmp X, X -> true/false
512   // X icmp undef -> true/false.  For example, icmp ugt %X, undef -> false
513   // because X could be 0.
514   if (LHS == RHS || isa<UndefValue>(RHS))
515     return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
516
517   // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
518   // addresses never equal each other!  We already know that Op0 != Op1.
519   if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
520        isa<ConstantPointerNull>(LHS)) &&
521       (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
522        isa<ConstantPointerNull>(RHS)))
523     return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
524
525   // See if we are doing a comparison with a constant.
526   if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
527     // If we have an icmp le or icmp ge instruction, turn it into the
528     // appropriate icmp lt or icmp gt instruction.  This allows us to rely on
529     // them being folded in the code below.
530     switch (Pred) {
531     default: break;
532     case ICmpInst::ICMP_ULE:
533       if (CI->isMaxValue(false))                 // A <=u MAX -> TRUE
534         return ConstantInt::getTrue(CI->getContext());
535       break;
536     case ICmpInst::ICMP_SLE:
537       if (CI->isMaxValue(true))                  // A <=s MAX -> TRUE
538         return ConstantInt::getTrue(CI->getContext());
539       break;
540     case ICmpInst::ICMP_UGE:
541       if (CI->isMinValue(false))                 // A >=u MIN -> TRUE
542         return ConstantInt::getTrue(CI->getContext());
543       break;
544     case ICmpInst::ICMP_SGE:
545       if (CI->isMinValue(true))                  // A >=s MIN -> TRUE
546         return ConstantInt::getTrue(CI->getContext());
547       break;
548     }
549   }
550
551   // If the comparison is with the result of a select instruction, check whether
552   // comparing with either branch of the select always yields the same value.
553   if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
554     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
555       return V;
556
557   // If the comparison is with the result of a phi instruction, check whether
558   // doing the compare with each incoming phi value yields a common result.
559   if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
560     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
561       return V;
562
563   return 0;
564 }
565
566 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
567                               const TargetData *TD, const DominatorTree *DT) {
568   return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
569 }
570
571 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
572 /// fold the result.  If not, this returns null.
573 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
574                                const TargetData *TD, const DominatorTree *DT,
575                                unsigned MaxRecurse) {
576   CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
577   assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
578
579   if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
580     if (Constant *CRHS = dyn_cast<Constant>(RHS))
581       return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
582
583     // If we have a constant, make sure it is on the RHS.
584     std::swap(LHS, RHS);
585     Pred = CmpInst::getSwappedPredicate(Pred);
586   }
587
588   // Fold trivial predicates.
589   if (Pred == FCmpInst::FCMP_FALSE)
590     return ConstantInt::get(GetCompareTy(LHS), 0);
591   if (Pred == FCmpInst::FCMP_TRUE)
592     return ConstantInt::get(GetCompareTy(LHS), 1);
593
594   if (isa<UndefValue>(RHS))                  // fcmp pred X, undef -> undef
595     return UndefValue::get(GetCompareTy(LHS));
596
597   // fcmp x,x -> true/false.  Not all compares are foldable.
598   if (LHS == RHS) {
599     if (CmpInst::isTrueWhenEqual(Pred))
600       return ConstantInt::get(GetCompareTy(LHS), 1);
601     if (CmpInst::isFalseWhenEqual(Pred))
602       return ConstantInt::get(GetCompareTy(LHS), 0);
603   }
604
605   // Handle fcmp with constant RHS
606   if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
607     // If the constant is a nan, see if we can fold the comparison based on it.
608     if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
609       if (CFP->getValueAPF().isNaN()) {
610         if (FCmpInst::isOrdered(Pred))   // True "if ordered and foo"
611           return ConstantInt::getFalse(CFP->getContext());
612         assert(FCmpInst::isUnordered(Pred) &&
613                "Comparison must be either ordered or unordered!");
614         // True if unordered.
615         return ConstantInt::getTrue(CFP->getContext());
616       }
617       // Check whether the constant is an infinity.
618       if (CFP->getValueAPF().isInfinity()) {
619         if (CFP->getValueAPF().isNegative()) {
620           switch (Pred) {
621           case FCmpInst::FCMP_OLT:
622             // No value is ordered and less than negative infinity.
623             return ConstantInt::getFalse(CFP->getContext());
624           case FCmpInst::FCMP_UGE:
625             // All values are unordered with or at least negative infinity.
626             return ConstantInt::getTrue(CFP->getContext());
627           default:
628             break;
629           }
630         } else {
631           switch (Pred) {
632           case FCmpInst::FCMP_OGT:
633             // No value is ordered and greater than infinity.
634             return ConstantInt::getFalse(CFP->getContext());
635           case FCmpInst::FCMP_ULE:
636             // All values are unordered with and at most infinity.
637             return ConstantInt::getTrue(CFP->getContext());
638           default:
639             break;
640           }
641         }
642       }
643     }
644   }
645
646   // If the comparison is with the result of a select instruction, check whether
647   // comparing with either branch of the select always yields the same value.
648   if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
649     if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
650       return V;
651
652   // If the comparison is with the result of a phi instruction, check whether
653   // doing the compare with each incoming phi value yields a common result.
654   if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
655     if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
656       return V;
657
658   return 0;
659 }
660
661 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
662                               const TargetData *TD, const DominatorTree *DT) {
663   return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
664 }
665
666 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
667 /// the result.  If not, this returns null.
668 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
669                                 const TargetData *TD, const DominatorTree *) {
670   // select true, X, Y  -> X
671   // select false, X, Y -> Y
672   if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
673     return CB->getZExtValue() ? TrueVal : FalseVal;
674
675   // select C, X, X -> X
676   if (TrueVal == FalseVal)
677     return TrueVal;
678
679   if (isa<UndefValue>(TrueVal))   // select C, undef, X -> X
680     return FalseVal;
681   if (isa<UndefValue>(FalseVal))   // select C, X, undef -> X
682     return TrueVal;
683   if (isa<UndefValue>(CondVal)) {  // select undef, X, Y -> X or Y
684     if (isa<Constant>(TrueVal))
685       return TrueVal;
686     return FalseVal;
687   }
688
689   return 0;
690 }
691
692 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
693 /// fold the result.  If not, this returns null.
694 Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
695                              const TargetData *TD, const DominatorTree *) {
696   // The type of the GEP pointer operand.
697   const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
698
699   // getelementptr P -> P.
700   if (NumOps == 1)
701     return Ops[0];
702
703   if (isa<UndefValue>(Ops[0])) {
704     // Compute the (pointer) type returned by the GEP instruction.
705     const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
706                                                              NumOps-1);
707     const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
708     return UndefValue::get(GEPTy);
709   }
710
711   if (NumOps == 2) {
712     // getelementptr P, 0 -> P.
713     if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
714       if (C->isZero())
715         return Ops[0];
716     // getelementptr P, N -> P if P points to a type of zero size.
717     if (TD) {
718       const Type *Ty = PtrTy->getElementType();
719       if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
720         return Ops[0];
721     }
722   }
723
724   // Check to see if this is constant foldable.
725   for (unsigned i = 0; i != NumOps; ++i)
726     if (!isa<Constant>(Ops[i]))
727       return 0;
728
729   return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
730                                         (Constant *const*)Ops+1, NumOps-1);
731 }
732
733 /// SimplifyPHINode - See if we can fold the given phi.  If not, returns null.
734 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
735   // If all of the PHI's incoming values are the same then replace the PHI node
736   // with the common value.
737   Value *CommonValue = 0;
738   bool HasUndefInput = false;
739   for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
740     Value *Incoming = PN->getIncomingValue(i);
741     // If the incoming value is the phi node itself, it can safely be skipped.
742     if (Incoming == PN) continue;
743     if (isa<UndefValue>(Incoming)) {
744       // Remember that we saw an undef value, but otherwise ignore them.
745       HasUndefInput = true;
746       continue;
747     }
748     if (CommonValue && Incoming != CommonValue)
749       return 0;  // Not the same, bail out.
750     CommonValue = Incoming;
751   }
752
753   // If CommonValue is null then all of the incoming values were either undef or
754   // equal to the phi node itself.
755   if (!CommonValue)
756     return UndefValue::get(PN->getType());
757
758   // If we have a PHI node like phi(X, undef, X), where X is defined by some
759   // instruction, we cannot return X as the result of the PHI node unless it
760   // dominates the PHI block.
761   if (HasUndefInput)
762     return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
763
764   return CommonValue;
765 }
766
767
768 //=== Helper functions for higher up the class hierarchy.
769
770 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
771 /// fold the result.  If not, this returns null.
772 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
773                             const TargetData *TD, const DominatorTree *DT,
774                             unsigned MaxRecurse) {
775   switch (Opcode) {
776   case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
777   case Instruction::Or:  return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
778   default:
779     if (Constant *CLHS = dyn_cast<Constant>(LHS))
780       if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
781         Constant *COps[] = {CLHS, CRHS};
782         return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
783       }
784
785     // If the operation is with the result of a select instruction, check whether
786     // operating on either branch of the select always yields the same value.
787     if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
788       if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
789                                            MaxRecurse-1))
790         return V;
791
792     // If the operation is with the result of a phi instruction, check whether
793     // operating on all incoming values of the phi always yields the same value.
794     if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
795       if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
796         return V;
797
798     return 0;
799   }
800 }
801
802 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
803                            const TargetData *TD, const DominatorTree *DT) {
804   return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
805 }
806
807 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
808 /// fold the result.
809 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
810                               const TargetData *TD, const DominatorTree *DT,
811                               unsigned MaxRecurse) {
812   if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
813     return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
814   return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
815 }
816
817 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
818                              const TargetData *TD, const DominatorTree *DT) {
819   return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
820 }
821
822 /// SimplifyInstruction - See if we can compute a simplified version of this
823 /// instruction.  If not, this returns null.
824 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
825                                  const DominatorTree *DT) {
826   Value *Result;
827
828   switch (I->getOpcode()) {
829   default:
830     Result = ConstantFoldInstruction(I, TD);
831     break;
832   case Instruction::Add:
833     Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
834                              cast<BinaryOperator>(I)->hasNoSignedWrap(),
835                              cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
836                              TD, DT);
837     break;
838   case Instruction::And:
839     Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
840     break;
841   case Instruction::Or:
842     Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
843     break;
844   case Instruction::Xor:
845     Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
846     break;
847   case Instruction::ICmp:
848     Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
849                               I->getOperand(0), I->getOperand(1), TD, DT);
850     break;
851   case Instruction::FCmp:
852     Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
853                               I->getOperand(0), I->getOperand(1), TD, DT);
854     break;
855   case Instruction::Select:
856     Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
857                                 I->getOperand(2), TD, DT);
858     break;
859   case Instruction::GetElementPtr: {
860     SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
861     Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
862     break;
863   }
864   case Instruction::PHI:
865     Result = SimplifyPHINode(cast<PHINode>(I), DT);
866     break;
867   }
868
869   /// If called on unreachable code, the above logic may report that the
870   /// instruction simplified to itself.  Make life easier for users by
871   /// detecting that case here, returning a safe value instead.
872   return Result == I ? UndefValue::get(I->getType()) : Result;
873 }
874
875 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
876 /// delete the From instruction.  In addition to a basic RAUW, this does a
877 /// recursive simplification of the newly formed instructions.  This catches
878 /// things where one simplification exposes other opportunities.  This only
879 /// simplifies and deletes scalar operations, it does not change the CFG.
880 ///
881 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
882                                      const TargetData *TD,
883                                      const DominatorTree *DT) {
884   assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
885
886   // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
887   // we can know if it gets deleted out from under us or replaced in a
888   // recursive simplification.
889   WeakVH FromHandle(From);
890   WeakVH ToHandle(To);
891
892   while (!From->use_empty()) {
893     // Update the instruction to use the new value.
894     Use &TheUse = From->use_begin().getUse();
895     Instruction *User = cast<Instruction>(TheUse.getUser());
896     TheUse = To;
897
898     // Check to see if the instruction can be folded due to the operand
899     // replacement.  For example changing (or X, Y) into (or X, -1) can replace
900     // the 'or' with -1.
901     Value *SimplifiedVal;
902     {
903       // Sanity check to make sure 'User' doesn't dangle across
904       // SimplifyInstruction.
905       AssertingVH<> UserHandle(User);
906
907       SimplifiedVal = SimplifyInstruction(User, TD, DT);
908       if (SimplifiedVal == 0) continue;
909     }
910
911     // Recursively simplify this user to the new value.
912     ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
913     From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
914     To = ToHandle;
915
916     assert(ToHandle && "To value deleted by recursive simplification?");
917
918     // If the recursive simplification ended up revisiting and deleting
919     // 'From' then we're done.
920     if (From == 0)
921       return;
922   }
923
924   // If 'From' has value handles referring to it, do a real RAUW to update them.
925   From->replaceAllUsesWith(To);
926
927   From->eraseFromParent();
928 }