blob: ac21a9ae20b625bbe371581f43ce43aa329c3ffd [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
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000245 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
246 // X + undef -> undef
247 if (isa<UndefValue>(Op1C))
248 return Op1C;
Duncan Sands12a86f52010-11-14 11:23:23 +0000249
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000250 // X + 0 --> X
251 if (Op1C->isNullValue())
252 return Op0;
253 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000254
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000255 // FIXME: Could pull several more out of instcombine.
Duncan Sands87689cf2010-11-19 09:20:39 +0000256
257 // Threading Add over selects and phi nodes is pointless, so don't bother.
258 // Threading over the select in "A + select(cond, B, C)" means evaluating
259 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
260 // only if B and C are equal. If B and C are equal then (since we assume
261 // that operands have already been simplified) "select(cond, B, C)" should
262 // have been simplified to the common value of B and C already. Analysing
263 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
264 // for threading over phi nodes.
265
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000266 return 0;
267}
268
Chris Lattnerd06094f2009-11-10 00:55:12 +0000269/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000270/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000271static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000272 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000273 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
274 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
275 Constant *Ops[] = { CLHS, CRHS };
276 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
277 Ops, 2, TD);
278 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000279
Chris Lattnerd06094f2009-11-10 00:55:12 +0000280 // Canonicalize the constant to the RHS.
281 std::swap(Op0, Op1);
282 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000283
Chris Lattnerd06094f2009-11-10 00:55:12 +0000284 // X & undef -> 0
285 if (isa<UndefValue>(Op1))
286 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000287
Chris Lattnerd06094f2009-11-10 00:55:12 +0000288 // X & X = X
289 if (Op0 == Op1)
290 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000291
Duncan Sands2b749872010-11-17 18:52:15 +0000292 // X & 0 = 0
293 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000294 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000295
Duncan Sands2b749872010-11-17 18:52:15 +0000296 // X & -1 = X
297 if (match(Op1, m_AllOnes()))
298 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000299
Chris Lattnerd06094f2009-11-10 00:55:12 +0000300 // A & ~A = ~A & A = 0
301 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000302 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
303 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000304 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000305
Chris Lattnerd06094f2009-11-10 00:55:12 +0000306 // (A | ?) & A = A
307 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
308 (A == Op1 || B == Op1))
309 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000310
Chris Lattnerd06094f2009-11-10 00:55:12 +0000311 // A & (A | ?) = A
312 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
313 (A == Op0 || B == Op0))
314 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000315
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000316 // (A & B) & A -> A & B
317 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
318 (A == Op1 || B == Op1))
319 return Op0;
320
321 // A & (A & B) -> A & B
322 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
323 (A == Op0 || B == Op0))
324 return Op1;
325
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000326 // If the operation is with the result of a select instruction, check whether
327 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000328 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000329 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000330 MaxRecurse-1))
331 return V;
332
333 // If the operation is with the result of a phi instruction, check whether
334 // operating on all incoming values of the phi always yields the same value.
335 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000336 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000337 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000338 return V;
339
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000340 return 0;
341}
342
Duncan Sands18450092010-11-16 12:16:38 +0000343Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
344 const DominatorTree *DT) {
345 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000346}
347
Chris Lattnerd06094f2009-11-10 00:55:12 +0000348/// SimplifyOrInst - Given operands for an Or, see if we can
349/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000350static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000351 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000352 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
353 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
354 Constant *Ops[] = { CLHS, CRHS };
355 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
356 Ops, 2, TD);
357 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000358
Chris Lattnerd06094f2009-11-10 00:55:12 +0000359 // Canonicalize the constant to the RHS.
360 std::swap(Op0, Op1);
361 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000362
Chris Lattnerd06094f2009-11-10 00:55:12 +0000363 // X | undef -> -1
364 if (isa<UndefValue>(Op1))
365 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000366
Chris Lattnerd06094f2009-11-10 00:55:12 +0000367 // X | X = X
368 if (Op0 == Op1)
369 return Op0;
370
Duncan Sands2b749872010-11-17 18:52:15 +0000371 // X | 0 = X
372 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000373 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000374
Duncan Sands2b749872010-11-17 18:52:15 +0000375 // X | -1 = -1
376 if (match(Op1, m_AllOnes()))
377 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000378
Chris Lattnerd06094f2009-11-10 00:55:12 +0000379 // A | ~A = ~A | A = -1
380 Value *A, *B;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000381 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
382 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000383 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000384
Chris Lattnerd06094f2009-11-10 00:55:12 +0000385 // (A & ?) | A = A
386 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
387 (A == Op1 || B == Op1))
388 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000389
Chris Lattnerd06094f2009-11-10 00:55:12 +0000390 // A | (A & ?) = A
391 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
392 (A == Op0 || B == Op0))
393 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000394
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000395 // (A | B) | A -> A | B
396 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
397 (A == Op1 || B == Op1))
398 return Op0;
399
400 // A | (A | B) -> A | B
401 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
402 (A == Op0 || B == Op0))
403 return Op1;
404
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000405 // If the operation is with the result of a select instruction, check whether
406 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000407 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000408 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000409 MaxRecurse-1))
410 return V;
411
412 // If the operation is with the result of a phi instruction, check whether
413 // operating on all incoming values of the phi always yields the same value.
414 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000415 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000416 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000417 return V;
418
Chris Lattnerd06094f2009-11-10 00:55:12 +0000419 return 0;
420}
421
Duncan Sands18450092010-11-16 12:16:38 +0000422Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
423 const DominatorTree *DT) {
424 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000425}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000426
Duncan Sands2b749872010-11-17 18:52:15 +0000427/// SimplifyXorInst - Given operands for a Xor, see if we can
428/// fold the result. If not, this returns null.
429static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
430 const DominatorTree *DT, unsigned MaxRecurse) {
431 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
432 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
433 Constant *Ops[] = { CLHS, CRHS };
434 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
435 Ops, 2, TD);
436 }
437
438 // Canonicalize the constant to the RHS.
439 std::swap(Op0, Op1);
440 }
441
442 // A ^ undef -> undef
443 if (isa<UndefValue>(Op1))
444 return UndefValue::get(Op0->getType());
445
446 // A ^ 0 = A
447 if (match(Op1, m_Zero()))
448 return Op0;
449
450 // A ^ A = 0
451 if (Op0 == Op1)
452 return Constant::getNullValue(Op0->getType());
453
454 // A ^ ~A = ~A ^ A = -1
455 Value *A, *B;
456 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
457 (match(Op1, m_Not(m_Value(A))) && A == Op0))
458 return Constant::getAllOnesValue(Op0->getType());
459
460 // (A ^ B) ^ A = B
461 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
462 (A == Op1 || B == Op1))
463 return A == Op1 ? B : A;
464
465 // A ^ (A ^ B) = B
466 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
467 (A == Op0 || B == Op0))
468 return A == Op0 ? B : A;
469
Duncan Sands87689cf2010-11-19 09:20:39 +0000470 // Threading Xor over selects and phi nodes is pointless, so don't bother.
471 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
472 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
473 // only if B and C are equal. If B and C are equal then (since we assume
474 // that operands have already been simplified) "select(cond, B, C)" should
475 // have been simplified to the common value of B and C already. Analysing
476 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
477 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000478
479 return 0;
480}
481
482Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
483 const DominatorTree *DT) {
484 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
485}
486
Chris Lattner210c5d42009-11-09 23:55:12 +0000487static const Type *GetCompareTy(Value *Op) {
488 return CmpInst::makeCmpResultType(Op->getType());
489}
490
Chris Lattner9dbb4292009-11-09 23:28:39 +0000491/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
492/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000493static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000494 const TargetData *TD, const DominatorTree *DT,
495 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000496 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000497 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000498
Chris Lattnerd06094f2009-11-10 00:55:12 +0000499 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000500 if (Constant *CRHS = dyn_cast<Constant>(RHS))
501 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000502
503 // If we have a constant, make sure it is on the RHS.
504 std::swap(LHS, RHS);
505 Pred = CmpInst::getSwappedPredicate(Pred);
506 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000507
Chris Lattner210c5d42009-11-09 23:55:12 +0000508 // ITy - This is the return type of the compare we're considering.
509 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000510
Chris Lattner210c5d42009-11-09 23:55:12 +0000511 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000512 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
513 // because X could be 0.
514 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000515 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000516
Chris Lattner210c5d42009-11-09 23:55:12 +0000517 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
518 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000519 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000520 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000521 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000522 isa<ConstantPointerNull>(RHS)))
523 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000524
Chris Lattner210c5d42009-11-09 23:55:12 +0000525 // See if we are doing a comparison with a constant.
526 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
527 // If we have an icmp le or icmp ge instruction, turn it into the
528 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
529 // them being folded in the code below.
530 switch (Pred) {
531 default: break;
532 case ICmpInst::ICMP_ULE:
533 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
534 return ConstantInt::getTrue(CI->getContext());
535 break;
536 case ICmpInst::ICMP_SLE:
537 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
538 return ConstantInt::getTrue(CI->getContext());
539 break;
540 case ICmpInst::ICMP_UGE:
541 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
542 return ConstantInt::getTrue(CI->getContext());
543 break;
544 case ICmpInst::ICMP_SGE:
545 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
546 return ConstantInt::getTrue(CI->getContext());
547 break;
548 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000549 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000550
551 // If the comparison is with the result of a select instruction, check whether
552 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000553 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000554 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000555 return V;
556
557 // If the comparison is with the result of a phi instruction, check whether
558 // doing the compare with each incoming phi value yields a common result.
559 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000560 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000561 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000562
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000563 return 0;
564}
565
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000566Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000567 const TargetData *TD, const DominatorTree *DT) {
568 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000569}
570
Chris Lattner9dbb4292009-11-09 23:28:39 +0000571/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
572/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000573static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000574 const TargetData *TD, const DominatorTree *DT,
575 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000576 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
577 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
578
Chris Lattnerd06094f2009-11-10 00:55:12 +0000579 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000580 if (Constant *CRHS = dyn_cast<Constant>(RHS))
581 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000582
Chris Lattnerd06094f2009-11-10 00:55:12 +0000583 // If we have a constant, make sure it is on the RHS.
584 std::swap(LHS, RHS);
585 Pred = CmpInst::getSwappedPredicate(Pred);
586 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000587
Chris Lattner210c5d42009-11-09 23:55:12 +0000588 // Fold trivial predicates.
589 if (Pred == FCmpInst::FCMP_FALSE)
590 return ConstantInt::get(GetCompareTy(LHS), 0);
591 if (Pred == FCmpInst::FCMP_TRUE)
592 return ConstantInt::get(GetCompareTy(LHS), 1);
593
Chris Lattner210c5d42009-11-09 23:55:12 +0000594 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
595 return UndefValue::get(GetCompareTy(LHS));
596
597 // fcmp x,x -> true/false. Not all compares are foldable.
598 if (LHS == RHS) {
599 if (CmpInst::isTrueWhenEqual(Pred))
600 return ConstantInt::get(GetCompareTy(LHS), 1);
601 if (CmpInst::isFalseWhenEqual(Pred))
602 return ConstantInt::get(GetCompareTy(LHS), 0);
603 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000604
Chris Lattner210c5d42009-11-09 23:55:12 +0000605 // Handle fcmp with constant RHS
606 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
607 // If the constant is a nan, see if we can fold the comparison based on it.
608 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
609 if (CFP->getValueAPF().isNaN()) {
610 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
611 return ConstantInt::getFalse(CFP->getContext());
612 assert(FCmpInst::isUnordered(Pred) &&
613 "Comparison must be either ordered or unordered!");
614 // True if unordered.
615 return ConstantInt::getTrue(CFP->getContext());
616 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000617 // Check whether the constant is an infinity.
618 if (CFP->getValueAPF().isInfinity()) {
619 if (CFP->getValueAPF().isNegative()) {
620 switch (Pred) {
621 case FCmpInst::FCMP_OLT:
622 // No value is ordered and less than negative infinity.
623 return ConstantInt::getFalse(CFP->getContext());
624 case FCmpInst::FCMP_UGE:
625 // All values are unordered with or at least negative infinity.
626 return ConstantInt::getTrue(CFP->getContext());
627 default:
628 break;
629 }
630 } else {
631 switch (Pred) {
632 case FCmpInst::FCMP_OGT:
633 // No value is ordered and greater than infinity.
634 return ConstantInt::getFalse(CFP->getContext());
635 case FCmpInst::FCMP_ULE:
636 // All values are unordered with and at most infinity.
637 return ConstantInt::getTrue(CFP->getContext());
638 default:
639 break;
640 }
641 }
642 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000643 }
644 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000645
Duncan Sands92826de2010-11-07 16:46:25 +0000646 // If the comparison is with the result of a select instruction, check whether
647 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000648 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000649 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000650 return V;
651
652 // If the comparison is with the result of a phi instruction, check whether
653 // doing the compare with each incoming phi value yields a common result.
654 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000655 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000656 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000657
Chris Lattner9dbb4292009-11-09 23:28:39 +0000658 return 0;
659}
660
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000661Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000662 const TargetData *TD, const DominatorTree *DT) {
663 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000664}
665
Chris Lattner04754262010-04-20 05:32:14 +0000666/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
667/// the result. If not, this returns null.
668Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000669 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000670 // select true, X, Y -> X
671 // select false, X, Y -> Y
672 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
673 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000674
Chris Lattner04754262010-04-20 05:32:14 +0000675 // select C, X, X -> X
676 if (TrueVal == FalseVal)
677 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000678
Chris Lattner04754262010-04-20 05:32:14 +0000679 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
680 return FalseVal;
681 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
682 return TrueVal;
683 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
684 if (isa<Constant>(TrueVal))
685 return TrueVal;
686 return FalseVal;
687 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000688
Chris Lattner04754262010-04-20 05:32:14 +0000689 return 0;
690}
691
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000692/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
693/// fold the result. If not, this returns null.
694Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +0000695 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000696 // The type of the GEP pointer operand.
697 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
698
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000699 // getelementptr P -> P.
700 if (NumOps == 1)
701 return Ops[0];
702
Duncan Sands85bbff62010-11-22 13:42:49 +0000703 if (isa<UndefValue>(Ops[0])) {
704 // Compute the (pointer) type returned by the GEP instruction.
705 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
706 NumOps-1);
707 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
708 return UndefValue::get(GEPTy);
709 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000710
Duncan Sandse60d79f2010-11-21 13:53:09 +0000711 if (NumOps == 2) {
712 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000713 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
714 if (C->isZero())
715 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +0000716 // getelementptr P, N -> P if P points to a type of zero size.
717 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000718 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +0000719 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +0000720 return Ops[0];
721 }
722 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000723
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000724 // Check to see if this is constant foldable.
725 for (unsigned i = 0; i != NumOps; ++i)
726 if (!isa<Constant>(Ops[i]))
727 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000728
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000729 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
730 (Constant *const*)Ops+1, NumOps-1);
731}
732
Duncan Sandsff103412010-11-17 04:30:22 +0000733/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
734static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
735 // If all of the PHI's incoming values are the same then replace the PHI node
736 // with the common value.
737 Value *CommonValue = 0;
738 bool HasUndefInput = false;
739 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
740 Value *Incoming = PN->getIncomingValue(i);
741 // If the incoming value is the phi node itself, it can safely be skipped.
742 if (Incoming == PN) continue;
743 if (isa<UndefValue>(Incoming)) {
744 // Remember that we saw an undef value, but otherwise ignore them.
745 HasUndefInput = true;
746 continue;
747 }
748 if (CommonValue && Incoming != CommonValue)
749 return 0; // Not the same, bail out.
750 CommonValue = Incoming;
751 }
752
753 // If CommonValue is null then all of the incoming values were either undef or
754 // equal to the phi node itself.
755 if (!CommonValue)
756 return UndefValue::get(PN->getType());
757
758 // If we have a PHI node like phi(X, undef, X), where X is defined by some
759 // instruction, we cannot return X as the result of the PHI node unless it
760 // dominates the PHI block.
761 if (HasUndefInput)
762 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
763
764 return CommonValue;
765}
766
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000767
Chris Lattnerd06094f2009-11-10 00:55:12 +0000768//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000769
Chris Lattnerd06094f2009-11-10 00:55:12 +0000770/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
771/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000772static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000773 const TargetData *TD, const DominatorTree *DT,
774 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000775 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +0000776 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
777 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000778 default:
779 if (Constant *CLHS = dyn_cast<Constant>(LHS))
780 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
781 Constant *COps[] = {CLHS, CRHS};
782 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
783 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000784
785 // If the operation is with the result of a select instruction, check whether
786 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000787 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000788 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
789 MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000790 return V;
791
792 // If the operation is with the result of a phi instruction, check whether
793 // operating on all incoming values of the phi always yields the same value.
794 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000795 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000796 return V;
797
Chris Lattnerd06094f2009-11-10 00:55:12 +0000798 return 0;
799 }
800}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000801
Duncan Sands12a86f52010-11-14 11:23:23 +0000802Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000803 const TargetData *TD, const DominatorTree *DT) {
804 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +0000805}
806
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000807/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
808/// fold the result.
809static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000810 const TargetData *TD, const DominatorTree *DT,
811 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000812 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +0000813 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
814 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000815}
816
817Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000818 const TargetData *TD, const DominatorTree *DT) {
819 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000820}
Chris Lattnere3453782009-11-10 01:08:51 +0000821
822/// SimplifyInstruction - See if we can compute a simplified version of this
823/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +0000824Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
825 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +0000826 Value *Result;
827
Chris Lattnere3453782009-11-10 01:08:51 +0000828 switch (I->getOpcode()) {
829 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000830 Result = ConstantFoldInstruction(I, TD);
831 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000832 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000833 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
834 cast<BinaryOperator>(I)->hasNoSignedWrap(),
835 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
836 TD, DT);
837 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000838 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000839 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
840 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000841 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000842 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
843 break;
Duncan Sands2b749872010-11-17 18:52:15 +0000844 case Instruction::Xor:
845 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
846 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000847 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000848 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
849 I->getOperand(0), I->getOperand(1), TD, DT);
850 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000851 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000852 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
853 I->getOperand(0), I->getOperand(1), TD, DT);
854 break;
Chris Lattner04754262010-04-20 05:32:14 +0000855 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000856 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
857 I->getOperand(2), TD, DT);
858 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000859 case Instruction::GetElementPtr: {
860 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +0000861 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
862 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000863 }
Duncan Sandscd6636c2010-11-14 13:30:18 +0000864 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000865 Result = SimplifyPHINode(cast<PHINode>(I), DT);
866 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000867 }
Duncan Sandsd261dc62010-11-17 08:35:29 +0000868
869 /// If called on unreachable code, the above logic may report that the
870 /// instruction simplified to itself. Make life easier for users by
871 /// detecting that case here, returning null if it occurs.
872 return Result == I ? 0 : Result;
Chris Lattnere3453782009-11-10 01:08:51 +0000873}
874
Chris Lattner40d8c282009-11-10 22:26:15 +0000875/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
876/// delete the From instruction. In addition to a basic RAUW, this does a
877/// recursive simplification of the newly formed instructions. This catches
878/// things where one simplification exposes other opportunities. This only
879/// simplifies and deletes scalar operations, it does not change the CFG.
880///
881void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +0000882 const TargetData *TD,
883 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +0000884 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000885
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000886 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
887 // we can know if it gets deleted out from under us or replaced in a
888 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +0000889 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000890 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000891
Chris Lattner40d8c282009-11-10 22:26:15 +0000892 while (!From->use_empty()) {
893 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000894 Use &TheUse = From->use_begin().getUse();
895 Instruction *User = cast<Instruction>(TheUse.getUser());
896 TheUse = To;
897
898 // Check to see if the instruction can be folded due to the operand
899 // replacement. For example changing (or X, Y) into (or X, -1) can replace
900 // the 'or' with -1.
901 Value *SimplifiedVal;
902 {
903 // Sanity check to make sure 'User' doesn't dangle across
904 // SimplifyInstruction.
905 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +0000906
Duncan Sandseff05812010-11-14 18:36:10 +0000907 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000908 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +0000909 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000910
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000911 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +0000912 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000913 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
914 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +0000915
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000916 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +0000917
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000918 // If the recursive simplification ended up revisiting and deleting
919 // 'From' then we're done.
920 if (From == 0)
921 return;
Chris Lattner40d8c282009-11-10 22:26:15 +0000922 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000923
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000924 // If 'From' has value handles referring to it, do a real RAUW to update them.
925 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000926
Chris Lattner40d8c282009-11-10 22:26:15 +0000927 From->eraseFromParent();
928}