blob: 4b6320bb46a8c5b9201ecd16b99582b930801b88 [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"
Duncan Sandse60d79f2010-11-21 13:53:09 +000021#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000022using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000023using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000024
Duncan Sands18450092010-11-16 12:16:38 +000025#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000026
27static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000028 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000029static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000030 const DominatorTree *, unsigned);
31
32/// ValueDominatesPHI - Does the given value dominate the specified phi node?
33static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
34 Instruction *I = dyn_cast<Instruction>(V);
35 if (!I)
36 // Arguments and constants dominate all instructions.
37 return true;
38
39 // If we have a DominatorTree then do a precise test.
40 if (DT)
41 return DT->dominates(I, P);
42
43 // Otherwise, if the instruction is in the entry block, and is not an invoke,
44 // then it obviously dominates all phi nodes.
45 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
46 !isa<InvokeInst>(I))
47 return true;
48
49 return false;
50}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000051
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000052/// ThreadBinOpOverSelect - In the case of a binary operation with a select
53/// instruction as an operand, try to simplify the binop by seeing whether
54/// evaluating it on both branches of the select results in the same value.
55/// Returns the common value if so, otherwise returns null.
56static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +000057 const TargetData *TD,
58 const DominatorTree *DT,
59 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000060 SelectInst *SI;
61 if (isa<SelectInst>(LHS)) {
62 SI = cast<SelectInst>(LHS);
63 } else {
64 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
65 SI = cast<SelectInst>(RHS);
66 }
67
68 // Evaluate the BinOp on the true and false branches of the select.
69 Value *TV;
70 Value *FV;
71 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +000072 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
73 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000074 } else {
Duncan Sands18450092010-11-16 12:16:38 +000075 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
76 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000077 }
78
79 // If they simplified to the same value, then return the common value.
80 // If they both failed to simplify then return null.
81 if (TV == FV)
82 return TV;
83
84 // If one branch simplified to undef, return the other one.
85 if (TV && isa<UndefValue>(TV))
86 return FV;
87 if (FV && isa<UndefValue>(FV))
88 return TV;
89
90 // If applying the operation did not change the true and false select values,
91 // then the result of the binop is the select itself.
92 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
93 return SI;
94
95 // If one branch simplified and the other did not, and the simplified
96 // value is equal to the unsimplified one, return the simplified value.
97 // For example, select (cond, X, X & Z) & Z -> X & Z.
98 if ((FV && !TV) || (TV && !FV)) {
99 // Check that the simplified value has the form "X op Y" where "op" is the
100 // same as the original operation.
101 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
102 if (Simplified && Simplified->getOpcode() == Opcode) {
103 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
104 // We already know that "op" is the same as for the simplified value. See
105 // if the operands match too. If so, return the simplified value.
106 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
107 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
108 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
109 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
110 Simplified->getOperand(1) == UnsimplifiedRHS)
111 return Simplified;
112 if (Simplified->isCommutative() &&
113 Simplified->getOperand(1) == UnsimplifiedLHS &&
114 Simplified->getOperand(0) == UnsimplifiedRHS)
115 return Simplified;
116 }
117 }
118
119 return 0;
120}
121
122/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
123/// try to simplify the comparison by seeing whether both branches of the select
124/// result in the same value. Returns the common value if so, otherwise returns
125/// null.
126static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000127 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000128 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000129 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000130 // Make sure the select is on the LHS.
131 if (!isa<SelectInst>(LHS)) {
132 std::swap(LHS, RHS);
133 Pred = CmpInst::getSwappedPredicate(Pred);
134 }
135 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
136 SelectInst *SI = cast<SelectInst>(LHS);
137
138 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
139 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000140 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000141 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000142 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000143 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000144 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000145 // It does! If they simplified to the same value, then use it as the
146 // result of the original comparison.
147 if (TCmp == FCmp)
148 return TCmp;
149 return 0;
150}
151
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000152/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
153/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
154/// it on the incoming phi values yields the same result for every value. If so
155/// returns the common value, otherwise returns null.
156static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000157 const TargetData *TD, const DominatorTree *DT,
158 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000159 PHINode *PI;
160 if (isa<PHINode>(LHS)) {
161 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000162 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
163 if (!ValueDominatesPHI(RHS, PI, DT))
164 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000165 } else {
166 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
167 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000168 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
169 if (!ValueDominatesPHI(LHS, PI, DT))
170 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000171 }
172
173 // Evaluate the BinOp on the incoming phi values.
174 Value *CommonValue = 0;
175 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000176 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000177 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000178 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000179 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000180 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
181 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000182 // If the operation failed to simplify, or simplified to a different value
183 // to previously, then give up.
184 if (!V || (CommonValue && V != CommonValue))
185 return 0;
186 CommonValue = V;
187 }
188
189 return CommonValue;
190}
191
192/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
193/// try to simplify the comparison by seeing whether comparing with all of the
194/// incoming phi values yields the same result every time. If so returns the
195/// common result, otherwise returns null.
196static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000197 const TargetData *TD, const DominatorTree *DT,
198 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000199 // Make sure the phi is on the LHS.
200 if (!isa<PHINode>(LHS)) {
201 std::swap(LHS, RHS);
202 Pred = CmpInst::getSwappedPredicate(Pred);
203 }
204 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
205 PHINode *PI = cast<PHINode>(LHS);
206
Duncan Sands18450092010-11-16 12:16:38 +0000207 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
208 if (!ValueDominatesPHI(RHS, PI, DT))
209 return 0;
210
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000211 // Evaluate the BinOp on the incoming phi values.
212 Value *CommonValue = 0;
213 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000214 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000215 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000216 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000217 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000218 // If the operation failed to simplify, or simplified to a different value
219 // to previously, then give up.
220 if (!V || (CommonValue && V != CommonValue))
221 return 0;
222 CommonValue = V;
223 }
224
225 return CommonValue;
226}
227
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000228/// SimplifyAddInst - Given operands for an Add, see if we can
229/// fold the result. If not, this returns null.
230Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands18450092010-11-16 12:16:38 +0000231 const TargetData *TD, const DominatorTree *) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000232 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
233 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
234 Constant *Ops[] = { CLHS, CRHS };
235 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
236 Ops, 2, TD);
237 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000238
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000239 // Canonicalize the constant to the RHS.
240 std::swap(Op0, Op1);
241 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000242
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000243 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
244 // X + undef -> undef
245 if (isa<UndefValue>(Op1C))
246 return Op1C;
Duncan Sands12a86f52010-11-14 11:23:23 +0000247
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000248 // X + 0 --> X
249 if (Op1C->isNullValue())
250 return Op0;
251 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000252
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000253 // FIXME: Could pull several more out of instcombine.
Duncan Sands87689cf2010-11-19 09:20:39 +0000254
255 // Threading Add over selects and phi nodes is pointless, so don't bother.
256 // Threading over the select in "A + select(cond, B, C)" means evaluating
257 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
258 // only if B and C are equal. If B and C are equal then (since we assume
259 // that operands have already been simplified) "select(cond, B, C)" should
260 // have been simplified to the common value of B and C already. Analysing
261 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
262 // for threading over phi nodes.
263
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000264 return 0;
265}
266
Chris Lattnerd06094f2009-11-10 00:55:12 +0000267/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000268/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000269static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000270 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000271 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
272 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
273 Constant *Ops[] = { CLHS, CRHS };
274 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
275 Ops, 2, TD);
276 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000277
Chris Lattnerd06094f2009-11-10 00:55:12 +0000278 // Canonicalize the constant to the RHS.
279 std::swap(Op0, Op1);
280 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000281
Chris Lattnerd06094f2009-11-10 00:55:12 +0000282 // X & undef -> 0
283 if (isa<UndefValue>(Op1))
284 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000285
Chris Lattnerd06094f2009-11-10 00:55:12 +0000286 // X & X = X
287 if (Op0 == Op1)
288 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000289
Duncan Sands2b749872010-11-17 18:52:15 +0000290 // X & 0 = 0
291 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000292 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000293
Duncan Sands2b749872010-11-17 18:52:15 +0000294 // X & -1 = X
295 if (match(Op1, m_AllOnes()))
296 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000297
Chris Lattnerd06094f2009-11-10 00:55:12 +0000298 // A & ~A = ~A & A = 0
299 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000300 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
301 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000302 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000303
Chris Lattnerd06094f2009-11-10 00:55:12 +0000304 // (A | ?) & A = A
305 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
306 (A == Op1 || B == Op1))
307 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000308
Chris Lattnerd06094f2009-11-10 00:55:12 +0000309 // A & (A | ?) = A
310 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
311 (A == Op0 || B == Op0))
312 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000313
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000314 // (A & B) & A -> A & B
315 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
316 (A == Op1 || B == Op1))
317 return Op0;
318
319 // A & (A & B) -> A & B
320 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
321 (A == Op0 || B == Op0))
322 return Op1;
323
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000324 // If the operation is with the result of a select instruction, check whether
325 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000326 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000327 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000328 MaxRecurse-1))
329 return V;
330
331 // If the operation is with the result of a phi instruction, check whether
332 // operating on all incoming values of the phi always yields the same value.
333 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000334 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000335 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000336 return V;
337
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000338 return 0;
339}
340
Duncan Sands18450092010-11-16 12:16:38 +0000341Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
342 const DominatorTree *DT) {
343 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000344}
345
Chris Lattnerd06094f2009-11-10 00:55:12 +0000346/// SimplifyOrInst - Given operands for an Or, see if we can
347/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000348static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000349 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000350 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
351 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
352 Constant *Ops[] = { CLHS, CRHS };
353 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
354 Ops, 2, TD);
355 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000356
Chris Lattnerd06094f2009-11-10 00:55:12 +0000357 // Canonicalize the constant to the RHS.
358 std::swap(Op0, Op1);
359 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000360
Chris Lattnerd06094f2009-11-10 00:55:12 +0000361 // X | undef -> -1
362 if (isa<UndefValue>(Op1))
363 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000364
Chris Lattnerd06094f2009-11-10 00:55:12 +0000365 // X | X = X
366 if (Op0 == Op1)
367 return Op0;
368
Duncan Sands2b749872010-11-17 18:52:15 +0000369 // X | 0 = X
370 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000371 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000372
Duncan Sands2b749872010-11-17 18:52:15 +0000373 // X | -1 = -1
374 if (match(Op1, m_AllOnes()))
375 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000376
Chris Lattnerd06094f2009-11-10 00:55:12 +0000377 // A | ~A = ~A | A = -1
378 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000379 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
380 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000381 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000382
Chris Lattnerd06094f2009-11-10 00:55:12 +0000383 // (A & ?) | A = A
384 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
385 (A == Op1 || B == Op1))
386 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000387
Chris Lattnerd06094f2009-11-10 00:55:12 +0000388 // A | (A & ?) = A
389 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
390 (A == Op0 || B == Op0))
391 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000392
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000393 // (A | B) | A -> A | B
394 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
395 (A == Op1 || B == Op1))
396 return Op0;
397
398 // A | (A | B) -> A | B
399 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
400 (A == Op0 || B == Op0))
401 return Op1;
402
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000403 // If the operation is with the result of a select instruction, check whether
404 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000405 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000406 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000407 MaxRecurse-1))
408 return V;
409
410 // If the operation is with the result of a phi instruction, check whether
411 // operating on all incoming values of the phi always yields the same value.
412 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000413 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000414 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000415 return V;
416
Chris Lattnerd06094f2009-11-10 00:55:12 +0000417 return 0;
418}
419
Duncan Sands18450092010-11-16 12:16:38 +0000420Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
421 const DominatorTree *DT) {
422 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000423}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000424
Duncan Sands2b749872010-11-17 18:52:15 +0000425/// SimplifyXorInst - Given operands for a Xor, see if we can
426/// fold the result. If not, this returns null.
427static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
428 const DominatorTree *DT, unsigned MaxRecurse) {
429 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
430 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
431 Constant *Ops[] = { CLHS, CRHS };
432 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
433 Ops, 2, TD);
434 }
435
436 // Canonicalize the constant to the RHS.
437 std::swap(Op0, Op1);
438 }
439
440 // A ^ undef -> undef
441 if (isa<UndefValue>(Op1))
442 return UndefValue::get(Op0->getType());
443
444 // A ^ 0 = A
445 if (match(Op1, m_Zero()))
446 return Op0;
447
448 // A ^ A = 0
449 if (Op0 == Op1)
450 return Constant::getNullValue(Op0->getType());
451
452 // A ^ ~A = ~A ^ A = -1
453 Value *A, *B;
454 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
455 (match(Op1, m_Not(m_Value(A))) && A == Op0))
456 return Constant::getAllOnesValue(Op0->getType());
457
458 // (A ^ B) ^ A = B
459 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
460 (A == Op1 || B == Op1))
461 return A == Op1 ? B : A;
462
463 // A ^ (A ^ B) = B
464 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
465 (A == Op0 || B == Op0))
466 return A == Op0 ? B : A;
467
Duncan Sands87689cf2010-11-19 09:20:39 +0000468 // Threading Xor over selects and phi nodes is pointless, so don't bother.
469 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
470 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
471 // only if B and C are equal. If B and C are equal then (since we assume
472 // that operands have already been simplified) "select(cond, B, C)" should
473 // have been simplified to the common value of B and C already. Analysing
474 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
475 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000476
477 return 0;
478}
479
480Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
481 const DominatorTree *DT) {
482 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
483}
484
Chris Lattner210c5d42009-11-09 23:55:12 +0000485static const Type *GetCompareTy(Value *Op) {
486 return CmpInst::makeCmpResultType(Op->getType());
487}
488
Chris Lattner9dbb4292009-11-09 23:28:39 +0000489/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
490/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000491static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000492 const TargetData *TD, const DominatorTree *DT,
493 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000494 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000495 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000496
Chris Lattnerd06094f2009-11-10 00:55:12 +0000497 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000498 if (Constant *CRHS = dyn_cast<Constant>(RHS))
499 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000500
501 // If we have a constant, make sure it is on the RHS.
502 std::swap(LHS, RHS);
503 Pred = CmpInst::getSwappedPredicate(Pred);
504 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000505
Chris Lattner210c5d42009-11-09 23:55:12 +0000506 // ITy - This is the return type of the compare we're considering.
507 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000508
Chris Lattner210c5d42009-11-09 23:55:12 +0000509 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000510 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
511 // because X could be 0.
512 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000513 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000514
Chris Lattner210c5d42009-11-09 23:55:12 +0000515 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
516 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000517 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000518 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000519 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000520 isa<ConstantPointerNull>(RHS)))
521 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000522
Chris Lattner210c5d42009-11-09 23:55:12 +0000523 // See if we are doing a comparison with a constant.
524 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
525 // If we have an icmp le or icmp ge instruction, turn it into the
526 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
527 // them being folded in the code below.
528 switch (Pred) {
529 default: break;
530 case ICmpInst::ICMP_ULE:
531 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
532 return ConstantInt::getTrue(CI->getContext());
533 break;
534 case ICmpInst::ICMP_SLE:
535 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
536 return ConstantInt::getTrue(CI->getContext());
537 break;
538 case ICmpInst::ICMP_UGE:
539 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
540 return ConstantInt::getTrue(CI->getContext());
541 break;
542 case ICmpInst::ICMP_SGE:
543 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
544 return ConstantInt::getTrue(CI->getContext());
545 break;
546 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000547 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000548
549 // If the comparison is with the result of a select instruction, check whether
550 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000551 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000552 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000553 return V;
554
555 // If the comparison is with the result of a phi instruction, check whether
556 // doing the compare with each incoming phi value yields a common result.
557 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000558 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000559 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000560
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000561 return 0;
562}
563
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000564Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000565 const TargetData *TD, const DominatorTree *DT) {
566 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000567}
568
Chris Lattner9dbb4292009-11-09 23:28:39 +0000569/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
570/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000571static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000572 const TargetData *TD, const DominatorTree *DT,
573 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000574 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
575 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
576
Chris Lattnerd06094f2009-11-10 00:55:12 +0000577 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000578 if (Constant *CRHS = dyn_cast<Constant>(RHS))
579 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000580
Chris Lattnerd06094f2009-11-10 00:55:12 +0000581 // If we have a constant, make sure it is on the RHS.
582 std::swap(LHS, RHS);
583 Pred = CmpInst::getSwappedPredicate(Pred);
584 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000585
Chris Lattner210c5d42009-11-09 23:55:12 +0000586 // Fold trivial predicates.
587 if (Pred == FCmpInst::FCMP_FALSE)
588 return ConstantInt::get(GetCompareTy(LHS), 0);
589 if (Pred == FCmpInst::FCMP_TRUE)
590 return ConstantInt::get(GetCompareTy(LHS), 1);
591
Chris Lattner210c5d42009-11-09 23:55:12 +0000592 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
593 return UndefValue::get(GetCompareTy(LHS));
594
595 // fcmp x,x -> true/false. Not all compares are foldable.
596 if (LHS == RHS) {
597 if (CmpInst::isTrueWhenEqual(Pred))
598 return ConstantInt::get(GetCompareTy(LHS), 1);
599 if (CmpInst::isFalseWhenEqual(Pred))
600 return ConstantInt::get(GetCompareTy(LHS), 0);
601 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000602
Chris Lattner210c5d42009-11-09 23:55:12 +0000603 // Handle fcmp with constant RHS
604 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
605 // If the constant is a nan, see if we can fold the comparison based on it.
606 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
607 if (CFP->getValueAPF().isNaN()) {
608 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
609 return ConstantInt::getFalse(CFP->getContext());
610 assert(FCmpInst::isUnordered(Pred) &&
611 "Comparison must be either ordered or unordered!");
612 // True if unordered.
613 return ConstantInt::getTrue(CFP->getContext());
614 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000615 // Check whether the constant is an infinity.
616 if (CFP->getValueAPF().isInfinity()) {
617 if (CFP->getValueAPF().isNegative()) {
618 switch (Pred) {
619 case FCmpInst::FCMP_OLT:
620 // No value is ordered and less than negative infinity.
621 return ConstantInt::getFalse(CFP->getContext());
622 case FCmpInst::FCMP_UGE:
623 // All values are unordered with or at least negative infinity.
624 return ConstantInt::getTrue(CFP->getContext());
625 default:
626 break;
627 }
628 } else {
629 switch (Pred) {
630 case FCmpInst::FCMP_OGT:
631 // No value is ordered and greater than infinity.
632 return ConstantInt::getFalse(CFP->getContext());
633 case FCmpInst::FCMP_ULE:
634 // All values are unordered with and at most infinity.
635 return ConstantInt::getTrue(CFP->getContext());
636 default:
637 break;
638 }
639 }
640 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000641 }
642 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000643
Duncan Sands92826de2010-11-07 16:46:25 +0000644 // If the comparison is with the result of a select instruction, check whether
645 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000646 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000647 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000648 return V;
649
650 // If the comparison is with the result of a phi instruction, check whether
651 // doing the compare with each incoming phi value yields a common result.
652 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000653 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000654 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000655
Chris Lattner9dbb4292009-11-09 23:28:39 +0000656 return 0;
657}
658
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000659Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000660 const TargetData *TD, const DominatorTree *DT) {
661 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000662}
663
Chris Lattner04754262010-04-20 05:32:14 +0000664/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
665/// the result. If not, this returns null.
666Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000667 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000668 // select true, X, Y -> X
669 // select false, X, Y -> Y
670 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
671 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000672
Chris Lattner04754262010-04-20 05:32:14 +0000673 // select C, X, X -> X
674 if (TrueVal == FalseVal)
675 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000676
Chris Lattner04754262010-04-20 05:32:14 +0000677 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
678 return FalseVal;
679 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
680 return TrueVal;
681 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
682 if (isa<Constant>(TrueVal))
683 return TrueVal;
684 return FalseVal;
685 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000686
Chris Lattner04754262010-04-20 05:32:14 +0000687 return 0;
688}
689
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000690/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
691/// fold the result. If not, this returns null.
692Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +0000693 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000694 // The type of the GEP pointer operand.
695 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
696
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000697 // getelementptr P -> P.
698 if (NumOps == 1)
699 return Ops[0];
700
Duncan Sands85bbff62010-11-22 13:42:49 +0000701 if (isa<UndefValue>(Ops[0])) {
702 // Compute the (pointer) type returned by the GEP instruction.
703 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
704 NumOps-1);
705 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
706 return UndefValue::get(GEPTy);
707 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000708
Duncan Sandse60d79f2010-11-21 13:53:09 +0000709 if (NumOps == 2) {
710 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000711 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
712 if (C->isZero())
713 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +0000714 // getelementptr P, N -> P if P points to a type of zero size.
715 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000716 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +0000717 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +0000718 return Ops[0];
719 }
720 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000721
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000722 // Check to see if this is constant foldable.
723 for (unsigned i = 0; i != NumOps; ++i)
724 if (!isa<Constant>(Ops[i]))
725 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000726
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000727 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
728 (Constant *const*)Ops+1, NumOps-1);
729}
730
Duncan Sandsff103412010-11-17 04:30:22 +0000731/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
732static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
733 // If all of the PHI's incoming values are the same then replace the PHI node
734 // with the common value.
735 Value *CommonValue = 0;
736 bool HasUndefInput = false;
737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
738 Value *Incoming = PN->getIncomingValue(i);
739 // If the incoming value is the phi node itself, it can safely be skipped.
740 if (Incoming == PN) continue;
741 if (isa<UndefValue>(Incoming)) {
742 // Remember that we saw an undef value, but otherwise ignore them.
743 HasUndefInput = true;
744 continue;
745 }
746 if (CommonValue && Incoming != CommonValue)
747 return 0; // Not the same, bail out.
748 CommonValue = Incoming;
749 }
750
751 // If CommonValue is null then all of the incoming values were either undef or
752 // equal to the phi node itself.
753 if (!CommonValue)
754 return UndefValue::get(PN->getType());
755
756 // If we have a PHI node like phi(X, undef, X), where X is defined by some
757 // instruction, we cannot return X as the result of the PHI node unless it
758 // dominates the PHI block.
759 if (HasUndefInput)
760 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
761
762 return CommonValue;
763}
764
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000765
Chris Lattnerd06094f2009-11-10 00:55:12 +0000766//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000767
Chris Lattnerd06094f2009-11-10 00:55:12 +0000768/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
769/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000770static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000771 const TargetData *TD, const DominatorTree *DT,
772 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000773 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +0000774 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
775 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000776 default:
777 if (Constant *CLHS = dyn_cast<Constant>(LHS))
778 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
779 Constant *COps[] = {CLHS, CRHS};
780 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
781 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000782
783 // If the operation is with the result of a select instruction, check whether
784 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000785 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000786 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
787 MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000788 return V;
789
790 // If the operation is with the result of a phi instruction, check whether
791 // operating on all incoming values of the phi always yields the same value.
792 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000793 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000794 return V;
795
Chris Lattnerd06094f2009-11-10 00:55:12 +0000796 return 0;
797 }
798}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000799
Duncan Sands12a86f52010-11-14 11:23:23 +0000800Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000801 const TargetData *TD, const DominatorTree *DT) {
802 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +0000803}
804
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000805/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
806/// fold the result.
807static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000808 const TargetData *TD, const DominatorTree *DT,
809 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000810 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +0000811 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
812 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000813}
814
815Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000816 const TargetData *TD, const DominatorTree *DT) {
817 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000818}
Chris Lattnere3453782009-11-10 01:08:51 +0000819
820/// SimplifyInstruction - See if we can compute a simplified version of this
821/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +0000822Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
823 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +0000824 Value *Result;
825
Chris Lattnere3453782009-11-10 01:08:51 +0000826 switch (I->getOpcode()) {
827 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000828 Result = ConstantFoldInstruction(I, TD);
829 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000830 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000831 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
832 cast<BinaryOperator>(I)->hasNoSignedWrap(),
833 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
834 TD, DT);
835 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000836 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000837 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
838 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000839 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000840 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
841 break;
Duncan Sands2b749872010-11-17 18:52:15 +0000842 case Instruction::Xor:
843 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
844 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000845 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000846 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
847 I->getOperand(0), I->getOperand(1), TD, DT);
848 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000849 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000850 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
851 I->getOperand(0), I->getOperand(1), TD, DT);
852 break;
Chris Lattner04754262010-04-20 05:32:14 +0000853 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000854 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
855 I->getOperand(2), TD, DT);
856 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000857 case Instruction::GetElementPtr: {
858 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +0000859 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
860 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000861 }
Duncan Sandscd6636c2010-11-14 13:30:18 +0000862 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000863 Result = SimplifyPHINode(cast<PHINode>(I), DT);
864 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000865 }
Duncan Sandsd261dc62010-11-17 08:35:29 +0000866
867 /// If called on unreachable code, the above logic may report that the
868 /// instruction simplified to itself. Make life easier for users by
869 /// detecting that case here, returning null if it occurs.
870 return Result == I ? 0 : Result;
Chris Lattnere3453782009-11-10 01:08:51 +0000871}
872
Chris Lattner40d8c282009-11-10 22:26:15 +0000873/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
874/// delete the From instruction. In addition to a basic RAUW, this does a
875/// recursive simplification of the newly formed instructions. This catches
876/// things where one simplification exposes other opportunities. This only
877/// simplifies and deletes scalar operations, it does not change the CFG.
878///
879void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +0000880 const TargetData *TD,
881 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +0000882 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000883
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000884 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
885 // we can know if it gets deleted out from under us or replaced in a
886 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +0000887 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000888 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000889
Chris Lattner40d8c282009-11-10 22:26:15 +0000890 while (!From->use_empty()) {
891 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000892 Use &TheUse = From->use_begin().getUse();
893 Instruction *User = cast<Instruction>(TheUse.getUser());
894 TheUse = To;
895
896 // Check to see if the instruction can be folded due to the operand
897 // replacement. For example changing (or X, Y) into (or X, -1) can replace
898 // the 'or' with -1.
899 Value *SimplifiedVal;
900 {
901 // Sanity check to make sure 'User' doesn't dangle across
902 // SimplifyInstruction.
903 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +0000904
Duncan Sandseff05812010-11-14 18:36:10 +0000905 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000906 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +0000907 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000908
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000909 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +0000910 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000911 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
912 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +0000913
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000914 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +0000915
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000916 // If the recursive simplification ended up revisiting and deleting
917 // 'From' then we're done.
918 if (From == 0)
919 return;
Chris Lattner40d8c282009-11-10 22:26:15 +0000920 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000921
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000922 // If 'From' has value handles referring to it, do a real RAUW to update them.
923 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000924
Chris Lattner40d8c282009-11-10 22:26:15 +0000925 From->eraseFromParent();
926}