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