blob: f4636553ca2b5a8133c6162b4f044c72248d8b2e [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
Duncan Sandsee9a2e32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000022#include "llvm/Analysis/Dominators.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000023#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000024#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000025#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000026using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000027using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000028
Duncan Sands18450092010-11-16 12:16:38 +000029#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000030
31static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000032 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000033static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000034 const DominatorTree *, unsigned);
35
36/// ValueDominatesPHI - Does the given value dominate the specified phi node?
37static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
38 Instruction *I = dyn_cast<Instruction>(V);
39 if (!I)
40 // Arguments and constants dominate all instructions.
41 return true;
42
43 // If we have a DominatorTree then do a precise test.
44 if (DT)
45 return DT->dominates(I, P);
46
47 // Otherwise, if the instruction is in the entry block, and is not an invoke,
48 // then it obviously dominates all phi nodes.
49 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
50 !isa<InvokeInst>(I))
51 return true;
52
53 return false;
54}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000055
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000056/// ThreadBinOpOverSelect - In the case of a binary operation with a select
57/// instruction as an operand, try to simplify the binop by seeing whether
58/// evaluating it on both branches of the select results in the same value.
59/// Returns the common value if so, otherwise returns null.
60static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +000061 const TargetData *TD,
62 const DominatorTree *DT,
63 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000064 SelectInst *SI;
65 if (isa<SelectInst>(LHS)) {
66 SI = cast<SelectInst>(LHS);
67 } else {
68 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
69 SI = cast<SelectInst>(RHS);
70 }
71
72 // Evaluate the BinOp on the true and false branches of the select.
73 Value *TV;
74 Value *FV;
75 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +000076 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
77 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000078 } else {
Duncan Sands18450092010-11-16 12:16:38 +000079 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
80 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +000081 }
82
83 // If they simplified to the same value, then return the common value.
84 // If they both failed to simplify then return null.
85 if (TV == FV)
86 return TV;
87
88 // If one branch simplified to undef, return the other one.
89 if (TV && isa<UndefValue>(TV))
90 return FV;
91 if (FV && isa<UndefValue>(FV))
92 return TV;
93
94 // If applying the operation did not change the true and false select values,
95 // then the result of the binop is the select itself.
96 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
97 return SI;
98
99 // If one branch simplified and the other did not, and the simplified
100 // value is equal to the unsimplified one, return the simplified value.
101 // For example, select (cond, X, X & Z) & Z -> X & Z.
102 if ((FV && !TV) || (TV && !FV)) {
103 // Check that the simplified value has the form "X op Y" where "op" is the
104 // same as the original operation.
105 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
106 if (Simplified && Simplified->getOpcode() == Opcode) {
107 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
108 // We already know that "op" is the same as for the simplified value. See
109 // if the operands match too. If so, return the simplified value.
110 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
111 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
112 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
113 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
114 Simplified->getOperand(1) == UnsimplifiedRHS)
115 return Simplified;
116 if (Simplified->isCommutative() &&
117 Simplified->getOperand(1) == UnsimplifiedLHS &&
118 Simplified->getOperand(0) == UnsimplifiedRHS)
119 return Simplified;
120 }
121 }
122
123 return 0;
124}
125
126/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
127/// try to simplify the comparison by seeing whether both branches of the select
128/// result in the same value. Returns the common value if so, otherwise returns
129/// null.
130static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000131 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000132 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000133 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000134 // Make sure the select is on the LHS.
135 if (!isa<SelectInst>(LHS)) {
136 std::swap(LHS, RHS);
137 Pred = CmpInst::getSwappedPredicate(Pred);
138 }
139 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
140 SelectInst *SI = cast<SelectInst>(LHS);
141
142 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
143 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000144 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000145 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000146 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000147 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000148 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000149 // It does! If they simplified to the same value, then use it as the
150 // result of the original comparison.
151 if (TCmp == FCmp)
152 return TCmp;
153 return 0;
154}
155
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000156/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
157/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
158/// it on the incoming phi values yields the same result for every value. If so
159/// returns the common value, otherwise returns null.
160static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000161 const TargetData *TD, const DominatorTree *DT,
162 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000163 PHINode *PI;
164 if (isa<PHINode>(LHS)) {
165 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000166 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
167 if (!ValueDominatesPHI(RHS, PI, DT))
168 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000169 } else {
170 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
171 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000172 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
173 if (!ValueDominatesPHI(LHS, PI, DT))
174 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000175 }
176
177 // Evaluate the BinOp on the incoming phi values.
178 Value *CommonValue = 0;
179 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000180 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000181 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000182 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000183 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000184 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
185 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000186 // If the operation failed to simplify, or simplified to a different value
187 // to previously, then give up.
188 if (!V || (CommonValue && V != CommonValue))
189 return 0;
190 CommonValue = V;
191 }
192
193 return CommonValue;
194}
195
196/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
197/// try to simplify the comparison by seeing whether comparing with all of the
198/// incoming phi values yields the same result every time. If so returns the
199/// common result, otherwise returns null.
200static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000201 const TargetData *TD, const DominatorTree *DT,
202 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000203 // Make sure the phi is on the LHS.
204 if (!isa<PHINode>(LHS)) {
205 std::swap(LHS, RHS);
206 Pred = CmpInst::getSwappedPredicate(Pred);
207 }
208 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
209 PHINode *PI = cast<PHINode>(LHS);
210
Duncan Sands18450092010-11-16 12:16:38 +0000211 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
212 if (!ValueDominatesPHI(RHS, PI, DT))
213 return 0;
214
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000215 // Evaluate the BinOp on the incoming phi values.
216 Value *CommonValue = 0;
217 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000218 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000219 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000220 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000221 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000222 // If the operation failed to simplify, or simplified to a different value
223 // to previously, then give up.
224 if (!V || (CommonValue && V != CommonValue))
225 return 0;
226 CommonValue = V;
227 }
228
229 return CommonValue;
230}
231
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000232/// SimplifyAddInst - Given operands for an Add, see if we can
233/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000234static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
235 const TargetData *TD, const DominatorTree *DT,
236 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000237 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
238 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
239 Constant *Ops[] = { CLHS, CRHS };
240 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
241 Ops, 2, TD);
242 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000243
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000244 // Canonicalize the constant to the RHS.
245 std::swap(Op0, Op1);
246 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000247
Duncan Sandsfea3b212010-12-15 14:07:39 +0000248 // X + undef -> undef
249 if (isa<UndefValue>(Op1))
250 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000251
Duncan Sandsfea3b212010-12-15 14:07:39 +0000252 // X + 0 -> X
253 if (match(Op1, m_Zero()))
254 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000255
Duncan Sandsfea3b212010-12-15 14:07:39 +0000256 // X + (Y - X) -> Y
257 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000258 // Eg: X + -X -> 0
Duncan Sandsfea3b212010-12-15 14:07:39 +0000259 Value *Y = 0;
260 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
261 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
262 return Y;
263
264 // X + ~X -> -1 since ~X = -X-1
265 if (match(Op0, m_Not(m_Specific(Op1))) ||
266 match(Op1, m_Not(m_Specific(Op0))))
267 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000268
269 // Threading Add over selects and phi nodes is pointless, so don't bother.
270 // Threading over the select in "A + select(cond, B, C)" means evaluating
271 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
272 // only if B and C are equal. If B and C are equal then (since we assume
273 // that operands have already been simplified) "select(cond, B, C)" should
274 // have been simplified to the common value of B and C already. Analysing
275 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
276 // for threading over phi nodes.
277
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000278 return 0;
279}
280
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000281Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
282 const TargetData *TD, const DominatorTree *DT) {
283 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
284}
285
Duncan Sandsfea3b212010-12-15 14:07:39 +0000286/// SimplifySubInst - Given operands for a Sub, see if we can
287/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000288static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
289 const TargetData *TD, const DominatorTree *,
290 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000291 if (Constant *CLHS = dyn_cast<Constant>(Op0))
292 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
293 Constant *Ops[] = { CLHS, CRHS };
294 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
295 Ops, 2, TD);
296 }
297
298 // X - undef -> undef
299 // undef - X -> undef
300 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
301 return UndefValue::get(Op0->getType());
302
303 // X - 0 -> X
304 if (match(Op1, m_Zero()))
305 return Op0;
306
307 // X - X -> 0
308 if (Op0 == Op1)
309 return Constant::getNullValue(Op0->getType());
310
311 // (X + Y) - Y -> X
312 // (Y + X) - Y -> X
313 Value *X = 0;
314 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
315 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
316 return X;
317
318 // Threading Sub over selects and phi nodes is pointless, so don't bother.
319 // Threading over the select in "A - select(cond, B, C)" means evaluating
320 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
321 // only if B and C are equal. If B and C are equal then (since we assume
322 // that operands have already been simplified) "select(cond, B, C)" should
323 // have been simplified to the common value of B and C already. Analysing
324 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
325 // for threading over phi nodes.
326
327 return 0;
328}
329
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000330Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
331 const TargetData *TD, const DominatorTree *DT) {
332 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
333}
334
Chris Lattnerd06094f2009-11-10 00:55:12 +0000335/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000336/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000337static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000338 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000339 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
340 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
341 Constant *Ops[] = { CLHS, CRHS };
342 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
343 Ops, 2, TD);
344 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000345
Chris Lattnerd06094f2009-11-10 00:55:12 +0000346 // Canonicalize the constant to the RHS.
347 std::swap(Op0, Op1);
348 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000349
Chris Lattnerd06094f2009-11-10 00:55:12 +0000350 // X & undef -> 0
351 if (isa<UndefValue>(Op1))
352 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000353
Chris Lattnerd06094f2009-11-10 00:55:12 +0000354 // X & X = X
355 if (Op0 == Op1)
356 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000357
Duncan Sands2b749872010-11-17 18:52:15 +0000358 // X & 0 = 0
359 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000360 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000361
Duncan Sands2b749872010-11-17 18:52:15 +0000362 // X & -1 = X
363 if (match(Op1, m_AllOnes()))
364 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000365
Chris Lattnerd06094f2009-11-10 00:55:12 +0000366 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000367 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000368 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
369 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000370 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000371
Chris Lattnerd06094f2009-11-10 00:55:12 +0000372 // (A | ?) & A = A
373 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
374 (A == Op1 || B == Op1))
375 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000376
Chris Lattnerd06094f2009-11-10 00:55:12 +0000377 // A & (A | ?) = A
378 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
379 (A == Op0 || B == Op0))
380 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000381
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000382 // (A & B) & A -> A & B
383 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
384 (A == Op1 || B == Op1))
385 return Op0;
386
387 // A & (A & B) -> A & B
388 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
389 (A == Op0 || B == Op0))
390 return Op1;
391
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000392 // If the operation is with the result of a select instruction, check whether
393 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000394 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000395 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000396 MaxRecurse-1))
397 return V;
398
399 // If the operation is with the result of a phi instruction, check whether
400 // operating on all incoming values of the phi always yields the same value.
401 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000402 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000403 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000404 return V;
405
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000406 return 0;
407}
408
Duncan Sands18450092010-11-16 12:16:38 +0000409Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
410 const DominatorTree *DT) {
411 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000412}
413
Chris Lattnerd06094f2009-11-10 00:55:12 +0000414/// SimplifyOrInst - Given operands for an Or, see if we can
415/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000416static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000417 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000418 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
419 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
420 Constant *Ops[] = { CLHS, CRHS };
421 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
422 Ops, 2, TD);
423 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000424
Chris Lattnerd06094f2009-11-10 00:55:12 +0000425 // Canonicalize the constant to the RHS.
426 std::swap(Op0, Op1);
427 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000428
Chris Lattnerd06094f2009-11-10 00:55:12 +0000429 // X | undef -> -1
430 if (isa<UndefValue>(Op1))
431 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000432
Chris Lattnerd06094f2009-11-10 00:55:12 +0000433 // X | X = X
434 if (Op0 == Op1)
435 return Op0;
436
Duncan Sands2b749872010-11-17 18:52:15 +0000437 // X | 0 = X
438 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000439 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000440
Duncan Sands2b749872010-11-17 18:52:15 +0000441 // X | -1 = -1
442 if (match(Op1, m_AllOnes()))
443 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000444
Chris Lattnerd06094f2009-11-10 00:55:12 +0000445 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000446 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000447 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
448 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000449 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000450
Chris Lattnerd06094f2009-11-10 00:55:12 +0000451 // (A & ?) | A = A
452 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
453 (A == Op1 || B == Op1))
454 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000455
Chris Lattnerd06094f2009-11-10 00:55:12 +0000456 // A | (A & ?) = A
457 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
458 (A == Op0 || B == Op0))
459 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000460
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000461 // (A | B) | A -> A | B
462 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
463 (A == Op1 || B == Op1))
464 return Op0;
465
466 // A | (A | B) -> A | B
467 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
468 (A == Op0 || B == Op0))
469 return Op1;
470
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000471 // If the operation is with the result of a select instruction, check whether
472 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000473 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000474 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000475 MaxRecurse-1))
476 return V;
477
478 // If the operation is with the result of a phi instruction, check whether
479 // operating on all incoming values of the phi always yields the same value.
480 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000481 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000482 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000483 return V;
484
Chris Lattnerd06094f2009-11-10 00:55:12 +0000485 return 0;
486}
487
Duncan Sands18450092010-11-16 12:16:38 +0000488Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
489 const DominatorTree *DT) {
490 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000491}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000492
Duncan Sands2b749872010-11-17 18:52:15 +0000493/// SimplifyXorInst - Given operands for a Xor, see if we can
494/// fold the result. If not, this returns null.
495static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
496 const DominatorTree *DT, unsigned MaxRecurse) {
497 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
498 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
499 Constant *Ops[] = { CLHS, CRHS };
500 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
501 Ops, 2, TD);
502 }
503
504 // Canonicalize the constant to the RHS.
505 std::swap(Op0, Op1);
506 }
507
508 // A ^ undef -> undef
509 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000510 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000511
512 // A ^ 0 = A
513 if (match(Op1, m_Zero()))
514 return Op0;
515
516 // A ^ A = 0
517 if (Op0 == Op1)
518 return Constant::getNullValue(Op0->getType());
519
520 // A ^ ~A = ~A ^ A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000521 Value *A = 0, *B = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000522 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
523 (match(Op1, m_Not(m_Value(A))) && A == Op0))
524 return Constant::getAllOnesValue(Op0->getType());
525
526 // (A ^ B) ^ A = B
527 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
528 (A == Op1 || B == Op1))
529 return A == Op1 ? B : A;
530
531 // A ^ (A ^ B) = B
532 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
533 (A == Op0 || B == Op0))
534 return A == Op0 ? B : A;
535
Duncan Sands87689cf2010-11-19 09:20:39 +0000536 // Threading Xor over selects and phi nodes is pointless, so don't bother.
537 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
538 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
539 // only if B and C are equal. If B and C are equal then (since we assume
540 // that operands have already been simplified) "select(cond, B, C)" should
541 // have been simplified to the common value of B and C already. Analysing
542 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
543 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000544
545 return 0;
546}
547
548Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
549 const DominatorTree *DT) {
550 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
551}
552
Chris Lattner210c5d42009-11-09 23:55:12 +0000553static const Type *GetCompareTy(Value *Op) {
554 return CmpInst::makeCmpResultType(Op->getType());
555}
556
Chris Lattner9dbb4292009-11-09 23:28:39 +0000557/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
558/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000559static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000560 const TargetData *TD, const DominatorTree *DT,
561 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000562 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000563 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000564
Chris Lattnerd06094f2009-11-10 00:55:12 +0000565 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000566 if (Constant *CRHS = dyn_cast<Constant>(RHS))
567 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000568
569 // If we have a constant, make sure it is on the RHS.
570 std::swap(LHS, RHS);
571 Pred = CmpInst::getSwappedPredicate(Pred);
572 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000573
Chris Lattner210c5d42009-11-09 23:55:12 +0000574 // ITy - This is the return type of the compare we're considering.
575 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000576
Chris Lattner210c5d42009-11-09 23:55:12 +0000577 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000578 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
579 // because X could be 0.
580 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000581 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000582
Chris Lattner210c5d42009-11-09 23:55:12 +0000583 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
584 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000585 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000586 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000587 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000588 isa<ConstantPointerNull>(RHS)))
589 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000590
Chris Lattner210c5d42009-11-09 23:55:12 +0000591 // See if we are doing a comparison with a constant.
592 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
593 // If we have an icmp le or icmp ge instruction, turn it into the
594 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
595 // them being folded in the code below.
596 switch (Pred) {
597 default: break;
598 case ICmpInst::ICMP_ULE:
599 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
600 return ConstantInt::getTrue(CI->getContext());
601 break;
602 case ICmpInst::ICMP_SLE:
603 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
604 return ConstantInt::getTrue(CI->getContext());
605 break;
606 case ICmpInst::ICMP_UGE:
607 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
608 return ConstantInt::getTrue(CI->getContext());
609 break;
610 case ICmpInst::ICMP_SGE:
611 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
612 return ConstantInt::getTrue(CI->getContext());
613 break;
614 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000615 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000616
617 // If the comparison is with the result of a select instruction, check whether
618 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000619 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000620 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000621 return V;
622
623 // If the comparison is with the result of a phi instruction, check whether
624 // doing the compare with each incoming phi value yields a common result.
625 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000626 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000627 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000628
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000629 return 0;
630}
631
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000632Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000633 const TargetData *TD, const DominatorTree *DT) {
634 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000635}
636
Chris Lattner9dbb4292009-11-09 23:28:39 +0000637/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
638/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000639static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000640 const TargetData *TD, const DominatorTree *DT,
641 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000642 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
643 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
644
Chris Lattnerd06094f2009-11-10 00:55:12 +0000645 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000646 if (Constant *CRHS = dyn_cast<Constant>(RHS))
647 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000648
Chris Lattnerd06094f2009-11-10 00:55:12 +0000649 // If we have a constant, make sure it is on the RHS.
650 std::swap(LHS, RHS);
651 Pred = CmpInst::getSwappedPredicate(Pred);
652 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000653
Chris Lattner210c5d42009-11-09 23:55:12 +0000654 // Fold trivial predicates.
655 if (Pred == FCmpInst::FCMP_FALSE)
656 return ConstantInt::get(GetCompareTy(LHS), 0);
657 if (Pred == FCmpInst::FCMP_TRUE)
658 return ConstantInt::get(GetCompareTy(LHS), 1);
659
Chris Lattner210c5d42009-11-09 23:55:12 +0000660 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
661 return UndefValue::get(GetCompareTy(LHS));
662
663 // fcmp x,x -> true/false. Not all compares are foldable.
664 if (LHS == RHS) {
665 if (CmpInst::isTrueWhenEqual(Pred))
666 return ConstantInt::get(GetCompareTy(LHS), 1);
667 if (CmpInst::isFalseWhenEqual(Pred))
668 return ConstantInt::get(GetCompareTy(LHS), 0);
669 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000670
Chris Lattner210c5d42009-11-09 23:55:12 +0000671 // Handle fcmp with constant RHS
672 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
673 // If the constant is a nan, see if we can fold the comparison based on it.
674 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
675 if (CFP->getValueAPF().isNaN()) {
676 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
677 return ConstantInt::getFalse(CFP->getContext());
678 assert(FCmpInst::isUnordered(Pred) &&
679 "Comparison must be either ordered or unordered!");
680 // True if unordered.
681 return ConstantInt::getTrue(CFP->getContext());
682 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000683 // Check whether the constant is an infinity.
684 if (CFP->getValueAPF().isInfinity()) {
685 if (CFP->getValueAPF().isNegative()) {
686 switch (Pred) {
687 case FCmpInst::FCMP_OLT:
688 // No value is ordered and less than negative infinity.
689 return ConstantInt::getFalse(CFP->getContext());
690 case FCmpInst::FCMP_UGE:
691 // All values are unordered with or at least negative infinity.
692 return ConstantInt::getTrue(CFP->getContext());
693 default:
694 break;
695 }
696 } else {
697 switch (Pred) {
698 case FCmpInst::FCMP_OGT:
699 // No value is ordered and greater than infinity.
700 return ConstantInt::getFalse(CFP->getContext());
701 case FCmpInst::FCMP_ULE:
702 // All values are unordered with and at most infinity.
703 return ConstantInt::getTrue(CFP->getContext());
704 default:
705 break;
706 }
707 }
708 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000709 }
710 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000711
Duncan Sands92826de2010-11-07 16:46:25 +0000712 // If the comparison is with the result of a select instruction, check whether
713 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000714 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000715 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000716 return V;
717
718 // If the comparison is with the result of a phi instruction, check whether
719 // doing the compare with each incoming phi value yields a common result.
720 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000721 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000722 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000723
Chris Lattner9dbb4292009-11-09 23:28:39 +0000724 return 0;
725}
726
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000727Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000728 const TargetData *TD, const DominatorTree *DT) {
729 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000730}
731
Chris Lattner04754262010-04-20 05:32:14 +0000732/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
733/// the result. If not, this returns null.
734Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000735 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000736 // select true, X, Y -> X
737 // select false, X, Y -> Y
738 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
739 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000740
Chris Lattner04754262010-04-20 05:32:14 +0000741 // select C, X, X -> X
742 if (TrueVal == FalseVal)
743 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000744
Chris Lattner04754262010-04-20 05:32:14 +0000745 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
746 return FalseVal;
747 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
748 return TrueVal;
749 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
750 if (isa<Constant>(TrueVal))
751 return TrueVal;
752 return FalseVal;
753 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000754
Chris Lattner04754262010-04-20 05:32:14 +0000755 return 0;
756}
757
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000758/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
759/// fold the result. If not, this returns null.
760Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +0000761 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000762 // The type of the GEP pointer operand.
763 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
764
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000765 // getelementptr P -> P.
766 if (NumOps == 1)
767 return Ops[0];
768
Duncan Sands85bbff62010-11-22 13:42:49 +0000769 if (isa<UndefValue>(Ops[0])) {
770 // Compute the (pointer) type returned by the GEP instruction.
771 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
772 NumOps-1);
773 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
774 return UndefValue::get(GEPTy);
775 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000776
Duncan Sandse60d79f2010-11-21 13:53:09 +0000777 if (NumOps == 2) {
778 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000779 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
780 if (C->isZero())
781 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +0000782 // getelementptr P, N -> P if P points to a type of zero size.
783 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000784 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +0000785 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +0000786 return Ops[0];
787 }
788 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000789
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000790 // Check to see if this is constant foldable.
791 for (unsigned i = 0; i != NumOps; ++i)
792 if (!isa<Constant>(Ops[i]))
793 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000794
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000795 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
796 (Constant *const*)Ops+1, NumOps-1);
797}
798
Duncan Sandsff103412010-11-17 04:30:22 +0000799/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
800static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
801 // If all of the PHI's incoming values are the same then replace the PHI node
802 // with the common value.
803 Value *CommonValue = 0;
804 bool HasUndefInput = false;
805 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
806 Value *Incoming = PN->getIncomingValue(i);
807 // If the incoming value is the phi node itself, it can safely be skipped.
808 if (Incoming == PN) continue;
809 if (isa<UndefValue>(Incoming)) {
810 // Remember that we saw an undef value, but otherwise ignore them.
811 HasUndefInput = true;
812 continue;
813 }
814 if (CommonValue && Incoming != CommonValue)
815 return 0; // Not the same, bail out.
816 CommonValue = Incoming;
817 }
818
819 // If CommonValue is null then all of the incoming values were either undef or
820 // equal to the phi node itself.
821 if (!CommonValue)
822 return UndefValue::get(PN->getType());
823
824 // If we have a PHI node like phi(X, undef, X), where X is defined by some
825 // instruction, we cannot return X as the result of the PHI node unless it
826 // dominates the PHI block.
827 if (HasUndefInput)
828 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
829
830 return CommonValue;
831}
832
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000833
Chris Lattnerd06094f2009-11-10 00:55:12 +0000834//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000835
Chris Lattnerd06094f2009-11-10 00:55:12 +0000836/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
837/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000838static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000839 const TargetData *TD, const DominatorTree *DT,
840 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000841 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +0000842 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
843 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000844 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
845 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
846 /* isNUW */ false, TD, DT,
847 MaxRecurse);
848 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
849 /* isNUW */ false, TD, DT,
850 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000851 default:
852 if (Constant *CLHS = dyn_cast<Constant>(LHS))
853 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
854 Constant *COps[] = {CLHS, CRHS};
855 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
856 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000857
858 // If the operation is with the result of a select instruction, check whether
859 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000860 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000861 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
862 MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000863 return V;
864
865 // If the operation is with the result of a phi instruction, check whether
866 // operating on all incoming values of the phi always yields the same value.
867 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000868 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000869 return V;
870
Chris Lattnerd06094f2009-11-10 00:55:12 +0000871 return 0;
872 }
873}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000874
Duncan Sands12a86f52010-11-14 11:23:23 +0000875Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000876 const TargetData *TD, const DominatorTree *DT) {
877 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +0000878}
879
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000880/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
881/// fold the result.
882static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000883 const TargetData *TD, const DominatorTree *DT,
884 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000885 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +0000886 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
887 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000888}
889
890Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000891 const TargetData *TD, const DominatorTree *DT) {
892 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000893}
Chris Lattnere3453782009-11-10 01:08:51 +0000894
895/// SimplifyInstruction - See if we can compute a simplified version of this
896/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +0000897Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
898 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +0000899 Value *Result;
900
Chris Lattnere3453782009-11-10 01:08:51 +0000901 switch (I->getOpcode()) {
902 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000903 Result = ConstantFoldInstruction(I, TD);
904 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000905 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000906 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
907 cast<BinaryOperator>(I)->hasNoSignedWrap(),
908 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
909 TD, DT);
910 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +0000911 case Instruction::Sub:
912 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
913 cast<BinaryOperator>(I)->hasNoSignedWrap(),
914 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
915 TD, DT);
916 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000917 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000918 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
919 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000920 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000921 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
922 break;
Duncan Sands2b749872010-11-17 18:52:15 +0000923 case Instruction::Xor:
924 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
925 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000926 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000927 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
928 I->getOperand(0), I->getOperand(1), TD, DT);
929 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000930 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000931 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
932 I->getOperand(0), I->getOperand(1), TD, DT);
933 break;
Chris Lattner04754262010-04-20 05:32:14 +0000934 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000935 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
936 I->getOperand(2), TD, DT);
937 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000938 case Instruction::GetElementPtr: {
939 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +0000940 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
941 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000942 }
Duncan Sandscd6636c2010-11-14 13:30:18 +0000943 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000944 Result = SimplifyPHINode(cast<PHINode>(I), DT);
945 break;
Chris Lattnere3453782009-11-10 01:08:51 +0000946 }
Duncan Sandsd261dc62010-11-17 08:35:29 +0000947
948 /// If called on unreachable code, the above logic may report that the
949 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000950 /// detecting that case here, returning a safe value instead.
951 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +0000952}
953
Chris Lattner40d8c282009-11-10 22:26:15 +0000954/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
955/// delete the From instruction. In addition to a basic RAUW, this does a
956/// recursive simplification of the newly formed instructions. This catches
957/// things where one simplification exposes other opportunities. This only
958/// simplifies and deletes scalar operations, it does not change the CFG.
959///
960void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +0000961 const TargetData *TD,
962 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +0000963 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000964
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000965 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
966 // we can know if it gets deleted out from under us or replaced in a
967 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +0000968 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000969 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +0000970
Chris Lattner40d8c282009-11-10 22:26:15 +0000971 while (!From->use_empty()) {
972 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000973 Use &TheUse = From->use_begin().getUse();
974 Instruction *User = cast<Instruction>(TheUse.getUser());
975 TheUse = To;
976
977 // Check to see if the instruction can be folded due to the operand
978 // replacement. For example changing (or X, Y) into (or X, -1) can replace
979 // the 'or' with -1.
980 Value *SimplifiedVal;
981 {
982 // Sanity check to make sure 'User' doesn't dangle across
983 // SimplifyInstruction.
984 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +0000985
Duncan Sandseff05812010-11-14 18:36:10 +0000986 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000987 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +0000988 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000989
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000990 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +0000991 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000992 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
993 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +0000994
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000995 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +0000996
Chris Lattnerd2bfe542010-07-15 06:36:08 +0000997 // If the recursive simplification ended up revisiting and deleting
998 // 'From' then we're done.
999 if (From == 0)
1000 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001001 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001002
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001003 // If 'From' has value handles referring to it, do a real RAUW to update them.
1004 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001005
Chris Lattner40d8c282009-11-10 22:26:15 +00001006 From->eraseFromParent();
1007}