blob: 97612f46d327aac2059067141f1c999af6ce5b57 [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- 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. For example, this does
12// constant folding, and can handle identities like (X&0)->0.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/Analysis/InstructionSimplify.h"
17#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000018#include "llvm/Analysis/Dominators.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000019#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000020#include "llvm/Support/ValueHandle.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000021using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000022using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000023
Duncan Sands18450092010-11-16 12:16:38 +000024#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000025
26static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000027 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000028static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000029 const DominatorTree *, unsigned);
30
31/// ValueDominatesPHI - Does the given value dominate the specified phi node?
32static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
33 Instruction *I = dyn_cast<Instruction>(V);
34 if (!I)
35 // Arguments and constants dominate all instructions.
36 return true;
37
38 // If we have a DominatorTree then do a precise test.
39 if (DT)
40 return DT->dominates(I, P);
41
42 // Otherwise, if the instruction is in the entry block, and is not an invoke,
43 // then it obviously dominates all phi nodes.
44 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
45 !isa<InvokeInst>(I))
46 return true;
47
48 return false;
49}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000050
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000051/// ThreadBinOpOverSelect - In the case of a binary operation with a select
52/// instruction as an operand, try to simplify the binop by seeing whether
53/// evaluating it on both branches of the select results in the same value.
54/// Returns the common value if so, otherwise returns null.
55static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +000056 const TargetData *TD,
57 const DominatorTree *DT,
58 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000059 SelectInst *SI;
60 if (isa<SelectInst>(LHS)) {
61 SI = cast<SelectInst>(LHS);
62 } else {
63 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
64 SI = cast<SelectInst>(RHS);
65 }
66
67 // Evaluate the BinOp on the true and false branches of the select.
68 Value *TV;
69 Value *FV;
70 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +000071 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
72 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000073 } else {
Duncan Sands18450092010-11-16 12:16:38 +000074 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
75 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000076 }
77
78 // If they simplified to the same value, then return the common value.
79 // If they both failed to simplify then return null.
80 if (TV == FV)
81 return TV;
82
83 // If one branch simplified to undef, return the other one.
84 if (TV && isa<UndefValue>(TV))
85 return FV;
86 if (FV && isa<UndefValue>(FV))
87 return TV;
88
89 // If applying the operation did not change the true and false select values,
90 // then the result of the binop is the select itself.
91 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
92 return SI;
93
94 // If one branch simplified and the other did not, and the simplified
95 // value is equal to the unsimplified one, return the simplified value.
96 // For example, select (cond, X, X & Z) & Z -> X & Z.
97 if ((FV && !TV) || (TV && !FV)) {
98 // Check that the simplified value has the form "X op Y" where "op" is the
99 // same as the original operation.
100 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
101 if (Simplified && Simplified->getOpcode() == Opcode) {
102 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
103 // We already know that "op" is the same as for the simplified value. See
104 // if the operands match too. If so, return the simplified value.
105 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
106 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
107 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
108 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
109 Simplified->getOperand(1) == UnsimplifiedRHS)
110 return Simplified;
111 if (Simplified->isCommutative() &&
112 Simplified->getOperand(1) == UnsimplifiedLHS &&
113 Simplified->getOperand(0) == UnsimplifiedRHS)
114 return Simplified;
115 }
116 }
117
118 return 0;
119}
120
121/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
122/// try to simplify the comparison by seeing whether both branches of the select
123/// result in the same value. Returns the common value if so, otherwise returns
124/// null.
125static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000126 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000127 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000128 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000129 // Make sure the select is on the LHS.
130 if (!isa<SelectInst>(LHS)) {
131 std::swap(LHS, RHS);
132 Pred = CmpInst::getSwappedPredicate(Pred);
133 }
134 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
135 SelectInst *SI = cast<SelectInst>(LHS);
136
137 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
138 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000139 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000140 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000141 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000142 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000143 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000144 // It does! If they simplified to the same value, then use it as the
145 // result of the original comparison.
146 if (TCmp == FCmp)
147 return TCmp;
148 return 0;
149}
150
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000151/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
152/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
153/// it on the incoming phi values yields the same result for every value. If so
154/// returns the common value, otherwise returns null.
155static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000156 const TargetData *TD, const DominatorTree *DT,
157 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000158 PHINode *PI;
159 if (isa<PHINode>(LHS)) {
160 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000161 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
162 if (!ValueDominatesPHI(RHS, PI, DT))
163 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000164 } else {
165 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
166 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000167 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
168 if (!ValueDominatesPHI(LHS, PI, DT))
169 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000170 }
171
172 // Evaluate the BinOp on the incoming phi values.
173 Value *CommonValue = 0;
174 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000175 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000176 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000177 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000178 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000179 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
180 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000181 // If the operation failed to simplify, or simplified to a different value
182 // to previously, then give up.
183 if (!V || (CommonValue && V != CommonValue))
184 return 0;
185 CommonValue = V;
186 }
187
188 return CommonValue;
189}
190
191/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
192/// try to simplify the comparison by seeing whether comparing with all of the
193/// incoming phi values yields the same result every time. If so returns the
194/// common result, otherwise returns null.
195static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000196 const TargetData *TD, const DominatorTree *DT,
197 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000198 // Make sure the phi is on the LHS.
199 if (!isa<PHINode>(LHS)) {
200 std::swap(LHS, RHS);
201 Pred = CmpInst::getSwappedPredicate(Pred);
202 }
203 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
204 PHINode *PI = cast<PHINode>(LHS);
205
Duncan Sands18450092010-11-16 12:16:38 +0000206 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
207 if (!ValueDominatesPHI(RHS, PI, DT))
208 return 0;
209
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000210 // Evaluate the BinOp on the incoming phi values.
211 Value *CommonValue = 0;
212 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000213 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000214 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000215 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000216 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000217 // If the operation failed to simplify, or simplified to a different value
218 // to previously, then give up.
219 if (!V || (CommonValue && V != CommonValue))
220 return 0;
221 CommonValue = V;
222 }
223
224 return CommonValue;
225}
226
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000227/// SimplifyAddInst - Given operands for an Add, see if we can
228/// fold the result. If not, this returns null.
229Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands18450092010-11-16 12:16:38 +0000230 const TargetData *TD, const DominatorTree *) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000231 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
232 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
233 Constant *Ops[] = { CLHS, CRHS };
234 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
235 Ops, 2, TD);
236 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000237
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000238 // Canonicalize the constant to the RHS.
239 std::swap(Op0, Op1);
240 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000241
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000242 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
243 // X + undef -> undef
244 if (isa<UndefValue>(Op1C))
245 return Op1C;
Duncan Sands12a86f52010-11-14 11:23:23 +0000246
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000247 // X + 0 --> X
248 if (Op1C->isNullValue())
249 return Op0;
250 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000251
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000252 // FIXME: Could pull several more out of instcombine.
Duncan Sands87689cf2010-11-19 09:20:39 +0000253
254 // Threading Add over selects and phi nodes is pointless, so don't bother.
255 // Threading over the select in "A + select(cond, B, C)" means evaluating
256 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
257 // only if B and C are equal. If B and C are equal then (since we assume
258 // that operands have already been simplified) "select(cond, B, C)" should
259 // have been simplified to the common value of B and C already. Analysing
260 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
261 // for threading over phi nodes.
262
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000263 return 0;
264}
265
Chris Lattnerd06094f2009-11-10 00:55:12 +0000266/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000267/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000268static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000269 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000270 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
271 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
272 Constant *Ops[] = { CLHS, CRHS };
273 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
274 Ops, 2, TD);
275 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000276
Chris Lattnerd06094f2009-11-10 00:55:12 +0000277 // Canonicalize the constant to the RHS.
278 std::swap(Op0, Op1);
279 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000280
Chris Lattnerd06094f2009-11-10 00:55:12 +0000281 // X & undef -> 0
282 if (isa<UndefValue>(Op1))
283 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000284
Chris Lattnerd06094f2009-11-10 00:55:12 +0000285 // X & X = X
286 if (Op0 == Op1)
287 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000288
Duncan Sands2b749872010-11-17 18:52:15 +0000289 // X & 0 = 0
290 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000291 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000292
Duncan Sands2b749872010-11-17 18:52:15 +0000293 // X & -1 = X
294 if (match(Op1, m_AllOnes()))
295 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000296
Chris Lattnerd06094f2009-11-10 00:55:12 +0000297 // A & ~A = ~A & A = 0
298 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000299 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
300 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000301 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000302
Chris Lattnerd06094f2009-11-10 00:55:12 +0000303 // (A | ?) & A = A
304 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
305 (A == Op1 || B == Op1))
306 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000307
Chris Lattnerd06094f2009-11-10 00:55:12 +0000308 // A & (A | ?) = A
309 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
310 (A == Op0 || B == Op0))
311 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000312
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000313 // (A & B) & A -> A & B
314 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
315 (A == Op1 || B == Op1))
316 return Op0;
317
318 // A & (A & B) -> A & B
319 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
320 (A == Op0 || B == Op0))
321 return Op1;
322
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000323 // If the operation is with the result of a select instruction, check whether
324 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000325 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000326 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000327 MaxRecurse-1))
328 return V;
329
330 // If the operation is with the result of a phi instruction, check whether
331 // operating on all incoming values of the phi always yields the same value.
332 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000333 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000334 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000335 return V;
336
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000337 return 0;
338}
339
Duncan Sands18450092010-11-16 12:16:38 +0000340Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
341 const DominatorTree *DT) {
342 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000343}
344
Chris Lattnerd06094f2009-11-10 00:55:12 +0000345/// SimplifyOrInst - Given operands for an Or, see if we can
346/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000347static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000348 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000349 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
350 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
351 Constant *Ops[] = { CLHS, CRHS };
352 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
353 Ops, 2, TD);
354 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000355
Chris Lattnerd06094f2009-11-10 00:55:12 +0000356 // Canonicalize the constant to the RHS.
357 std::swap(Op0, Op1);
358 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000359
Chris Lattnerd06094f2009-11-10 00:55:12 +0000360 // X | undef -> -1
361 if (isa<UndefValue>(Op1))
362 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000363
Chris Lattnerd06094f2009-11-10 00:55:12 +0000364 // X | X = X
365 if (Op0 == Op1)
366 return Op0;
367
Duncan Sands2b749872010-11-17 18:52:15 +0000368 // X | 0 = X
369 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000370 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000371
Duncan Sands2b749872010-11-17 18:52:15 +0000372 // X | -1 = -1
373 if (match(Op1, m_AllOnes()))
374 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000375
Chris Lattnerd06094f2009-11-10 00:55:12 +0000376 // A | ~A = ~A | A = -1
377 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000378 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
379 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000380 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000381
Chris Lattnerd06094f2009-11-10 00:55:12 +0000382 // (A & ?) | A = A
383 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
384 (A == Op1 || B == Op1))
385 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000386
Chris Lattnerd06094f2009-11-10 00:55:12 +0000387 // A | (A & ?) = A
388 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
389 (A == Op0 || B == Op0))
390 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000391
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000392 // (A | B) | A -> A | B
393 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
394 (A == Op1 || B == Op1))
395 return Op0;
396
397 // A | (A | B) -> A | B
398 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
399 (A == Op0 || B == Op0))
400 return Op1;
401
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000402 // If the operation is with the result of a select instruction, check whether
403 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000404 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000405 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000406 MaxRecurse-1))
407 return V;
408
409 // If the operation is with the result of a phi instruction, check whether
410 // operating on all incoming values of the phi always yields the same value.
411 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000412 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000413 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000414 return V;
415
Chris Lattnerd06094f2009-11-10 00:55:12 +0000416 return 0;
417}
418
Duncan Sands18450092010-11-16 12:16:38 +0000419Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
420 const DominatorTree *DT) {
421 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000422}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000423
Duncan Sands2b749872010-11-17 18:52:15 +0000424/// SimplifyXorInst - Given operands for a Xor, see if we can
425/// fold the result. If not, this returns null.
426static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
427 const DominatorTree *DT, unsigned MaxRecurse) {
428 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
429 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
430 Constant *Ops[] = { CLHS, CRHS };
431 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
432 Ops, 2, TD);
433 }
434
435 // Canonicalize the constant to the RHS.
436 std::swap(Op0, Op1);
437 }
438
439 // A ^ undef -> undef
440 if (isa<UndefValue>(Op1))
441 return UndefValue::get(Op0->getType());
442
443 // A ^ 0 = A
444 if (match(Op1, m_Zero()))
445 return Op0;
446
447 // A ^ A = 0
448 if (Op0 == Op1)
449 return Constant::getNullValue(Op0->getType());
450
451 // A ^ ~A = ~A ^ A = -1
452 Value *A, *B;
453 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
454 (match(Op1, m_Not(m_Value(A))) && A == Op0))
455 return Constant::getAllOnesValue(Op0->getType());
456
457 // (A ^ B) ^ A = B
458 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
459 (A == Op1 || B == Op1))
460 return A == Op1 ? B : A;
461
462 // A ^ (A ^ B) = B
463 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
464 (A == Op0 || B == Op0))
465 return A == Op0 ? B : A;
466
Duncan Sands87689cf2010-11-19 09:20:39 +0000467 // Threading Xor over selects and phi nodes is pointless, so don't bother.
468 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
469 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
470 // only if B and C are equal. If B and C are equal then (since we assume
471 // that operands have already been simplified) "select(cond, B, C)" should
472 // have been simplified to the common value of B and C already. Analysing
473 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
474 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000475
476 return 0;
477}
478
479Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
480 const DominatorTree *DT) {
481 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
482}
483
Chris Lattner210c5d42009-11-09 23:55:12 +0000484static const Type *GetCompareTy(Value *Op) {
485 return CmpInst::makeCmpResultType(Op->getType());
486}
487
Chris Lattner9dbb4292009-11-09 23:28:39 +0000488/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
489/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000490static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000491 const TargetData *TD, const DominatorTree *DT,
492 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000493 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000494 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000495
Chris Lattnerd06094f2009-11-10 00:55:12 +0000496 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000497 if (Constant *CRHS = dyn_cast<Constant>(RHS))
498 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000499
500 // If we have a constant, make sure it is on the RHS.
501 std::swap(LHS, RHS);
502 Pred = CmpInst::getSwappedPredicate(Pred);
503 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000504
Chris Lattner210c5d42009-11-09 23:55:12 +0000505 // ITy - This is the return type of the compare we're considering.
506 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000507
Chris Lattner210c5d42009-11-09 23:55:12 +0000508 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000509 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
510 // because X could be 0.
511 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000512 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000513
Chris Lattner210c5d42009-11-09 23:55:12 +0000514 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
515 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000516 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000517 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000518 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000519 isa<ConstantPointerNull>(RHS)))
520 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000521
Chris Lattner210c5d42009-11-09 23:55:12 +0000522 // See if we are doing a comparison with a constant.
523 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
524 // If we have an icmp le or icmp ge instruction, turn it into the
525 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
526 // them being folded in the code below.
527 switch (Pred) {
528 default: break;
529 case ICmpInst::ICMP_ULE:
530 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
531 return ConstantInt::getTrue(CI->getContext());
532 break;
533 case ICmpInst::ICMP_SLE:
534 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
535 return ConstantInt::getTrue(CI->getContext());
536 break;
537 case ICmpInst::ICMP_UGE:
538 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
539 return ConstantInt::getTrue(CI->getContext());
540 break;
541 case ICmpInst::ICMP_SGE:
542 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
543 return ConstantInt::getTrue(CI->getContext());
544 break;
545 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000546 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000547
548 // If the comparison is with the result of a select instruction, check whether
549 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000550 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000551 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000552 return V;
553
554 // If the comparison is with the result of a phi instruction, check whether
555 // doing the compare with each incoming phi value yields a common result.
556 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000557 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000558 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000559
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000560 return 0;
561}
562
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000563Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000564 const TargetData *TD, const DominatorTree *DT) {
565 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000566}
567
Chris Lattner9dbb4292009-11-09 23:28:39 +0000568/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
569/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000570static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000571 const TargetData *TD, const DominatorTree *DT,
572 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000573 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
574 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
575
Chris Lattnerd06094f2009-11-10 00:55:12 +0000576 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000577 if (Constant *CRHS = dyn_cast<Constant>(RHS))
578 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000579
Chris Lattnerd06094f2009-11-10 00:55:12 +0000580 // If we have a constant, make sure it is on the RHS.
581 std::swap(LHS, RHS);
582 Pred = CmpInst::getSwappedPredicate(Pred);
583 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000584
Chris Lattner210c5d42009-11-09 23:55:12 +0000585 // Fold trivial predicates.
586 if (Pred == FCmpInst::FCMP_FALSE)
587 return ConstantInt::get(GetCompareTy(LHS), 0);
588 if (Pred == FCmpInst::FCMP_TRUE)
589 return ConstantInt::get(GetCompareTy(LHS), 1);
590
Chris Lattner210c5d42009-11-09 23:55:12 +0000591 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
592 return UndefValue::get(GetCompareTy(LHS));
593
594 // fcmp x,x -> true/false. Not all compares are foldable.
595 if (LHS == RHS) {
596 if (CmpInst::isTrueWhenEqual(Pred))
597 return ConstantInt::get(GetCompareTy(LHS), 1);
598 if (CmpInst::isFalseWhenEqual(Pred))
599 return ConstantInt::get(GetCompareTy(LHS), 0);
600 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000601
Chris Lattner210c5d42009-11-09 23:55:12 +0000602 // Handle fcmp with constant RHS
603 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
604 // If the constant is a nan, see if we can fold the comparison based on it.
605 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
606 if (CFP->getValueAPF().isNaN()) {
607 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
608 return ConstantInt::getFalse(CFP->getContext());
609 assert(FCmpInst::isUnordered(Pred) &&
610 "Comparison must be either ordered or unordered!");
611 // True if unordered.
612 return ConstantInt::getTrue(CFP->getContext());
613 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000614 // Check whether the constant is an infinity.
615 if (CFP->getValueAPF().isInfinity()) {
616 if (CFP->getValueAPF().isNegative()) {
617 switch (Pred) {
618 case FCmpInst::FCMP_OLT:
619 // No value is ordered and less than negative infinity.
620 return ConstantInt::getFalse(CFP->getContext());
621 case FCmpInst::FCMP_UGE:
622 // All values are unordered with or at least negative infinity.
623 return ConstantInt::getTrue(CFP->getContext());
624 default:
625 break;
626 }
627 } else {
628 switch (Pred) {
629 case FCmpInst::FCMP_OGT:
630 // No value is ordered and greater than infinity.
631 return ConstantInt::getFalse(CFP->getContext());
632 case FCmpInst::FCMP_ULE:
633 // All values are unordered with and at most infinity.
634 return ConstantInt::getTrue(CFP->getContext());
635 default:
636 break;
637 }
638 }
639 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000640 }
641 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000642
Duncan Sands92826de2010-11-07 16:46:25 +0000643 // If the comparison is with the result of a select instruction, check whether
644 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000645 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000646 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000647 return V;
648
649 // If the comparison is with the result of a phi instruction, check whether
650 // doing the compare with each incoming phi value yields a common result.
651 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000652 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000653 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000654
Chris Lattner9dbb4292009-11-09 23:28:39 +0000655 return 0;
656}
657
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000658Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000659 const TargetData *TD, const DominatorTree *DT) {
660 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000661}
662
Chris Lattner04754262010-04-20 05:32:14 +0000663/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
664/// the result. If not, this returns null.
665Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000666 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000667 // select true, X, Y -> X
668 // select false, X, Y -> Y
669 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
670 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000671
Chris Lattner04754262010-04-20 05:32:14 +0000672 // select C, X, X -> X
673 if (TrueVal == FalseVal)
674 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000675
Chris Lattner04754262010-04-20 05:32:14 +0000676 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
677 return FalseVal;
678 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
679 return TrueVal;
680 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
681 if (isa<Constant>(TrueVal))
682 return TrueVal;
683 return FalseVal;
684 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000685
Chris Lattner04754262010-04-20 05:32:14 +0000686 return 0;
687}
688
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000689/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
690/// fold the result. If not, this returns null.
691Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +0000692 const TargetData *TD, const DominatorTree *) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000693 // getelementptr P -> P.
694 if (NumOps == 1)
695 return Ops[0];
696
697 // TODO.
698 //if (isa<UndefValue>(Ops[0]))
699 // return UndefValue::get(GEP.getType());
700
701 // getelementptr P, 0 -> P.
702 if (NumOps == 2)
703 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
704 if (C->isZero())
705 return Ops[0];
Duncan Sands12a86f52010-11-14 11:23:23 +0000706
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000707 // Check to see if this is constant foldable.
708 for (unsigned i = 0; i != NumOps; ++i)
709 if (!isa<Constant>(Ops[i]))
710 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000711
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000712 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
713 (Constant *const*)Ops+1, NumOps-1);
714}
715
Duncan Sandsff103412010-11-17 04:30:22 +0000716/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
717static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
718 // If all of the PHI's incoming values are the same then replace the PHI node
719 // with the common value.
720 Value *CommonValue = 0;
721 bool HasUndefInput = false;
722 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
723 Value *Incoming = PN->getIncomingValue(i);
724 // If the incoming value is the phi node itself, it can safely be skipped.
725 if (Incoming == PN) continue;
726 if (isa<UndefValue>(Incoming)) {
727 // Remember that we saw an undef value, but otherwise ignore them.
728 HasUndefInput = true;
729 continue;
730 }
731 if (CommonValue && Incoming != CommonValue)
732 return 0; // Not the same, bail out.
733 CommonValue = Incoming;
734 }
735
736 // If CommonValue is null then all of the incoming values were either undef or
737 // equal to the phi node itself.
738 if (!CommonValue)
739 return UndefValue::get(PN->getType());
740
741 // If we have a PHI node like phi(X, undef, X), where X is defined by some
742 // instruction, we cannot return X as the result of the PHI node unless it
743 // dominates the PHI block.
744 if (HasUndefInput)
745 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
746
747 return CommonValue;
748}
749
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000750
Chris Lattnerd06094f2009-11-10 00:55:12 +0000751//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000752
Chris Lattnerd06094f2009-11-10 00:55:12 +0000753/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
754/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000755static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000756 const TargetData *TD, const DominatorTree *DT,
757 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000758 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +0000759 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
760 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000761 default:
762 if (Constant *CLHS = dyn_cast<Constant>(LHS))
763 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
764 Constant *COps[] = {CLHS, CRHS};
765 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
766 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000767
768 // If the operation is with the result of a select instruction, check whether
769 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000770 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000771 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
772 MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000773 return V;
774
775 // If the operation is with the result of a phi instruction, check whether
776 // operating on all incoming values of the phi always yields the same value.
777 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000778 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000779 return V;
780
Chris Lattnerd06094f2009-11-10 00:55:12 +0000781 return 0;
782 }
783}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000784
Duncan Sands12a86f52010-11-14 11:23:23 +0000785Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000786 const TargetData *TD, const DominatorTree *DT) {
787 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +0000788}
789
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000790/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
791/// fold the result.
792static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000793 const TargetData *TD, const DominatorTree *DT,
794 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000795 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +0000796 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
797 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000798}
799
800Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000801 const TargetData *TD, const DominatorTree *DT) {
802 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000803}
Chris Lattnere3453782009-11-10 01:08:51 +0000804
805/// SimplifyInstruction - See if we can compute a simplified version of this
806/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +0000807Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
808 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +0000809 Value *Result;
810
Chris Lattnere3453782009-11-10 01:08:51 +0000811 switch (I->getOpcode()) {
812 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000813 Result = ConstantFoldInstruction(I, TD);
814 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000815 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000816 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
817 cast<BinaryOperator>(I)->hasNoSignedWrap(),
818 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
819 TD, DT);
820 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000821 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000822 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
823 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000824 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000825 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
826 break;
Duncan Sands2b749872010-11-17 18:52:15 +0000827 case Instruction::Xor:
828 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
829 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000830 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000831 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
832 I->getOperand(0), I->getOperand(1), TD, DT);
833 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000834 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000835 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
836 I->getOperand(0), I->getOperand(1), TD, DT);
837 break;
Chris Lattner04754262010-04-20 05:32:14 +0000838 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000839 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
840 I->getOperand(2), TD, DT);
841 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000842 case Instruction::GetElementPtr: {
843 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +0000844 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
845 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000846 }
Duncan Sandscd6636c2010-11-14 13:30:18 +0000847 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000848 Result = SimplifyPHINode(cast<PHINode>(I), DT);
849 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000850 }
Duncan Sandsd261dc62010-11-17 08:35:29 +0000851
852 /// If called on unreachable code, the above logic may report that the
853 /// instruction simplified to itself. Make life easier for users by
854 /// detecting that case here, returning null if it occurs.
855 return Result == I ? 0 : Result;
Chris Lattnere3453782009-11-10 01:08:51 +0000856}
857
Chris Lattner40d8c282009-11-10 22:26:15 +0000858/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
859/// delete the From instruction. In addition to a basic RAUW, this does a
860/// recursive simplification of the newly formed instructions. This catches
861/// things where one simplification exposes other opportunities. This only
862/// simplifies and deletes scalar operations, it does not change the CFG.
863///
864void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +0000865 const TargetData *TD,
866 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +0000867 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000868
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000869 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
870 // we can know if it gets deleted out from under us or replaced in a
871 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +0000872 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000873 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000874
Chris Lattner40d8c282009-11-10 22:26:15 +0000875 while (!From->use_empty()) {
876 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000877 Use &TheUse = From->use_begin().getUse();
878 Instruction *User = cast<Instruction>(TheUse.getUser());
879 TheUse = To;
880
881 // Check to see if the instruction can be folded due to the operand
882 // replacement. For example changing (or X, Y) into (or X, -1) can replace
883 // the 'or' with -1.
884 Value *SimplifiedVal;
885 {
886 // Sanity check to make sure 'User' doesn't dangle across
887 // SimplifyInstruction.
888 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +0000889
Duncan Sandseff05812010-11-14 18:36:10 +0000890 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000891 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +0000892 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000893
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000894 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +0000895 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000896 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
897 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +0000898
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000899 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +0000900
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000901 // If the recursive simplification ended up revisiting and deleting
902 // 'From' then we're done.
903 if (From == 0)
904 return;
Chris Lattner40d8c282009-11-10 22:26:15 +0000905 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000906
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000907 // If 'From' has value handles referring to it, do a real RAUW to update them.
908 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000909
Chris Lattner40d8c282009-11-10 22:26:15 +0000910 From->eraseFromParent();
911}