blob: 2458d204bcad3c53c7e54deecb776f24c3bbd332 [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
Duncan Sands4cd2ad12010-11-23 10:50:08 +000011// 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").
Chris Lattner9f3c25a2009-11-09 22:57:59 +000015//
16//===----------------------------------------------------------------------===//
17
18#include "llvm/Analysis/InstructionSimplify.h"
19#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000020#include "llvm/Analysis/Dominators.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000021#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000022#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000023#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000024using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000025using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000026
Duncan Sands18450092010-11-16 12:16:38 +000027#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000028
29static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000030 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000031static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000032 const DominatorTree *, unsigned);
33
34/// ValueDominatesPHI - Does the given value dominate the specified phi node?
35static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
36 Instruction *I = dyn_cast<Instruction>(V);
37 if (!I)
38 // Arguments and constants dominate all instructions.
39 return true;
40
41 // If we have a DominatorTree then do a precise test.
42 if (DT)
43 return DT->dominates(I, P);
44
45 // Otherwise, if the instruction is in the entry block, and is not an invoke,
46 // then it obviously dominates all phi nodes.
47 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
48 !isa<InvokeInst>(I))
49 return true;
50
51 return false;
52}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000053
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000054/// ThreadBinOpOverSelect - In the case of a binary operation with a select
55/// instruction as an operand, try to simplify the binop by seeing whether
56/// evaluating it on both branches of the select results in the same value.
57/// Returns the common value if so, otherwise returns null.
58static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +000059 const TargetData *TD,
60 const DominatorTree *DT,
61 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000062 SelectInst *SI;
63 if (isa<SelectInst>(LHS)) {
64 SI = cast<SelectInst>(LHS);
65 } else {
66 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
67 SI = cast<SelectInst>(RHS);
68 }
69
70 // Evaluate the BinOp on the true and false branches of the select.
71 Value *TV;
72 Value *FV;
73 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +000074 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
75 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000076 } else {
Duncan Sands18450092010-11-16 12:16:38 +000077 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
78 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000079 }
80
81 // If they simplified to the same value, then return the common value.
82 // If they both failed to simplify then return null.
83 if (TV == FV)
84 return TV;
85
86 // If one branch simplified to undef, return the other one.
87 if (TV && isa<UndefValue>(TV))
88 return FV;
89 if (FV && isa<UndefValue>(FV))
90 return TV;
91
92 // If applying the operation did not change the true and false select values,
93 // then the result of the binop is the select itself.
94 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
95 return SI;
96
97 // If one branch simplified and the other did not, and the simplified
98 // value is equal to the unsimplified one, return the simplified value.
99 // For example, select (cond, X, X & Z) & Z -> X & Z.
100 if ((FV && !TV) || (TV && !FV)) {
101 // Check that the simplified value has the form "X op Y" where "op" is the
102 // same as the original operation.
103 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
104 if (Simplified && Simplified->getOpcode() == Opcode) {
105 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
106 // We already know that "op" is the same as for the simplified value. See
107 // if the operands match too. If so, return the simplified value.
108 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
109 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
110 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
111 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
112 Simplified->getOperand(1) == UnsimplifiedRHS)
113 return Simplified;
114 if (Simplified->isCommutative() &&
115 Simplified->getOperand(1) == UnsimplifiedLHS &&
116 Simplified->getOperand(0) == UnsimplifiedRHS)
117 return Simplified;
118 }
119 }
120
121 return 0;
122}
123
124/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
125/// try to simplify the comparison by seeing whether both branches of the select
126/// result in the same value. Returns the common value if so, otherwise returns
127/// null.
128static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000129 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000130 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000131 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000132 // Make sure the select is on the LHS.
133 if (!isa<SelectInst>(LHS)) {
134 std::swap(LHS, RHS);
135 Pred = CmpInst::getSwappedPredicate(Pred);
136 }
137 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
138 SelectInst *SI = cast<SelectInst>(LHS);
139
140 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
141 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000142 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000143 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000144 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000145 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000146 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000147 // It does! If they simplified to the same value, then use it as the
148 // result of the original comparison.
149 if (TCmp == FCmp)
150 return TCmp;
151 return 0;
152}
153
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000154/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
155/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
156/// it on the incoming phi values yields the same result for every value. If so
157/// returns the common value, otherwise returns null.
158static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000159 const TargetData *TD, const DominatorTree *DT,
160 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000161 PHINode *PI;
162 if (isa<PHINode>(LHS)) {
163 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000164 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
165 if (!ValueDominatesPHI(RHS, PI, DT))
166 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000167 } else {
168 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
169 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000170 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
171 if (!ValueDominatesPHI(LHS, PI, DT))
172 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000173 }
174
175 // Evaluate the BinOp on the incoming phi values.
176 Value *CommonValue = 0;
177 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000178 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000179 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000180 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000181 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000182 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
183 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000184 // If the operation failed to simplify, or simplified to a different value
185 // to previously, then give up.
186 if (!V || (CommonValue && V != CommonValue))
187 return 0;
188 CommonValue = V;
189 }
190
191 return CommonValue;
192}
193
194/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
195/// try to simplify the comparison by seeing whether comparing with all of the
196/// incoming phi values yields the same result every time. If so returns the
197/// common result, otherwise returns null.
198static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000199 const TargetData *TD, const DominatorTree *DT,
200 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000201 // Make sure the phi is on the LHS.
202 if (!isa<PHINode>(LHS)) {
203 std::swap(LHS, RHS);
204 Pred = CmpInst::getSwappedPredicate(Pred);
205 }
206 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
207 PHINode *PI = cast<PHINode>(LHS);
208
Duncan Sands18450092010-11-16 12:16:38 +0000209 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
210 if (!ValueDominatesPHI(RHS, PI, DT))
211 return 0;
212
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000213 // Evaluate the BinOp on the incoming phi values.
214 Value *CommonValue = 0;
215 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000216 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000217 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000218 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000219 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000220 // If the operation failed to simplify, or simplified to a different value
221 // to previously, then give up.
222 if (!V || (CommonValue && V != CommonValue))
223 return 0;
224 CommonValue = V;
225 }
226
227 return CommonValue;
228}
229
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000230/// SimplifyAddInst - Given operands for an Add, see if we can
231/// fold the result. If not, this returns null.
232Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands18450092010-11-16 12:16:38 +0000233 const TargetData *TD, const DominatorTree *) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000234 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
235 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
236 Constant *Ops[] = { CLHS, CRHS };
237 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
238 Ops, 2, TD);
239 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000240
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000241 // Canonicalize the constant to the RHS.
242 std::swap(Op0, Op1);
243 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000244
Duncan Sandsfea3b212010-12-15 14:07:39 +0000245 // X + undef -> undef
246 if (isa<UndefValue>(Op1))
247 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000248
Duncan Sandsfea3b212010-12-15 14:07:39 +0000249 // X + 0 -> X
250 if (match(Op1, m_Zero()))
251 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000252
Duncan Sandsfea3b212010-12-15 14:07:39 +0000253 // X + (Y - X) -> Y
254 // (Y - X) + X -> Y
255 Value *Y = 0;
256 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
257 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
258 return Y;
259
260 // X + ~X -> -1 since ~X = -X-1
261 if (match(Op0, m_Not(m_Specific(Op1))) ||
262 match(Op1, m_Not(m_Specific(Op0))))
263 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000264
265 // Threading Add over selects and phi nodes is pointless, so don't bother.
266 // Threading over the select in "A + select(cond, B, C)" means evaluating
267 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
268 // only if B and C are equal. If B and C are equal then (since we assume
269 // that operands have already been simplified) "select(cond, B, C)" should
270 // have been simplified to the common value of B and C already. Analysing
271 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
272 // for threading over phi nodes.
273
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000274 return 0;
275}
276
Duncan Sandsfea3b212010-12-15 14:07:39 +0000277/// SimplifySubInst - Given operands for a Sub, see if we can
278/// fold the result. If not, this returns null.
279Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
280 const TargetData *TD, const DominatorTree *) {
281 if (Constant *CLHS = dyn_cast<Constant>(Op0))
282 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
283 Constant *Ops[] = { CLHS, CRHS };
284 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
285 Ops, 2, TD);
286 }
287
288 // X - undef -> undef
289 // undef - X -> undef
290 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
291 return UndefValue::get(Op0->getType());
292
293 // X - 0 -> X
294 if (match(Op1, m_Zero()))
295 return Op0;
296
297 // X - X -> 0
298 if (Op0 == Op1)
299 return Constant::getNullValue(Op0->getType());
300
301 // (X + Y) - Y -> X
302 // (Y + X) - Y -> X
303 Value *X = 0;
304 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
305 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
306 return X;
307
308 // Threading Sub over selects and phi nodes is pointless, so don't bother.
309 // Threading over the select in "A - select(cond, B, C)" means evaluating
310 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
311 // only if B and C are equal. If B and C are equal then (since we assume
312 // that operands have already been simplified) "select(cond, B, C)" should
313 // have been simplified to the common value of B and C already. Analysing
314 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
315 // for threading over phi nodes.
316
317 return 0;
318}
319
Chris Lattnerd06094f2009-11-10 00:55:12 +0000320/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000321/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000322static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000323 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000324 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
325 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
326 Constant *Ops[] = { CLHS, CRHS };
327 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
328 Ops, 2, TD);
329 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000330
Chris Lattnerd06094f2009-11-10 00:55:12 +0000331 // Canonicalize the constant to the RHS.
332 std::swap(Op0, Op1);
333 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000334
Chris Lattnerd06094f2009-11-10 00:55:12 +0000335 // X & undef -> 0
336 if (isa<UndefValue>(Op1))
337 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000338
Chris Lattnerd06094f2009-11-10 00:55:12 +0000339 // X & X = X
340 if (Op0 == Op1)
341 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000342
Duncan Sands2b749872010-11-17 18:52:15 +0000343 // X & 0 = 0
344 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000345 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000346
Duncan Sands2b749872010-11-17 18:52:15 +0000347 // X & -1 = X
348 if (match(Op1, m_AllOnes()))
349 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000350
Chris Lattnerd06094f2009-11-10 00:55:12 +0000351 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000352 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000353 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
354 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000355 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000356
Chris Lattnerd06094f2009-11-10 00:55:12 +0000357 // (A | ?) & A = A
358 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
359 (A == Op1 || B == Op1))
360 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000361
Chris Lattnerd06094f2009-11-10 00:55:12 +0000362 // A & (A | ?) = A
363 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
364 (A == Op0 || B == Op0))
365 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000366
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000367 // (A & B) & A -> A & B
368 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
369 (A == Op1 || B == Op1))
370 return Op0;
371
372 // A & (A & B) -> A & B
373 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
374 (A == Op0 || B == Op0))
375 return Op1;
376
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000377 // If the operation is with the result of a select instruction, check whether
378 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000379 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000380 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000381 MaxRecurse-1))
382 return V;
383
384 // If the operation is with the result of a phi instruction, check whether
385 // operating on all incoming values of the phi always yields the same value.
386 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000387 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000388 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000389 return V;
390
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000391 return 0;
392}
393
Duncan Sands18450092010-11-16 12:16:38 +0000394Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
395 const DominatorTree *DT) {
396 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000397}
398
Chris Lattnerd06094f2009-11-10 00:55:12 +0000399/// SimplifyOrInst - Given operands for an Or, see if we can
400/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000401static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000402 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000403 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
404 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
405 Constant *Ops[] = { CLHS, CRHS };
406 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
407 Ops, 2, TD);
408 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000409
Chris Lattnerd06094f2009-11-10 00:55:12 +0000410 // Canonicalize the constant to the RHS.
411 std::swap(Op0, Op1);
412 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000413
Chris Lattnerd06094f2009-11-10 00:55:12 +0000414 // X | undef -> -1
415 if (isa<UndefValue>(Op1))
416 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000417
Chris Lattnerd06094f2009-11-10 00:55:12 +0000418 // X | X = X
419 if (Op0 == Op1)
420 return Op0;
421
Duncan Sands2b749872010-11-17 18:52:15 +0000422 // X | 0 = X
423 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000424 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000425
Duncan Sands2b749872010-11-17 18:52:15 +0000426 // X | -1 = -1
427 if (match(Op1, m_AllOnes()))
428 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000429
Chris Lattnerd06094f2009-11-10 00:55:12 +0000430 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000431 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000432 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
433 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000434 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000435
Chris Lattnerd06094f2009-11-10 00:55:12 +0000436 // (A & ?) | A = A
437 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
438 (A == Op1 || B == Op1))
439 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000440
Chris Lattnerd06094f2009-11-10 00:55:12 +0000441 // A | (A & ?) = A
442 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
443 (A == Op0 || B == Op0))
444 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000445
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000446 // (A | B) | A -> A | B
447 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
448 (A == Op1 || B == Op1))
449 return Op0;
450
451 // A | (A | B) -> A | B
452 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
453 (A == Op0 || B == Op0))
454 return Op1;
455
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000456 // If the operation is with the result of a select instruction, check whether
457 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000458 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000459 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000460 MaxRecurse-1))
461 return V;
462
463 // If the operation is with the result of a phi instruction, check whether
464 // operating on all incoming values of the phi always yields the same value.
465 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000466 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000467 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000468 return V;
469
Chris Lattnerd06094f2009-11-10 00:55:12 +0000470 return 0;
471}
472
Duncan Sands18450092010-11-16 12:16:38 +0000473Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
474 const DominatorTree *DT) {
475 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000476}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000477
Duncan Sands2b749872010-11-17 18:52:15 +0000478/// SimplifyXorInst - Given operands for a Xor, see if we can
479/// fold the result. If not, this returns null.
480static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
481 const DominatorTree *DT, unsigned MaxRecurse) {
482 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
483 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
484 Constant *Ops[] = { CLHS, CRHS };
485 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
486 Ops, 2, TD);
487 }
488
489 // Canonicalize the constant to the RHS.
490 std::swap(Op0, Op1);
491 }
492
493 // A ^ undef -> undef
494 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000495 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000496
497 // A ^ 0 = A
498 if (match(Op1, m_Zero()))
499 return Op0;
500
501 // A ^ A = 0
502 if (Op0 == Op1)
503 return Constant::getNullValue(Op0->getType());
504
505 // A ^ ~A = ~A ^ A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000506 Value *A = 0, *B = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000507 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
508 (match(Op1, m_Not(m_Value(A))) && A == Op0))
509 return Constant::getAllOnesValue(Op0->getType());
510
511 // (A ^ B) ^ A = B
512 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
513 (A == Op1 || B == Op1))
514 return A == Op1 ? B : A;
515
516 // A ^ (A ^ B) = B
517 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
518 (A == Op0 || B == Op0))
519 return A == Op0 ? B : A;
520
Duncan Sands87689cf2010-11-19 09:20:39 +0000521 // Threading Xor over selects and phi nodes is pointless, so don't bother.
522 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
523 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
524 // only if B and C are equal. If B and C are equal then (since we assume
525 // that operands have already been simplified) "select(cond, B, C)" should
526 // have been simplified to the common value of B and C already. Analysing
527 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
528 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000529
530 return 0;
531}
532
533Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
534 const DominatorTree *DT) {
535 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
536}
537
Chris Lattner210c5d42009-11-09 23:55:12 +0000538static const Type *GetCompareTy(Value *Op) {
539 return CmpInst::makeCmpResultType(Op->getType());
540}
541
Chris Lattner9dbb4292009-11-09 23:28:39 +0000542/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
543/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000544static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000545 const TargetData *TD, const DominatorTree *DT,
546 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000547 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000548 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000549
Chris Lattnerd06094f2009-11-10 00:55:12 +0000550 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000551 if (Constant *CRHS = dyn_cast<Constant>(RHS))
552 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000553
554 // If we have a constant, make sure it is on the RHS.
555 std::swap(LHS, RHS);
556 Pred = CmpInst::getSwappedPredicate(Pred);
557 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000558
Chris Lattner210c5d42009-11-09 23:55:12 +0000559 // ITy - This is the return type of the compare we're considering.
560 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000561
Chris Lattner210c5d42009-11-09 23:55:12 +0000562 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000563 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
564 // because X could be 0.
565 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000566 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000567
Chris Lattner210c5d42009-11-09 23:55:12 +0000568 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
569 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000570 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000571 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000572 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000573 isa<ConstantPointerNull>(RHS)))
574 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000575
Chris Lattner210c5d42009-11-09 23:55:12 +0000576 // See if we are doing a comparison with a constant.
577 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
578 // If we have an icmp le or icmp ge instruction, turn it into the
579 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
580 // them being folded in the code below.
581 switch (Pred) {
582 default: break;
583 case ICmpInst::ICMP_ULE:
584 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
585 return ConstantInt::getTrue(CI->getContext());
586 break;
587 case ICmpInst::ICMP_SLE:
588 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
589 return ConstantInt::getTrue(CI->getContext());
590 break;
591 case ICmpInst::ICMP_UGE:
592 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
593 return ConstantInt::getTrue(CI->getContext());
594 break;
595 case ICmpInst::ICMP_SGE:
596 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
597 return ConstantInt::getTrue(CI->getContext());
598 break;
599 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000600 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000601
602 // If the comparison is with the result of a select instruction, check whether
603 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000604 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000605 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000606 return V;
607
608 // If the comparison is with the result of a phi instruction, check whether
609 // doing the compare with each incoming phi value yields a common result.
610 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000611 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000612 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000613
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000614 return 0;
615}
616
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000617Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000618 const TargetData *TD, const DominatorTree *DT) {
619 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000620}
621
Chris Lattner9dbb4292009-11-09 23:28:39 +0000622/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
623/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000624static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000625 const TargetData *TD, const DominatorTree *DT,
626 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000627 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
628 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
629
Chris Lattnerd06094f2009-11-10 00:55:12 +0000630 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000631 if (Constant *CRHS = dyn_cast<Constant>(RHS))
632 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000633
Chris Lattnerd06094f2009-11-10 00:55:12 +0000634 // If we have a constant, make sure it is on the RHS.
635 std::swap(LHS, RHS);
636 Pred = CmpInst::getSwappedPredicate(Pred);
637 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000638
Chris Lattner210c5d42009-11-09 23:55:12 +0000639 // Fold trivial predicates.
640 if (Pred == FCmpInst::FCMP_FALSE)
641 return ConstantInt::get(GetCompareTy(LHS), 0);
642 if (Pred == FCmpInst::FCMP_TRUE)
643 return ConstantInt::get(GetCompareTy(LHS), 1);
644
Chris Lattner210c5d42009-11-09 23:55:12 +0000645 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
646 return UndefValue::get(GetCompareTy(LHS));
647
648 // fcmp x,x -> true/false. Not all compares are foldable.
649 if (LHS == RHS) {
650 if (CmpInst::isTrueWhenEqual(Pred))
651 return ConstantInt::get(GetCompareTy(LHS), 1);
652 if (CmpInst::isFalseWhenEqual(Pred))
653 return ConstantInt::get(GetCompareTy(LHS), 0);
654 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000655
Chris Lattner210c5d42009-11-09 23:55:12 +0000656 // Handle fcmp with constant RHS
657 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
658 // If the constant is a nan, see if we can fold the comparison based on it.
659 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
660 if (CFP->getValueAPF().isNaN()) {
661 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
662 return ConstantInt::getFalse(CFP->getContext());
663 assert(FCmpInst::isUnordered(Pred) &&
664 "Comparison must be either ordered or unordered!");
665 // True if unordered.
666 return ConstantInt::getTrue(CFP->getContext());
667 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000668 // Check whether the constant is an infinity.
669 if (CFP->getValueAPF().isInfinity()) {
670 if (CFP->getValueAPF().isNegative()) {
671 switch (Pred) {
672 case FCmpInst::FCMP_OLT:
673 // No value is ordered and less than negative infinity.
674 return ConstantInt::getFalse(CFP->getContext());
675 case FCmpInst::FCMP_UGE:
676 // All values are unordered with or at least negative infinity.
677 return ConstantInt::getTrue(CFP->getContext());
678 default:
679 break;
680 }
681 } else {
682 switch (Pred) {
683 case FCmpInst::FCMP_OGT:
684 // No value is ordered and greater than infinity.
685 return ConstantInt::getFalse(CFP->getContext());
686 case FCmpInst::FCMP_ULE:
687 // All values are unordered with and at most infinity.
688 return ConstantInt::getTrue(CFP->getContext());
689 default:
690 break;
691 }
692 }
693 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000694 }
695 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000696
Duncan Sands92826de2010-11-07 16:46:25 +0000697 // If the comparison is with the result of a select instruction, check whether
698 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000699 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000700 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000701 return V;
702
703 // If the comparison is with the result of a phi instruction, check whether
704 // doing the compare with each incoming phi value yields a common result.
705 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000706 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000707 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000708
Chris Lattner9dbb4292009-11-09 23:28:39 +0000709 return 0;
710}
711
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000712Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000713 const TargetData *TD, const DominatorTree *DT) {
714 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000715}
716
Chris Lattner04754262010-04-20 05:32:14 +0000717/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
718/// the result. If not, this returns null.
719Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000720 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000721 // select true, X, Y -> X
722 // select false, X, Y -> Y
723 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
724 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000725
Chris Lattner04754262010-04-20 05:32:14 +0000726 // select C, X, X -> X
727 if (TrueVal == FalseVal)
728 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000729
Chris Lattner04754262010-04-20 05:32:14 +0000730 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
731 return FalseVal;
732 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
733 return TrueVal;
734 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
735 if (isa<Constant>(TrueVal))
736 return TrueVal;
737 return FalseVal;
738 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000739
Chris Lattner04754262010-04-20 05:32:14 +0000740 return 0;
741}
742
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000743/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
744/// fold the result. If not, this returns null.
745Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +0000746 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000747 // The type of the GEP pointer operand.
748 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
749
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000750 // getelementptr P -> P.
751 if (NumOps == 1)
752 return Ops[0];
753
Duncan Sands85bbff62010-11-22 13:42:49 +0000754 if (isa<UndefValue>(Ops[0])) {
755 // Compute the (pointer) type returned by the GEP instruction.
756 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
757 NumOps-1);
758 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
759 return UndefValue::get(GEPTy);
760 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000761
Duncan Sandse60d79f2010-11-21 13:53:09 +0000762 if (NumOps == 2) {
763 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000764 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
765 if (C->isZero())
766 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +0000767 // getelementptr P, N -> P if P points to a type of zero size.
768 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000769 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +0000770 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +0000771 return Ops[0];
772 }
773 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000774
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000775 // Check to see if this is constant foldable.
776 for (unsigned i = 0; i != NumOps; ++i)
777 if (!isa<Constant>(Ops[i]))
778 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000779
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000780 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
781 (Constant *const*)Ops+1, NumOps-1);
782}
783
Duncan Sandsff103412010-11-17 04:30:22 +0000784/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
785static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
786 // If all of the PHI's incoming values are the same then replace the PHI node
787 // with the common value.
788 Value *CommonValue = 0;
789 bool HasUndefInput = false;
790 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
791 Value *Incoming = PN->getIncomingValue(i);
792 // If the incoming value is the phi node itself, it can safely be skipped.
793 if (Incoming == PN) continue;
794 if (isa<UndefValue>(Incoming)) {
795 // Remember that we saw an undef value, but otherwise ignore them.
796 HasUndefInput = true;
797 continue;
798 }
799 if (CommonValue && Incoming != CommonValue)
800 return 0; // Not the same, bail out.
801 CommonValue = Incoming;
802 }
803
804 // If CommonValue is null then all of the incoming values were either undef or
805 // equal to the phi node itself.
806 if (!CommonValue)
807 return UndefValue::get(PN->getType());
808
809 // If we have a PHI node like phi(X, undef, X), where X is defined by some
810 // instruction, we cannot return X as the result of the PHI node unless it
811 // dominates the PHI block.
812 if (HasUndefInput)
813 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
814
815 return CommonValue;
816}
817
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000818
Chris Lattnerd06094f2009-11-10 00:55:12 +0000819//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000820
Chris Lattnerd06094f2009-11-10 00:55:12 +0000821/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
822/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000823static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000824 const TargetData *TD, const DominatorTree *DT,
825 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000826 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +0000827 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
828 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000829 default:
830 if (Constant *CLHS = dyn_cast<Constant>(LHS))
831 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
832 Constant *COps[] = {CLHS, CRHS};
833 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
834 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000835
836 // If the operation is with the result of a select instruction, check whether
837 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000838 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000839 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
840 MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000841 return V;
842
843 // If the operation is with the result of a phi instruction, check whether
844 // operating on all incoming values of the phi always yields the same value.
845 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000846 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000847 return V;
848
Chris Lattnerd06094f2009-11-10 00:55:12 +0000849 return 0;
850 }
851}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000852
Duncan Sands12a86f52010-11-14 11:23:23 +0000853Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000854 const TargetData *TD, const DominatorTree *DT) {
855 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +0000856}
857
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000858/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
859/// fold the result.
860static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000861 const TargetData *TD, const DominatorTree *DT,
862 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000863 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +0000864 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
865 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000866}
867
868Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000869 const TargetData *TD, const DominatorTree *DT) {
870 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000871}
Chris Lattnere3453782009-11-10 01:08:51 +0000872
873/// SimplifyInstruction - See if we can compute a simplified version of this
874/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +0000875Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
876 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +0000877 Value *Result;
878
Chris Lattnere3453782009-11-10 01:08:51 +0000879 switch (I->getOpcode()) {
880 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000881 Result = ConstantFoldInstruction(I, TD);
882 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000883 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000884 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
885 cast<BinaryOperator>(I)->hasNoSignedWrap(),
886 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
887 TD, DT);
888 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +0000889 case Instruction::Sub:
890 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
891 cast<BinaryOperator>(I)->hasNoSignedWrap(),
892 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
893 TD, DT);
894 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000895 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000896 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
897 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000898 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000899 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
900 break;
Duncan Sands2b749872010-11-17 18:52:15 +0000901 case Instruction::Xor:
902 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
903 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000904 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000905 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
906 I->getOperand(0), I->getOperand(1), TD, DT);
907 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000908 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000909 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
910 I->getOperand(0), I->getOperand(1), TD, DT);
911 break;
Chris Lattner04754262010-04-20 05:32:14 +0000912 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000913 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
914 I->getOperand(2), TD, DT);
915 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000916 case Instruction::GetElementPtr: {
917 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +0000918 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
919 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000920 }
Duncan Sandscd6636c2010-11-14 13:30:18 +0000921 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000922 Result = SimplifyPHINode(cast<PHINode>(I), DT);
923 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000924 }
Duncan Sandsd261dc62010-11-17 08:35:29 +0000925
926 /// If called on unreachable code, the above logic may report that the
927 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000928 /// detecting that case here, returning a safe value instead.
929 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +0000930}
931
Chris Lattner40d8c282009-11-10 22:26:15 +0000932/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
933/// delete the From instruction. In addition to a basic RAUW, this does a
934/// recursive simplification of the newly formed instructions. This catches
935/// things where one simplification exposes other opportunities. This only
936/// simplifies and deletes scalar operations, it does not change the CFG.
937///
938void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +0000939 const TargetData *TD,
940 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +0000941 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000942
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000943 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
944 // we can know if it gets deleted out from under us or replaced in a
945 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +0000946 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000947 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000948
Chris Lattner40d8c282009-11-10 22:26:15 +0000949 while (!From->use_empty()) {
950 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000951 Use &TheUse = From->use_begin().getUse();
952 Instruction *User = cast<Instruction>(TheUse.getUser());
953 TheUse = To;
954
955 // Check to see if the instruction can be folded due to the operand
956 // replacement. For example changing (or X, Y) into (or X, -1) can replace
957 // the 'or' with -1.
958 Value *SimplifiedVal;
959 {
960 // Sanity check to make sure 'User' doesn't dangle across
961 // SimplifyInstruction.
962 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +0000963
Duncan Sandseff05812010-11-14 18:36:10 +0000964 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000965 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +0000966 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000967
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000968 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +0000969 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000970 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
971 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +0000972
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000973 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +0000974
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000975 // If the recursive simplification ended up revisiting and deleting
976 // 'From' then we're done.
977 if (From == 0)
978 return;
Chris Lattner40d8c282009-11-10 22:26:15 +0000979 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000980
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000981 // If 'From' has value handles referring to it, do a real RAUW to update them.
982 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000983
Chris Lattner40d8c282009-11-10 22:26:15 +0000984 From->eraseFromParent();
985}