blob: 675a109f0cb803a86efea43415643749f2178a10 [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 Sands566edb02010-12-21 08:49:00 +000056// SimplifyAssociativeBinOp - Generic simplifications for associative binary
57// operations. Returns the simpler value, or null if none was found.
58static Value *SimplifyAssociativeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
59 const TargetData *TD,
60 const DominatorTree *DT,
61 unsigned MaxRecurse) {
62 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
63
64 // Recursion is always used, so bail out at once if we already hit the limit.
65 if (!MaxRecurse--)
66 return 0;
67
68 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
69 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
70
71 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
72 if (Op0 && Op0->getOpcode() == Opcode) {
73 Value *A = Op0->getOperand(0);
74 Value *B = Op0->getOperand(1);
75 Value *C = RHS;
76
77 // Does "B op C" simplify?
78 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
79 // It does! Return "A op V" if it simplifies or is already available.
80 // If V equals B then "A op V" is just the LHS.
81 if (V == B)
82 return LHS;
83 // Otherwise return "A op V" if it simplifies.
84 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse))
85 return W;
86 }
87 }
88
89 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
90 if (Op1 && Op1->getOpcode() == Opcode) {
91 Value *A = LHS;
92 Value *B = Op1->getOperand(0);
93 Value *C = Op1->getOperand(1);
94
95 // Does "A op B" simplify?
96 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
97 // It does! Return "V op C" if it simplifies or is already available.
98 // If V equals B then "V op C" is just the RHS.
99 if (V == B)
100 return RHS;
101 // Otherwise return "V op C" if it simplifies.
102 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse))
103 return W;
104 }
105 }
106
107 // The remaining transforms require commutativity as well as associativity.
108 if (!Instruction::isCommutative(Opcode))
109 return 0;
110
111 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
112 if (Op0 && Op0->getOpcode() == Opcode) {
113 Value *A = Op0->getOperand(0);
114 Value *B = Op0->getOperand(1);
115 Value *C = RHS;
116
117 // Does "C op A" simplify?
118 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
119 // It does! Return "V op B" if it simplifies or is already available.
120 // If V equals A then "V op B" is just the LHS.
121 if (V == A)
122 return LHS;
123 // Otherwise return "V op B" if it simplifies.
124 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse))
125 return W;
126 }
127 }
128
129 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
130 if (Op1 && Op1->getOpcode() == Opcode) {
131 Value *A = LHS;
132 Value *B = Op1->getOperand(0);
133 Value *C = Op1->getOperand(1);
134
135 // Does "C op A" simplify?
136 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
137 // It does! Return "B op V" if it simplifies or is already available.
138 // If V equals C then "B op V" is just the RHS.
139 if (V == C)
140 return RHS;
141 // Otherwise return "B op V" if it simplifies.
142 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse))
143 return W;
144 }
145 }
146
147 return 0;
148}
149
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000150/// ThreadBinOpOverSelect - In the case of a binary operation with a select
151/// instruction as an operand, try to simplify the binop by seeing whether
152/// evaluating it on both branches of the select results in the same value.
153/// Returns the common value if so, otherwise returns null.
154static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000155 const TargetData *TD,
156 const DominatorTree *DT,
157 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000158 // Recursion is always used, so bail out at once if we already hit the limit.
159 if (!MaxRecurse--)
160 return 0;
161
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000162 SelectInst *SI;
163 if (isa<SelectInst>(LHS)) {
164 SI = cast<SelectInst>(LHS);
165 } else {
166 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
167 SI = cast<SelectInst>(RHS);
168 }
169
170 // Evaluate the BinOp on the true and false branches of the select.
171 Value *TV;
172 Value *FV;
173 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000174 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
175 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000176 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000177 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
178 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000179 }
180
181 // If they simplified to the same value, then return the common value.
182 // If they both failed to simplify then return null.
183 if (TV == FV)
184 return TV;
185
186 // If one branch simplified to undef, return the other one.
187 if (TV && isa<UndefValue>(TV))
188 return FV;
189 if (FV && isa<UndefValue>(FV))
190 return TV;
191
192 // If applying the operation did not change the true and false select values,
193 // then the result of the binop is the select itself.
194 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
195 return SI;
196
197 // If one branch simplified and the other did not, and the simplified
198 // value is equal to the unsimplified one, return the simplified value.
199 // For example, select (cond, X, X & Z) & Z -> X & Z.
200 if ((FV && !TV) || (TV && !FV)) {
201 // Check that the simplified value has the form "X op Y" where "op" is the
202 // same as the original operation.
203 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
204 if (Simplified && Simplified->getOpcode() == Opcode) {
205 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
206 // We already know that "op" is the same as for the simplified value. See
207 // if the operands match too. If so, return the simplified value.
208 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
209 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
210 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
211 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
212 Simplified->getOperand(1) == UnsimplifiedRHS)
213 return Simplified;
214 if (Simplified->isCommutative() &&
215 Simplified->getOperand(1) == UnsimplifiedLHS &&
216 Simplified->getOperand(0) == UnsimplifiedRHS)
217 return Simplified;
218 }
219 }
220
221 return 0;
222}
223
224/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
225/// try to simplify the comparison by seeing whether both branches of the select
226/// result in the same value. Returns the common value if so, otherwise returns
227/// null.
228static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000229 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000230 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000231 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000232 // Recursion is always used, so bail out at once if we already hit the limit.
233 if (!MaxRecurse--)
234 return 0;
235
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000236 // Make sure the select is on the LHS.
237 if (!isa<SelectInst>(LHS)) {
238 std::swap(LHS, RHS);
239 Pred = CmpInst::getSwappedPredicate(Pred);
240 }
241 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
242 SelectInst *SI = cast<SelectInst>(LHS);
243
244 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
245 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000246 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000247 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000248 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000249 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000250 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000251 // It does! If they simplified to the same value, then use it as the
252 // result of the original comparison.
253 if (TCmp == FCmp)
254 return TCmp;
255 return 0;
256}
257
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000258/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
259/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
260/// it on the incoming phi values yields the same result for every value. If so
261/// returns the common value, otherwise returns null.
262static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000263 const TargetData *TD, const DominatorTree *DT,
264 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000265 // Recursion is always used, so bail out at once if we already hit the limit.
266 if (!MaxRecurse--)
267 return 0;
268
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000269 PHINode *PI;
270 if (isa<PHINode>(LHS)) {
271 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000272 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
273 if (!ValueDominatesPHI(RHS, PI, DT))
274 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000275 } else {
276 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
277 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000278 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
279 if (!ValueDominatesPHI(LHS, PI, DT))
280 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000281 }
282
283 // Evaluate the BinOp on the incoming phi values.
284 Value *CommonValue = 0;
285 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000286 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000287 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000288 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000289 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000290 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
291 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000292 // If the operation failed to simplify, or simplified to a different value
293 // to previously, then give up.
294 if (!V || (CommonValue && V != CommonValue))
295 return 0;
296 CommonValue = V;
297 }
298
299 return CommonValue;
300}
301
302/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
303/// try to simplify the comparison by seeing whether comparing with all of the
304/// incoming phi values yields the same result every time. If so returns the
305/// common result, otherwise returns null.
306static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000307 const TargetData *TD, const DominatorTree *DT,
308 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000309 // Recursion is always used, so bail out at once if we already hit the limit.
310 if (!MaxRecurse--)
311 return 0;
312
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000313 // Make sure the phi is on the LHS.
314 if (!isa<PHINode>(LHS)) {
315 std::swap(LHS, RHS);
316 Pred = CmpInst::getSwappedPredicate(Pred);
317 }
318 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
319 PHINode *PI = cast<PHINode>(LHS);
320
Duncan Sands18450092010-11-16 12:16:38 +0000321 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
322 if (!ValueDominatesPHI(RHS, PI, DT))
323 return 0;
324
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000325 // Evaluate the BinOp on the incoming phi values.
326 Value *CommonValue = 0;
327 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000328 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000329 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000330 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000331 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000332 // If the operation failed to simplify, or simplified to a different value
333 // to previously, then give up.
334 if (!V || (CommonValue && V != CommonValue))
335 return 0;
336 CommonValue = V;
337 }
338
339 return CommonValue;
340}
341
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000342/// SimplifyAddInst - Given operands for an Add, see if we can
343/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000344static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
345 const TargetData *TD, const DominatorTree *DT,
346 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000347 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
348 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
349 Constant *Ops[] = { CLHS, CRHS };
350 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
351 Ops, 2, TD);
352 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000353
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000354 // Canonicalize the constant to the RHS.
355 std::swap(Op0, Op1);
356 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000357
Duncan Sandsfea3b212010-12-15 14:07:39 +0000358 // X + undef -> undef
359 if (isa<UndefValue>(Op1))
360 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000361
Duncan Sandsfea3b212010-12-15 14:07:39 +0000362 // X + 0 -> X
363 if (match(Op1, m_Zero()))
364 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000365
Duncan Sandsfea3b212010-12-15 14:07:39 +0000366 // X + (Y - X) -> Y
367 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000368 // Eg: X + -X -> 0
Duncan Sandsfea3b212010-12-15 14:07:39 +0000369 Value *Y = 0;
370 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
371 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
372 return Y;
373
374 // X + ~X -> -1 since ~X = -X-1
375 if (match(Op0, m_Not(m_Specific(Op1))) ||
376 match(Op1, m_Not(m_Specific(Op0))))
377 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000378
Duncan Sands566edb02010-12-21 08:49:00 +0000379 // Try some generic simplifications for associative operations.
380 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
381 MaxRecurse))
382 return V;
383
Duncan Sands87689cf2010-11-19 09:20:39 +0000384 // Threading Add over selects and phi nodes is pointless, so don't bother.
385 // Threading over the select in "A + select(cond, B, C)" means evaluating
386 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
387 // only if B and C are equal. If B and C are equal then (since we assume
388 // that operands have already been simplified) "select(cond, B, C)" should
389 // have been simplified to the common value of B and C already. Analysing
390 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
391 // for threading over phi nodes.
392
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000393 return 0;
394}
395
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000396Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
397 const TargetData *TD, const DominatorTree *DT) {
398 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
399}
400
Duncan Sandsfea3b212010-12-15 14:07:39 +0000401/// SimplifySubInst - Given operands for a Sub, see if we can
402/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000403static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
404 const TargetData *TD, const DominatorTree *,
405 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000406 if (Constant *CLHS = dyn_cast<Constant>(Op0))
407 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
408 Constant *Ops[] = { CLHS, CRHS };
409 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
410 Ops, 2, TD);
411 }
412
413 // X - undef -> undef
414 // undef - X -> undef
415 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
416 return UndefValue::get(Op0->getType());
417
418 // X - 0 -> X
419 if (match(Op1, m_Zero()))
420 return Op0;
421
422 // X - X -> 0
423 if (Op0 == Op1)
424 return Constant::getNullValue(Op0->getType());
425
426 // (X + Y) - Y -> X
427 // (Y + X) - Y -> X
428 Value *X = 0;
429 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
430 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
431 return X;
432
433 // Threading Sub over selects and phi nodes is pointless, so don't bother.
434 // Threading over the select in "A - select(cond, B, C)" means evaluating
435 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
436 // only if B and C are equal. If B and C are equal then (since we assume
437 // that operands have already been simplified) "select(cond, B, C)" should
438 // have been simplified to the common value of B and C already. Analysing
439 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
440 // for threading over phi nodes.
441
442 return 0;
443}
444
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000445Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
446 const TargetData *TD, const DominatorTree *DT) {
447 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
448}
449
Chris Lattnerd06094f2009-11-10 00:55:12 +0000450/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000451/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000452static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000453 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000454 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
455 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
456 Constant *Ops[] = { CLHS, CRHS };
457 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
458 Ops, 2, TD);
459 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000460
Chris Lattnerd06094f2009-11-10 00:55:12 +0000461 // Canonicalize the constant to the RHS.
462 std::swap(Op0, Op1);
463 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000464
Chris Lattnerd06094f2009-11-10 00:55:12 +0000465 // X & undef -> 0
466 if (isa<UndefValue>(Op1))
467 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000468
Chris Lattnerd06094f2009-11-10 00:55:12 +0000469 // X & X = X
470 if (Op0 == Op1)
471 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000472
Duncan Sands2b749872010-11-17 18:52:15 +0000473 // X & 0 = 0
474 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000475 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000476
Duncan Sands2b749872010-11-17 18:52:15 +0000477 // X & -1 = X
478 if (match(Op1, m_AllOnes()))
479 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000480
Chris Lattnerd06094f2009-11-10 00:55:12 +0000481 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000482 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000483 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
484 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000485 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000486
Chris Lattnerd06094f2009-11-10 00:55:12 +0000487 // (A | ?) & A = A
488 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
489 (A == Op1 || B == Op1))
490 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000491
Chris Lattnerd06094f2009-11-10 00:55:12 +0000492 // A & (A | ?) = A
493 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
494 (A == Op0 || B == Op0))
495 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000496
Duncan Sands566edb02010-12-21 08:49:00 +0000497 // Try some generic simplifications for associative operations.
498 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
499 MaxRecurse))
500 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000501
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000502 // If the operation is with the result of a select instruction, check whether
503 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000504 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000505 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000506 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000507 return V;
508
509 // If the operation is with the result of a phi instruction, check whether
510 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000511 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000512 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000513 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000514 return V;
515
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000516 return 0;
517}
518
Duncan Sands18450092010-11-16 12:16:38 +0000519Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
520 const DominatorTree *DT) {
521 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000522}
523
Chris Lattnerd06094f2009-11-10 00:55:12 +0000524/// SimplifyOrInst - Given operands for an Or, see if we can
525/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000526static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000527 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000528 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
529 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
530 Constant *Ops[] = { CLHS, CRHS };
531 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
532 Ops, 2, TD);
533 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000534
Chris Lattnerd06094f2009-11-10 00:55:12 +0000535 // Canonicalize the constant to the RHS.
536 std::swap(Op0, Op1);
537 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000538
Chris Lattnerd06094f2009-11-10 00:55:12 +0000539 // X | undef -> -1
540 if (isa<UndefValue>(Op1))
541 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000542
Chris Lattnerd06094f2009-11-10 00:55:12 +0000543 // X | X = X
544 if (Op0 == Op1)
545 return Op0;
546
Duncan Sands2b749872010-11-17 18:52:15 +0000547 // X | 0 = X
548 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000549 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000550
Duncan Sands2b749872010-11-17 18:52:15 +0000551 // X | -1 = -1
552 if (match(Op1, m_AllOnes()))
553 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000554
Chris Lattnerd06094f2009-11-10 00:55:12 +0000555 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000556 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000557 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
558 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000559 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000560
Chris Lattnerd06094f2009-11-10 00:55:12 +0000561 // (A & ?) | A = A
562 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
563 (A == Op1 || B == Op1))
564 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000565
Chris Lattnerd06094f2009-11-10 00:55:12 +0000566 // A | (A & ?) = A
567 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
568 (A == Op0 || B == Op0))
569 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000570
Duncan Sands566edb02010-12-21 08:49:00 +0000571 // Try some generic simplifications for associative operations.
572 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
573 MaxRecurse))
574 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000575
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000576 // If the operation is with the result of a select instruction, check whether
577 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000578 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000579 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000580 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000581 return V;
582
583 // If the operation is with the result of a phi instruction, check whether
584 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000585 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000586 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000587 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000588 return V;
589
Chris Lattnerd06094f2009-11-10 00:55:12 +0000590 return 0;
591}
592
Duncan Sands18450092010-11-16 12:16:38 +0000593Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
594 const DominatorTree *DT) {
595 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000596}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000597
Duncan Sands2b749872010-11-17 18:52:15 +0000598/// SimplifyXorInst - Given operands for a Xor, see if we can
599/// fold the result. If not, this returns null.
600static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
601 const DominatorTree *DT, unsigned MaxRecurse) {
602 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
603 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
604 Constant *Ops[] = { CLHS, CRHS };
605 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
606 Ops, 2, TD);
607 }
608
609 // Canonicalize the constant to the RHS.
610 std::swap(Op0, Op1);
611 }
612
613 // A ^ undef -> undef
614 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000615 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000616
617 // A ^ 0 = A
618 if (match(Op1, m_Zero()))
619 return Op0;
620
621 // A ^ A = 0
622 if (Op0 == Op1)
623 return Constant::getNullValue(Op0->getType());
624
625 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +0000626 Value *A = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000627 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
628 (match(Op1, m_Not(m_Value(A))) && A == Op0))
629 return Constant::getAllOnesValue(Op0->getType());
630
Duncan Sands566edb02010-12-21 08:49:00 +0000631 // Try some generic simplifications for associative operations.
632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
633 MaxRecurse))
634 return V;
Duncan Sands2b749872010-11-17 18:52:15 +0000635
Duncan Sands87689cf2010-11-19 09:20:39 +0000636 // Threading Xor over selects and phi nodes is pointless, so don't bother.
637 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
638 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
639 // only if B and C are equal. If B and C are equal then (since we assume
640 // that operands have already been simplified) "select(cond, B, C)" should
641 // have been simplified to the common value of B and C already. Analysing
642 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
643 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000644
645 return 0;
646}
647
648Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
649 const DominatorTree *DT) {
650 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
651}
652
Chris Lattner210c5d42009-11-09 23:55:12 +0000653static const Type *GetCompareTy(Value *Op) {
654 return CmpInst::makeCmpResultType(Op->getType());
655}
656
Chris Lattner9dbb4292009-11-09 23:28:39 +0000657/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
658/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000659static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000660 const TargetData *TD, const DominatorTree *DT,
661 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000662 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000663 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000664
Chris Lattnerd06094f2009-11-10 00:55:12 +0000665 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000666 if (Constant *CRHS = dyn_cast<Constant>(RHS))
667 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000668
669 // If we have a constant, make sure it is on the RHS.
670 std::swap(LHS, RHS);
671 Pred = CmpInst::getSwappedPredicate(Pred);
672 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000673
Chris Lattner210c5d42009-11-09 23:55:12 +0000674 // ITy - This is the return type of the compare we're considering.
675 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000676
Chris Lattner210c5d42009-11-09 23:55:12 +0000677 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000678 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
679 // because X could be 0.
680 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000681 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000682
Chris Lattner210c5d42009-11-09 23:55:12 +0000683 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
684 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000685 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000686 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000687 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000688 isa<ConstantPointerNull>(RHS)))
689 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000690
Chris Lattner210c5d42009-11-09 23:55:12 +0000691 // See if we are doing a comparison with a constant.
692 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
693 // If we have an icmp le or icmp ge instruction, turn it into the
694 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
695 // them being folded in the code below.
696 switch (Pred) {
697 default: break;
698 case ICmpInst::ICMP_ULE:
699 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
700 return ConstantInt::getTrue(CI->getContext());
701 break;
702 case ICmpInst::ICMP_SLE:
703 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
704 return ConstantInt::getTrue(CI->getContext());
705 break;
706 case ICmpInst::ICMP_UGE:
707 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
708 return ConstantInt::getTrue(CI->getContext());
709 break;
710 case ICmpInst::ICMP_SGE:
711 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
712 return ConstantInt::getTrue(CI->getContext());
713 break;
714 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000715 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000716
717 // If the comparison is with the result of a select instruction, check whether
718 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000719 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
720 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000721 return V;
722
723 // If the comparison is with the result of a phi instruction, check whether
724 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +0000725 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
726 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000727 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000728
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000729 return 0;
730}
731
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000732Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000733 const TargetData *TD, const DominatorTree *DT) {
734 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000735}
736
Chris Lattner9dbb4292009-11-09 23:28:39 +0000737/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
738/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000739static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000740 const TargetData *TD, const DominatorTree *DT,
741 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000742 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
743 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
744
Chris Lattnerd06094f2009-11-10 00:55:12 +0000745 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000746 if (Constant *CRHS = dyn_cast<Constant>(RHS))
747 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000748
Chris Lattnerd06094f2009-11-10 00:55:12 +0000749 // If we have a constant, make sure it is on the RHS.
750 std::swap(LHS, RHS);
751 Pred = CmpInst::getSwappedPredicate(Pred);
752 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000753
Chris Lattner210c5d42009-11-09 23:55:12 +0000754 // Fold trivial predicates.
755 if (Pred == FCmpInst::FCMP_FALSE)
756 return ConstantInt::get(GetCompareTy(LHS), 0);
757 if (Pred == FCmpInst::FCMP_TRUE)
758 return ConstantInt::get(GetCompareTy(LHS), 1);
759
Chris Lattner210c5d42009-11-09 23:55:12 +0000760 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
761 return UndefValue::get(GetCompareTy(LHS));
762
763 // fcmp x,x -> true/false. Not all compares are foldable.
764 if (LHS == RHS) {
765 if (CmpInst::isTrueWhenEqual(Pred))
766 return ConstantInt::get(GetCompareTy(LHS), 1);
767 if (CmpInst::isFalseWhenEqual(Pred))
768 return ConstantInt::get(GetCompareTy(LHS), 0);
769 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000770
Chris Lattner210c5d42009-11-09 23:55:12 +0000771 // Handle fcmp with constant RHS
772 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
773 // If the constant is a nan, see if we can fold the comparison based on it.
774 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
775 if (CFP->getValueAPF().isNaN()) {
776 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
777 return ConstantInt::getFalse(CFP->getContext());
778 assert(FCmpInst::isUnordered(Pred) &&
779 "Comparison must be either ordered or unordered!");
780 // True if unordered.
781 return ConstantInt::getTrue(CFP->getContext());
782 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000783 // Check whether the constant is an infinity.
784 if (CFP->getValueAPF().isInfinity()) {
785 if (CFP->getValueAPF().isNegative()) {
786 switch (Pred) {
787 case FCmpInst::FCMP_OLT:
788 // No value is ordered and less than negative infinity.
789 return ConstantInt::getFalse(CFP->getContext());
790 case FCmpInst::FCMP_UGE:
791 // All values are unordered with or at least negative infinity.
792 return ConstantInt::getTrue(CFP->getContext());
793 default:
794 break;
795 }
796 } else {
797 switch (Pred) {
798 case FCmpInst::FCMP_OGT:
799 // No value is ordered and greater than infinity.
800 return ConstantInt::getFalse(CFP->getContext());
801 case FCmpInst::FCMP_ULE:
802 // All values are unordered with and at most infinity.
803 return ConstantInt::getTrue(CFP->getContext());
804 default:
805 break;
806 }
807 }
808 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000809 }
810 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000811
Duncan Sands92826de2010-11-07 16:46:25 +0000812 // If the comparison is with the result of a select instruction, check whether
813 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000814 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
815 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000816 return V;
817
818 // If the comparison is with the result of a phi instruction, check whether
819 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +0000820 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
821 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000822 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000823
Chris Lattner9dbb4292009-11-09 23:28:39 +0000824 return 0;
825}
826
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000827Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000828 const TargetData *TD, const DominatorTree *DT) {
829 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000830}
831
Chris Lattner04754262010-04-20 05:32:14 +0000832/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
833/// the result. If not, this returns null.
834Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000835 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000836 // select true, X, Y -> X
837 // select false, X, Y -> Y
838 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
839 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000840
Chris Lattner04754262010-04-20 05:32:14 +0000841 // select C, X, X -> X
842 if (TrueVal == FalseVal)
843 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000844
Chris Lattner04754262010-04-20 05:32:14 +0000845 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
846 return FalseVal;
847 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
848 return TrueVal;
849 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
850 if (isa<Constant>(TrueVal))
851 return TrueVal;
852 return FalseVal;
853 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000854
Chris Lattner04754262010-04-20 05:32:14 +0000855 return 0;
856}
857
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000858/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
859/// fold the result. If not, this returns null.
860Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +0000861 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000862 // The type of the GEP pointer operand.
863 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
864
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000865 // getelementptr P -> P.
866 if (NumOps == 1)
867 return Ops[0];
868
Duncan Sands85bbff62010-11-22 13:42:49 +0000869 if (isa<UndefValue>(Ops[0])) {
870 // Compute the (pointer) type returned by the GEP instruction.
871 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
872 NumOps-1);
873 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
874 return UndefValue::get(GEPTy);
875 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000876
Duncan Sandse60d79f2010-11-21 13:53:09 +0000877 if (NumOps == 2) {
878 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000879 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
880 if (C->isZero())
881 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +0000882 // getelementptr P, N -> P if P points to a type of zero size.
883 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000884 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +0000885 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +0000886 return Ops[0];
887 }
888 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000889
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000890 // Check to see if this is constant foldable.
891 for (unsigned i = 0; i != NumOps; ++i)
892 if (!isa<Constant>(Ops[i]))
893 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000894
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000895 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
896 (Constant *const*)Ops+1, NumOps-1);
897}
898
Duncan Sandsff103412010-11-17 04:30:22 +0000899/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
900static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
901 // If all of the PHI's incoming values are the same then replace the PHI node
902 // with the common value.
903 Value *CommonValue = 0;
904 bool HasUndefInput = false;
905 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
906 Value *Incoming = PN->getIncomingValue(i);
907 // If the incoming value is the phi node itself, it can safely be skipped.
908 if (Incoming == PN) continue;
909 if (isa<UndefValue>(Incoming)) {
910 // Remember that we saw an undef value, but otherwise ignore them.
911 HasUndefInput = true;
912 continue;
913 }
914 if (CommonValue && Incoming != CommonValue)
915 return 0; // Not the same, bail out.
916 CommonValue = Incoming;
917 }
918
919 // If CommonValue is null then all of the incoming values were either undef or
920 // equal to the phi node itself.
921 if (!CommonValue)
922 return UndefValue::get(PN->getType());
923
924 // If we have a PHI node like phi(X, undef, X), where X is defined by some
925 // instruction, we cannot return X as the result of the PHI node unless it
926 // dominates the PHI block.
927 if (HasUndefInput)
928 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
929
930 return CommonValue;
931}
932
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000933
Chris Lattnerd06094f2009-11-10 00:55:12 +0000934//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000935
Chris Lattnerd06094f2009-11-10 00:55:12 +0000936/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
937/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000938static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000939 const TargetData *TD, const DominatorTree *DT,
940 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000941 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +0000942 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
943 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000944 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
945 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
946 /* isNUW */ false, TD, DT,
947 MaxRecurse);
948 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
949 /* isNUW */ false, TD, DT,
950 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000951 default:
952 if (Constant *CLHS = dyn_cast<Constant>(LHS))
953 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
954 Constant *COps[] = {CLHS, CRHS};
955 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
956 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000957
Duncan Sands566edb02010-12-21 08:49:00 +0000958 // If the operation is associative, try some generic simplifications.
959 if (Instruction::isAssociative(Opcode))
960 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
961 MaxRecurse))
962 return V;
963
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000964 // If the operation is with the result of a select instruction, check whether
965 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000966 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +0000967 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000968 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000969 return V;
970
971 // If the operation is with the result of a phi instruction, check whether
972 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000973 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
974 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000975 return V;
976
Chris Lattnerd06094f2009-11-10 00:55:12 +0000977 return 0;
978 }
979}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000980
Duncan Sands12a86f52010-11-14 11:23:23 +0000981Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000982 const TargetData *TD, const DominatorTree *DT) {
983 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +0000984}
985
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000986/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
987/// fold the result.
988static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000989 const TargetData *TD, const DominatorTree *DT,
990 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000991 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +0000992 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
993 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000994}
995
996Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000997 const TargetData *TD, const DominatorTree *DT) {
998 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000999}
Chris Lattnere3453782009-11-10 01:08:51 +00001000
1001/// SimplifyInstruction - See if we can compute a simplified version of this
1002/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00001003Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1004 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00001005 Value *Result;
1006
Chris Lattnere3453782009-11-10 01:08:51 +00001007 switch (I->getOpcode()) {
1008 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001009 Result = ConstantFoldInstruction(I, TD);
1010 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001011 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001012 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1013 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1014 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1015 TD, DT);
1016 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001017 case Instruction::Sub:
1018 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1019 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1020 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1021 TD, DT);
1022 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001023 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001024 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1025 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001026 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001027 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1028 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001029 case Instruction::Xor:
1030 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1031 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001032 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001033 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1034 I->getOperand(0), I->getOperand(1), TD, DT);
1035 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001036 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001037 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1038 I->getOperand(0), I->getOperand(1), TD, DT);
1039 break;
Chris Lattner04754262010-04-20 05:32:14 +00001040 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001041 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1042 I->getOperand(2), TD, DT);
1043 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001044 case Instruction::GetElementPtr: {
1045 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001046 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1047 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001048 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001049 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001050 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1051 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001052 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001053
1054 /// If called on unreachable code, the above logic may report that the
1055 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001056 /// detecting that case here, returning a safe value instead.
1057 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001058}
1059
Chris Lattner40d8c282009-11-10 22:26:15 +00001060/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1061/// delete the From instruction. In addition to a basic RAUW, this does a
1062/// recursive simplification of the newly formed instructions. This catches
1063/// things where one simplification exposes other opportunities. This only
1064/// simplifies and deletes scalar operations, it does not change the CFG.
1065///
1066void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001067 const TargetData *TD,
1068 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001069 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001070
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001071 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1072 // we can know if it gets deleted out from under us or replaced in a
1073 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001074 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001075 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001076
Chris Lattner40d8c282009-11-10 22:26:15 +00001077 while (!From->use_empty()) {
1078 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001079 Use &TheUse = From->use_begin().getUse();
1080 Instruction *User = cast<Instruction>(TheUse.getUser());
1081 TheUse = To;
1082
1083 // Check to see if the instruction can be folded due to the operand
1084 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1085 // the 'or' with -1.
1086 Value *SimplifiedVal;
1087 {
1088 // Sanity check to make sure 'User' doesn't dangle across
1089 // SimplifyInstruction.
1090 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001091
Duncan Sandseff05812010-11-14 18:36:10 +00001092 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001093 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001094 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001095
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001096 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001097 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001098 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1099 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001100
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001101 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001102
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001103 // If the recursive simplification ended up revisiting and deleting
1104 // 'From' then we're done.
1105 if (From == 0)
1106 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001107 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001108
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001109 // If 'From' has value handles referring to it, do a real RAUW to update them.
1110 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001111
Chris Lattner40d8c282009-11-10 22:26:15 +00001112 From->eraseFromParent();
1113}