blob: 157193d5d361d3909ea5da81605723d2213a0552 [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
Duncan Sands82fdab32010-12-21 14:00:22 +000031static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
32 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000033static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000034 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000035static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000036 const DominatorTree *, unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000037static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
38 const DominatorTree *, unsigned);
39static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
40 const DominatorTree *, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000041
42/// ValueDominatesPHI - Does the given value dominate the specified phi node?
43static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
44 Instruction *I = dyn_cast<Instruction>(V);
45 if (!I)
46 // Arguments and constants dominate all instructions.
47 return true;
48
49 // If we have a DominatorTree then do a precise test.
50 if (DT)
51 return DT->dominates(I, P);
52
53 // Otherwise, if the instruction is in the entry block, and is not an invoke,
54 // then it obviously dominates all phi nodes.
55 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
56 !isa<InvokeInst>(I))
57 return true;
58
59 return false;
60}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000061
Duncan Sands3421d902010-12-21 13:32:22 +000062/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
63/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
64/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
65/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
66/// Returns the simplified value, or null if no simplification was performed.
67static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
68 unsigned OpcodeToExpand, const TargetData *TD,
69 const DominatorTree *DT, unsigned MaxRecurse) {
70 // Recursion is always used, so bail out at once if we already hit the limit.
71 if (!MaxRecurse--)
72 return 0;
73
74 // Check whether the expression has the form "(A op' B) op C".
75 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
76 if (Op0->getOpcode() == OpcodeToExpand) {
77 // It does! Try turning it into "(A op C) op' (B op C)".
78 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
79 // Do "A op C" and "B op C" both simplify?
80 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
81 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
82 // They do! Return "L op' R" if it simplifies or is already available.
83 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
84 if ((L == A && R == B) ||
85 (Instruction::isCommutative(OpcodeToExpand) && L == B && R == A))
86 return LHS;
87 // Otherwise return "L op' R" if it simplifies.
88 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,MaxRecurse))
89 return V;
90 }
91 }
92
93 // Check whether the expression has the form "A op (B op' C)".
94 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
95 if (Op1->getOpcode() == OpcodeToExpand) {
96 // It does! Try turning it into "(A op B) op' (A op C)".
97 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
98 // Do "A op B" and "A op C" both simplify?
99 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
100 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
101 // They do! Return "L op' R" if it simplifies or is already available.
102 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
103 if ((L == B && R == C) ||
104 (Instruction::isCommutative(OpcodeToExpand) && L == C && R == B))
105 return RHS;
106 // Otherwise return "L op' R" if it simplifies.
107 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,MaxRecurse))
108 return V;
109 }
110 }
111
112 return 0;
113}
114
115/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
116/// using the operation OpCodeToExtract. For example, when Opcode is Add and
117/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
118/// Returns the simplified value, or null if no simplification was performed.
119static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
120 unsigned OpcodeToExtract, const TargetData *TD,
121 const DominatorTree *DT, unsigned MaxRecurse) {
122 // Recursion is always used, so bail out at once if we already hit the limit.
123 if (!MaxRecurse--)
124 return 0;
125
126 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
127 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
128
129 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
130 !Op1 || Op1->getOpcode() != OpcodeToExtract)
131 return 0;
132
133 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000134 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
135 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000136
137 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
138 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
139 // commutative case, "(A op' B) op (C op' A)"?
140 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
141 Value *DD = A == C ? D : C;
142 // Form "A op' (B op DD)" if it simplifies completely.
143 // Does "B op DD" simplify?
144 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
145 // It does! Return "A op' V" if it simplifies or is already available.
146 // If V equals B then "A op' V" is just the LHS.
147 if (V == B) return LHS;
148 // Otherwise return "A op' V" if it simplifies.
149 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse))
150 return W;
151 }
152 }
153
154 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
155 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
156 // commutative case, "(A op' B) op (B op' D)"?
157 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
158 Value *CC = B == D ? C : D;
159 // Form "(A op CC) op' B" if it simplifies completely..
160 // Does "A op CC" simplify?
161 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
162 // It does! Return "V op' B" if it simplifies or is already available.
163 // If V equals A then "V op' B" is just the LHS.
164 if (V == B) return LHS;
165 // Otherwise return "V op' B" if it simplifies.
166 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse))
167 return W;
168 }
169 }
170
171 return 0;
172}
173
174/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
175/// operations. Returns the simpler value, or null if none was found.
Duncan Sands566edb02010-12-21 08:49:00 +0000176static Value *SimplifyAssociativeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
177 const TargetData *TD,
178 const DominatorTree *DT,
179 unsigned MaxRecurse) {
180 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
181
182 // Recursion is always used, so bail out at once if we already hit the limit.
183 if (!MaxRecurse--)
184 return 0;
185
186 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
187 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
188
189 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
190 if (Op0 && Op0->getOpcode() == Opcode) {
191 Value *A = Op0->getOperand(0);
192 Value *B = Op0->getOperand(1);
193 Value *C = RHS;
194
195 // Does "B op C" simplify?
196 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
197 // It does! Return "A op V" if it simplifies or is already available.
198 // If V equals B then "A op V" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000199 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000200 // Otherwise return "A op V" if it simplifies.
201 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse))
202 return W;
203 }
204 }
205
206 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
207 if (Op1 && Op1->getOpcode() == Opcode) {
208 Value *A = LHS;
209 Value *B = Op1->getOperand(0);
210 Value *C = Op1->getOperand(1);
211
212 // Does "A op B" simplify?
213 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
214 // It does! Return "V op C" if it simplifies or is already available.
215 // If V equals B then "V op C" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000216 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000217 // Otherwise return "V op C" if it simplifies.
218 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse))
219 return W;
220 }
221 }
222
223 // The remaining transforms require commutativity as well as associativity.
224 if (!Instruction::isCommutative(Opcode))
225 return 0;
226
227 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
228 if (Op0 && Op0->getOpcode() == Opcode) {
229 Value *A = Op0->getOperand(0);
230 Value *B = Op0->getOperand(1);
231 Value *C = RHS;
232
233 // Does "C op A" simplify?
234 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
235 // It does! Return "V op B" if it simplifies or is already available.
236 // If V equals A then "V op B" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000237 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000238 // Otherwise return "V op B" if it simplifies.
239 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse))
240 return W;
241 }
242 }
243
244 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
245 if (Op1 && Op1->getOpcode() == Opcode) {
246 Value *A = LHS;
247 Value *B = Op1->getOperand(0);
248 Value *C = Op1->getOperand(1);
249
250 // Does "C op A" simplify?
251 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
252 // It does! Return "B op V" if it simplifies or is already available.
253 // If V equals C then "B op V" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000254 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000255 // Otherwise return "B op V" if it simplifies.
256 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse))
257 return W;
258 }
259 }
260
261 return 0;
262}
263
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000264/// ThreadBinOpOverSelect - In the case of a binary operation with a select
265/// instruction as an operand, try to simplify the binop by seeing whether
266/// evaluating it on both branches of the select results in the same value.
267/// Returns the common value if so, otherwise returns null.
268static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000269 const TargetData *TD,
270 const DominatorTree *DT,
271 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000272 // Recursion is always used, so bail out at once if we already hit the limit.
273 if (!MaxRecurse--)
274 return 0;
275
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000276 SelectInst *SI;
277 if (isa<SelectInst>(LHS)) {
278 SI = cast<SelectInst>(LHS);
279 } else {
280 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
281 SI = cast<SelectInst>(RHS);
282 }
283
284 // Evaluate the BinOp on the true and false branches of the select.
285 Value *TV;
286 Value *FV;
287 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000288 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
289 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000290 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000291 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
292 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000293 }
294
295 // If they simplified to the same value, then return the common value.
296 // If they both failed to simplify then return null.
297 if (TV == FV)
298 return TV;
299
300 // If one branch simplified to undef, return the other one.
301 if (TV && isa<UndefValue>(TV))
302 return FV;
303 if (FV && isa<UndefValue>(FV))
304 return TV;
305
306 // If applying the operation did not change the true and false select values,
307 // then the result of the binop is the select itself.
308 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
309 return SI;
310
311 // If one branch simplified and the other did not, and the simplified
312 // value is equal to the unsimplified one, return the simplified value.
313 // For example, select (cond, X, X & Z) & Z -> X & Z.
314 if ((FV && !TV) || (TV && !FV)) {
315 // Check that the simplified value has the form "X op Y" where "op" is the
316 // same as the original operation.
317 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
318 if (Simplified && Simplified->getOpcode() == Opcode) {
319 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
320 // We already know that "op" is the same as for the simplified value. See
321 // if the operands match too. If so, return the simplified value.
322 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
323 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
324 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
325 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
326 Simplified->getOperand(1) == UnsimplifiedRHS)
327 return Simplified;
328 if (Simplified->isCommutative() &&
329 Simplified->getOperand(1) == UnsimplifiedLHS &&
330 Simplified->getOperand(0) == UnsimplifiedRHS)
331 return Simplified;
332 }
333 }
334
335 return 0;
336}
337
338/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
339/// try to simplify the comparison by seeing whether both branches of the select
340/// result in the same value. Returns the common value if so, otherwise returns
341/// null.
342static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000343 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000344 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000345 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000346 // Recursion is always used, so bail out at once if we already hit the limit.
347 if (!MaxRecurse--)
348 return 0;
349
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000350 // Make sure the select is on the LHS.
351 if (!isa<SelectInst>(LHS)) {
352 std::swap(LHS, RHS);
353 Pred = CmpInst::getSwappedPredicate(Pred);
354 }
355 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
356 SelectInst *SI = cast<SelectInst>(LHS);
357
358 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
359 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000360 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000361 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000362 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000363 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000364 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000365 // It does! If they simplified to the same value, then use it as the
366 // result of the original comparison.
367 if (TCmp == FCmp)
368 return TCmp;
369 return 0;
370}
371
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000372/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
373/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
374/// it on the incoming phi values yields the same result for every value. If so
375/// returns the common value, otherwise returns null.
376static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000377 const TargetData *TD, const DominatorTree *DT,
378 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000379 // Recursion is always used, so bail out at once if we already hit the limit.
380 if (!MaxRecurse--)
381 return 0;
382
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000383 PHINode *PI;
384 if (isa<PHINode>(LHS)) {
385 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000386 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
387 if (!ValueDominatesPHI(RHS, PI, DT))
388 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000389 } else {
390 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
391 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000392 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
393 if (!ValueDominatesPHI(LHS, PI, DT))
394 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000395 }
396
397 // Evaluate the BinOp on the incoming phi values.
398 Value *CommonValue = 0;
399 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000400 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000401 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000402 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000403 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000404 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
405 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000406 // If the operation failed to simplify, or simplified to a different value
407 // to previously, then give up.
408 if (!V || (CommonValue && V != CommonValue))
409 return 0;
410 CommonValue = V;
411 }
412
413 return CommonValue;
414}
415
416/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
417/// try to simplify the comparison by seeing whether comparing with all of the
418/// incoming phi values yields the same result every time. If so returns the
419/// common result, otherwise returns null.
420static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000421 const TargetData *TD, const DominatorTree *DT,
422 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000423 // Recursion is always used, so bail out at once if we already hit the limit.
424 if (!MaxRecurse--)
425 return 0;
426
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000427 // Make sure the phi is on the LHS.
428 if (!isa<PHINode>(LHS)) {
429 std::swap(LHS, RHS);
430 Pred = CmpInst::getSwappedPredicate(Pred);
431 }
432 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
433 PHINode *PI = cast<PHINode>(LHS);
434
Duncan Sands18450092010-11-16 12:16:38 +0000435 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
436 if (!ValueDominatesPHI(RHS, PI, DT))
437 return 0;
438
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000439 // Evaluate the BinOp on the incoming phi values.
440 Value *CommonValue = 0;
441 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000442 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000443 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000444 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000445 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000446 // If the operation failed to simplify, or simplified to a different value
447 // to previously, then give up.
448 if (!V || (CommonValue && V != CommonValue))
449 return 0;
450 CommonValue = V;
451 }
452
453 return CommonValue;
454}
455
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000456/// SimplifyAddInst - Given operands for an Add, see if we can
457/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000458static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
459 const TargetData *TD, const DominatorTree *DT,
460 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000461 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
462 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
463 Constant *Ops[] = { CLHS, CRHS };
464 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
465 Ops, 2, TD);
466 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000467
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000468 // Canonicalize the constant to the RHS.
469 std::swap(Op0, Op1);
470 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000471
Duncan Sandsfea3b212010-12-15 14:07:39 +0000472 // X + undef -> undef
473 if (isa<UndefValue>(Op1))
474 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000475
Duncan Sandsfea3b212010-12-15 14:07:39 +0000476 // X + 0 -> X
477 if (match(Op1, m_Zero()))
478 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000479
Duncan Sandsfea3b212010-12-15 14:07:39 +0000480 // X + (Y - X) -> Y
481 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000482 // Eg: X + -X -> 0
Duncan Sandsfea3b212010-12-15 14:07:39 +0000483 Value *Y = 0;
484 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
485 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
486 return Y;
487
488 // X + ~X -> -1 since ~X = -X-1
489 if (match(Op0, m_Not(m_Specific(Op1))) ||
490 match(Op1, m_Not(m_Specific(Op0))))
491 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000492
Duncan Sands82fdab32010-12-21 14:00:22 +0000493 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000494 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands82fdab32010-12-21 14:00:22 +0000495 return SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1);
496
Duncan Sands566edb02010-12-21 08:49:00 +0000497 // Try some generic simplifications for associative operations.
498 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
499 MaxRecurse))
500 return V;
501
Duncan Sands3421d902010-12-21 13:32:22 +0000502 // Mul distributes over Add. Try some generic simplifications based on this.
503 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
504 TD, DT, MaxRecurse))
505 return V;
506
Duncan Sands87689cf2010-11-19 09:20:39 +0000507 // Threading Add over selects and phi nodes is pointless, so don't bother.
508 // Threading over the select in "A + select(cond, B, C)" means evaluating
509 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
510 // only if B and C are equal. If B and C are equal then (since we assume
511 // that operands have already been simplified) "select(cond, B, C)" should
512 // have been simplified to the common value of B and C already. Analysing
513 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
514 // for threading over phi nodes.
515
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000516 return 0;
517}
518
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000519Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
520 const TargetData *TD, const DominatorTree *DT) {
521 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
522}
523
Duncan Sandsfea3b212010-12-15 14:07:39 +0000524/// SimplifySubInst - Given operands for a Sub, see if we can
525/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000526static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000527 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000528 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000529 if (Constant *CLHS = dyn_cast<Constant>(Op0))
530 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
531 Constant *Ops[] = { CLHS, CRHS };
532 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
533 Ops, 2, TD);
534 }
535
536 // X - undef -> undef
537 // undef - X -> undef
538 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
539 return UndefValue::get(Op0->getType());
540
541 // X - 0 -> X
542 if (match(Op1, m_Zero()))
543 return Op0;
544
545 // X - X -> 0
546 if (Op0 == Op1)
547 return Constant::getNullValue(Op0->getType());
548
549 // (X + Y) - Y -> X
550 // (Y + X) - Y -> X
551 Value *X = 0;
552 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
553 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
554 return X;
555
Duncan Sands82fdab32010-12-21 14:00:22 +0000556 /// i1 sub -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000557 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands82fdab32010-12-21 14:00:22 +0000558 return SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1);
559
Duncan Sands3421d902010-12-21 13:32:22 +0000560 // Mul distributes over Sub. Try some generic simplifications based on this.
561 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
562 TD, DT, MaxRecurse))
563 return V;
564
Duncan Sandsfea3b212010-12-15 14:07:39 +0000565 // Threading Sub over selects and phi nodes is pointless, so don't bother.
566 // Threading over the select in "A - select(cond, B, C)" means evaluating
567 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
568 // only if B and C are equal. If B and C are equal then (since we assume
569 // that operands have already been simplified) "select(cond, B, C)" should
570 // have been simplified to the common value of B and C already. Analysing
571 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
572 // for threading over phi nodes.
573
574 return 0;
575}
576
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000577Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
578 const TargetData *TD, const DominatorTree *DT) {
579 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
580}
581
Duncan Sands82fdab32010-12-21 14:00:22 +0000582/// SimplifyMulInst - Given operands for a Mul, see if we can
583/// fold the result. If not, this returns null.
584static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
585 const DominatorTree *DT, unsigned MaxRecurse) {
586 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
587 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
588 Constant *Ops[] = { CLHS, CRHS };
589 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
590 Ops, 2, TD);
591 }
592
593 // Canonicalize the constant to the RHS.
594 std::swap(Op0, Op1);
595 }
596
597 // X * undef -> 0
598 if (isa<UndefValue>(Op1))
599 return Constant::getNullValue(Op0->getType());
600
601 // X * 0 -> 0
602 if (match(Op1, m_Zero()))
603 return Op1;
604
605 // X * 1 -> X
606 if (match(Op1, m_One()))
607 return Op0;
608
609 /// i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000610 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands82fdab32010-12-21 14:00:22 +0000611 return SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1);
612
613 // Try some generic simplifications for associative operations.
614 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
615 MaxRecurse))
616 return V;
617
618 // Mul distributes over Add. Try some generic simplifications based on this.
619 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
620 TD, DT, MaxRecurse))
621 return V;
622
623 // If the operation is with the result of a select instruction, check whether
624 // operating on either branch of the select always yields the same value.
625 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
626 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
627 MaxRecurse))
628 return V;
629
630 // If the operation is with the result of a phi instruction, check whether
631 // operating on all incoming values of the phi always yields the same value.
632 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
633 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
634 MaxRecurse))
635 return V;
636
637 return 0;
638}
639
640Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
641 const DominatorTree *DT) {
642 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
643}
644
Chris Lattnerd06094f2009-11-10 00:55:12 +0000645/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000646/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000647static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000648 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000649 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
650 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
651 Constant *Ops[] = { CLHS, CRHS };
652 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
653 Ops, 2, TD);
654 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000655
Chris Lattnerd06094f2009-11-10 00:55:12 +0000656 // Canonicalize the constant to the RHS.
657 std::swap(Op0, Op1);
658 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000659
Chris Lattnerd06094f2009-11-10 00:55:12 +0000660 // X & undef -> 0
661 if (isa<UndefValue>(Op1))
662 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000663
Chris Lattnerd06094f2009-11-10 00:55:12 +0000664 // X & X = X
665 if (Op0 == Op1)
666 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000667
Duncan Sands2b749872010-11-17 18:52:15 +0000668 // X & 0 = 0
669 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000670 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000671
Duncan Sands2b749872010-11-17 18:52:15 +0000672 // X & -1 = X
673 if (match(Op1, m_AllOnes()))
674 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000675
Chris Lattnerd06094f2009-11-10 00:55:12 +0000676 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000677 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000678 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
679 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000680 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000681
Chris Lattnerd06094f2009-11-10 00:55:12 +0000682 // (A | ?) & A = A
683 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
684 (A == Op1 || B == Op1))
685 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000686
Chris Lattnerd06094f2009-11-10 00:55:12 +0000687 // A & (A | ?) = A
688 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
689 (A == Op0 || B == Op0))
690 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000691
Duncan Sands566edb02010-12-21 08:49:00 +0000692 // Try some generic simplifications for associative operations.
693 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
694 MaxRecurse))
695 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000696
Duncan Sands3421d902010-12-21 13:32:22 +0000697 // And distributes over Or. Try some generic simplifications based on this.
698 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
699 TD, DT, MaxRecurse))
700 return V;
701
702 // And distributes over Xor. Try some generic simplifications based on this.
703 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
704 TD, DT, MaxRecurse))
705 return V;
706
707 // Or distributes over And. Try some generic simplifications based on this.
708 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
709 TD, DT, MaxRecurse))
710 return V;
711
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000712 // If the operation is with the result of a select instruction, check whether
713 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000714 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000715 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000716 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000717 return V;
718
719 // If the operation is with the result of a phi instruction, check whether
720 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000721 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000722 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000723 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000724 return V;
725
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000726 return 0;
727}
728
Duncan Sands18450092010-11-16 12:16:38 +0000729Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
730 const DominatorTree *DT) {
731 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000732}
733
Chris Lattnerd06094f2009-11-10 00:55:12 +0000734/// SimplifyOrInst - Given operands for an Or, see if we can
735/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000736static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000737 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000738 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
739 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
740 Constant *Ops[] = { CLHS, CRHS };
741 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
742 Ops, 2, TD);
743 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000744
Chris Lattnerd06094f2009-11-10 00:55:12 +0000745 // Canonicalize the constant to the RHS.
746 std::swap(Op0, Op1);
747 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000748
Chris Lattnerd06094f2009-11-10 00:55:12 +0000749 // X | undef -> -1
750 if (isa<UndefValue>(Op1))
751 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000752
Chris Lattnerd06094f2009-11-10 00:55:12 +0000753 // X | X = X
754 if (Op0 == Op1)
755 return Op0;
756
Duncan Sands2b749872010-11-17 18:52:15 +0000757 // X | 0 = X
758 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000759 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000760
Duncan Sands2b749872010-11-17 18:52:15 +0000761 // X | -1 = -1
762 if (match(Op1, m_AllOnes()))
763 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000764
Chris Lattnerd06094f2009-11-10 00:55:12 +0000765 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000766 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000767 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
768 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000769 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000770
Chris Lattnerd06094f2009-11-10 00:55:12 +0000771 // (A & ?) | A = A
772 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
773 (A == Op1 || B == Op1))
774 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000775
Chris Lattnerd06094f2009-11-10 00:55:12 +0000776 // A | (A & ?) = A
777 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
778 (A == Op0 || B == Op0))
779 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000780
Duncan Sands566edb02010-12-21 08:49:00 +0000781 // Try some generic simplifications for associative operations.
782 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
783 MaxRecurse))
784 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000785
Duncan Sands3421d902010-12-21 13:32:22 +0000786 // Or distributes over And. Try some generic simplifications based on this.
787 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
788 TD, DT, MaxRecurse))
789 return V;
790
791 // And distributes over Or. Try some generic simplifications based on this.
792 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
793 TD, DT, MaxRecurse))
794 return V;
795
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000796 // If the operation is with the result of a select instruction, check whether
797 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000798 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000799 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000800 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000801 return V;
802
803 // If the operation is with the result of a phi instruction, check whether
804 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000805 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000806 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000807 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000808 return V;
809
Chris Lattnerd06094f2009-11-10 00:55:12 +0000810 return 0;
811}
812
Duncan Sands18450092010-11-16 12:16:38 +0000813Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
814 const DominatorTree *DT) {
815 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000816}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000817
Duncan Sands2b749872010-11-17 18:52:15 +0000818/// SimplifyXorInst - Given operands for a Xor, see if we can
819/// fold the result. If not, this returns null.
820static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
821 const DominatorTree *DT, unsigned MaxRecurse) {
822 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
823 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
824 Constant *Ops[] = { CLHS, CRHS };
825 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
826 Ops, 2, TD);
827 }
828
829 // Canonicalize the constant to the RHS.
830 std::swap(Op0, Op1);
831 }
832
833 // A ^ undef -> undef
834 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000835 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000836
837 // A ^ 0 = A
838 if (match(Op1, m_Zero()))
839 return Op0;
840
841 // A ^ A = 0
842 if (Op0 == Op1)
843 return Constant::getNullValue(Op0->getType());
844
845 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +0000846 Value *A = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000847 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
848 (match(Op1, m_Not(m_Value(A))) && A == Op0))
849 return Constant::getAllOnesValue(Op0->getType());
850
Duncan Sands566edb02010-12-21 08:49:00 +0000851 // Try some generic simplifications for associative operations.
852 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
853 MaxRecurse))
854 return V;
Duncan Sands2b749872010-11-17 18:52:15 +0000855
Duncan Sands3421d902010-12-21 13:32:22 +0000856 // And distributes over Xor. Try some generic simplifications based on this.
857 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
858 TD, DT, MaxRecurse))
859 return V;
860
Duncan Sands87689cf2010-11-19 09:20:39 +0000861 // Threading Xor over selects and phi nodes is pointless, so don't bother.
862 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
863 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
864 // only if B and C are equal. If B and C are equal then (since we assume
865 // that operands have already been simplified) "select(cond, B, C)" should
866 // have been simplified to the common value of B and C already. Analysing
867 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
868 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000869
870 return 0;
871}
872
873Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
874 const DominatorTree *DT) {
875 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
876}
877
Chris Lattner210c5d42009-11-09 23:55:12 +0000878static const Type *GetCompareTy(Value *Op) {
879 return CmpInst::makeCmpResultType(Op->getType());
880}
881
Chris Lattner9dbb4292009-11-09 23:28:39 +0000882/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
883/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000884static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000885 const TargetData *TD, const DominatorTree *DT,
886 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000887 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000888 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000889
Chris Lattnerd06094f2009-11-10 00:55:12 +0000890 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000891 if (Constant *CRHS = dyn_cast<Constant>(RHS))
892 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000893
894 // If we have a constant, make sure it is on the RHS.
895 std::swap(LHS, RHS);
896 Pred = CmpInst::getSwappedPredicate(Pred);
897 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000898
Chris Lattner210c5d42009-11-09 23:55:12 +0000899 // ITy - This is the return type of the compare we're considering.
900 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000901
Chris Lattner210c5d42009-11-09 23:55:12 +0000902 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000903 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
904 // because X could be 0.
905 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000906 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000907
Chris Lattner210c5d42009-11-09 23:55:12 +0000908 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
909 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000910 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000911 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000912 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000913 isa<ConstantPointerNull>(RHS)))
914 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000915
Chris Lattner210c5d42009-11-09 23:55:12 +0000916 // See if we are doing a comparison with a constant.
917 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
918 // If we have an icmp le or icmp ge instruction, turn it into the
919 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
920 // them being folded in the code below.
921 switch (Pred) {
922 default: break;
923 case ICmpInst::ICMP_ULE:
924 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
925 return ConstantInt::getTrue(CI->getContext());
926 break;
927 case ICmpInst::ICMP_SLE:
928 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
929 return ConstantInt::getTrue(CI->getContext());
930 break;
931 case ICmpInst::ICMP_UGE:
932 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
933 return ConstantInt::getTrue(CI->getContext());
934 break;
935 case ICmpInst::ICMP_SGE:
936 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
937 return ConstantInt::getTrue(CI->getContext());
938 break;
939 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000940 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000941
942 // If the comparison is with the result of a select instruction, check whether
943 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000944 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
945 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000946 return V;
947
948 // If the comparison is with the result of a phi instruction, check whether
949 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +0000950 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
951 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000952 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000953
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000954 return 0;
955}
956
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000957Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000958 const TargetData *TD, const DominatorTree *DT) {
959 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000960}
961
Chris Lattner9dbb4292009-11-09 23:28:39 +0000962/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
963/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000964static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000965 const TargetData *TD, const DominatorTree *DT,
966 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000967 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
968 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
969
Chris Lattnerd06094f2009-11-10 00:55:12 +0000970 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000971 if (Constant *CRHS = dyn_cast<Constant>(RHS))
972 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000973
Chris Lattnerd06094f2009-11-10 00:55:12 +0000974 // If we have a constant, make sure it is on the RHS.
975 std::swap(LHS, RHS);
976 Pred = CmpInst::getSwappedPredicate(Pred);
977 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000978
Chris Lattner210c5d42009-11-09 23:55:12 +0000979 // Fold trivial predicates.
980 if (Pred == FCmpInst::FCMP_FALSE)
981 return ConstantInt::get(GetCompareTy(LHS), 0);
982 if (Pred == FCmpInst::FCMP_TRUE)
983 return ConstantInt::get(GetCompareTy(LHS), 1);
984
Chris Lattner210c5d42009-11-09 23:55:12 +0000985 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
986 return UndefValue::get(GetCompareTy(LHS));
987
988 // fcmp x,x -> true/false. Not all compares are foldable.
989 if (LHS == RHS) {
990 if (CmpInst::isTrueWhenEqual(Pred))
991 return ConstantInt::get(GetCompareTy(LHS), 1);
992 if (CmpInst::isFalseWhenEqual(Pred))
993 return ConstantInt::get(GetCompareTy(LHS), 0);
994 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000995
Chris Lattner210c5d42009-11-09 23:55:12 +0000996 // Handle fcmp with constant RHS
997 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
998 // If the constant is a nan, see if we can fold the comparison based on it.
999 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1000 if (CFP->getValueAPF().isNaN()) {
1001 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1002 return ConstantInt::getFalse(CFP->getContext());
1003 assert(FCmpInst::isUnordered(Pred) &&
1004 "Comparison must be either ordered or unordered!");
1005 // True if unordered.
1006 return ConstantInt::getTrue(CFP->getContext());
1007 }
Dan Gohman6b617a72010-02-22 04:06:03 +00001008 // Check whether the constant is an infinity.
1009 if (CFP->getValueAPF().isInfinity()) {
1010 if (CFP->getValueAPF().isNegative()) {
1011 switch (Pred) {
1012 case FCmpInst::FCMP_OLT:
1013 // No value is ordered and less than negative infinity.
1014 return ConstantInt::getFalse(CFP->getContext());
1015 case FCmpInst::FCMP_UGE:
1016 // All values are unordered with or at least negative infinity.
1017 return ConstantInt::getTrue(CFP->getContext());
1018 default:
1019 break;
1020 }
1021 } else {
1022 switch (Pred) {
1023 case FCmpInst::FCMP_OGT:
1024 // No value is ordered and greater than infinity.
1025 return ConstantInt::getFalse(CFP->getContext());
1026 case FCmpInst::FCMP_ULE:
1027 // All values are unordered with and at most infinity.
1028 return ConstantInt::getTrue(CFP->getContext());
1029 default:
1030 break;
1031 }
1032 }
1033 }
Chris Lattner210c5d42009-11-09 23:55:12 +00001034 }
1035 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001036
Duncan Sands92826de2010-11-07 16:46:25 +00001037 // If the comparison is with the result of a select instruction, check whether
1038 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001039 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1040 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001041 return V;
1042
1043 // If the comparison is with the result of a phi instruction, check whether
1044 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001045 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1046 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001047 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00001048
Chris Lattner9dbb4292009-11-09 23:28:39 +00001049 return 0;
1050}
1051
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001052Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001053 const TargetData *TD, const DominatorTree *DT) {
1054 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001055}
1056
Chris Lattner04754262010-04-20 05:32:14 +00001057/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1058/// the result. If not, this returns null.
1059Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +00001060 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00001061 // select true, X, Y -> X
1062 // select false, X, Y -> Y
1063 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1064 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001065
Chris Lattner04754262010-04-20 05:32:14 +00001066 // select C, X, X -> X
1067 if (TrueVal == FalseVal)
1068 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001069
Chris Lattner04754262010-04-20 05:32:14 +00001070 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1071 return FalseVal;
1072 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1073 return TrueVal;
1074 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1075 if (isa<Constant>(TrueVal))
1076 return TrueVal;
1077 return FalseVal;
1078 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001079
Chris Lattner04754262010-04-20 05:32:14 +00001080 return 0;
1081}
1082
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001083/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1084/// fold the result. If not, this returns null.
1085Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00001086 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001087 // The type of the GEP pointer operand.
1088 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1089
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001090 // getelementptr P -> P.
1091 if (NumOps == 1)
1092 return Ops[0];
1093
Duncan Sands85bbff62010-11-22 13:42:49 +00001094 if (isa<UndefValue>(Ops[0])) {
1095 // Compute the (pointer) type returned by the GEP instruction.
1096 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1097 NumOps-1);
1098 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1099 return UndefValue::get(GEPTy);
1100 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001101
Duncan Sandse60d79f2010-11-21 13:53:09 +00001102 if (NumOps == 2) {
1103 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001104 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1105 if (C->isZero())
1106 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00001107 // getelementptr P, N -> P if P points to a type of zero size.
1108 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001109 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00001110 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00001111 return Ops[0];
1112 }
1113 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001114
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001115 // Check to see if this is constant foldable.
1116 for (unsigned i = 0; i != NumOps; ++i)
1117 if (!isa<Constant>(Ops[i]))
1118 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001119
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001120 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1121 (Constant *const*)Ops+1, NumOps-1);
1122}
1123
Duncan Sandsff103412010-11-17 04:30:22 +00001124/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1125static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1126 // If all of the PHI's incoming values are the same then replace the PHI node
1127 // with the common value.
1128 Value *CommonValue = 0;
1129 bool HasUndefInput = false;
1130 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1131 Value *Incoming = PN->getIncomingValue(i);
1132 // If the incoming value is the phi node itself, it can safely be skipped.
1133 if (Incoming == PN) continue;
1134 if (isa<UndefValue>(Incoming)) {
1135 // Remember that we saw an undef value, but otherwise ignore them.
1136 HasUndefInput = true;
1137 continue;
1138 }
1139 if (CommonValue && Incoming != CommonValue)
1140 return 0; // Not the same, bail out.
1141 CommonValue = Incoming;
1142 }
1143
1144 // If CommonValue is null then all of the incoming values were either undef or
1145 // equal to the phi node itself.
1146 if (!CommonValue)
1147 return UndefValue::get(PN->getType());
1148
1149 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1150 // instruction, we cannot return X as the result of the PHI node unless it
1151 // dominates the PHI block.
1152 if (HasUndefInput)
1153 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1154
1155 return CommonValue;
1156}
1157
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001158
Chris Lattnerd06094f2009-11-10 00:55:12 +00001159//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00001160
Chris Lattnerd06094f2009-11-10 00:55:12 +00001161/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1162/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001163static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001164 const TargetData *TD, const DominatorTree *DT,
1165 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001166 switch (Opcode) {
Duncan Sandsee9a2e32010-12-20 14:47:04 +00001167 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1168 /* isNUW */ false, TD, DT,
1169 MaxRecurse);
1170 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1171 /* isNUW */ false, TD, DT,
1172 MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00001173 case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
1174 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1175 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1176 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001177 default:
1178 if (Constant *CLHS = dyn_cast<Constant>(LHS))
1179 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1180 Constant *COps[] = {CLHS, CRHS};
1181 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1182 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001183
Duncan Sands566edb02010-12-21 08:49:00 +00001184 // If the operation is associative, try some generic simplifications.
1185 if (Instruction::isAssociative(Opcode))
1186 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1187 MaxRecurse))
1188 return V;
1189
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001190 // If the operation is with the result of a select instruction, check whether
1191 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001192 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00001193 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001194 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001195 return V;
1196
1197 // If the operation is with the result of a phi instruction, check whether
1198 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001199 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1200 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001201 return V;
1202
Chris Lattnerd06094f2009-11-10 00:55:12 +00001203 return 0;
1204 }
1205}
Chris Lattner9dbb4292009-11-09 23:28:39 +00001206
Duncan Sands12a86f52010-11-14 11:23:23 +00001207Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001208 const TargetData *TD, const DominatorTree *DT) {
1209 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00001210}
1211
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001212/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1213/// fold the result.
1214static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001215 const TargetData *TD, const DominatorTree *DT,
1216 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001217 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00001218 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1219 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001220}
1221
1222Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001223 const TargetData *TD, const DominatorTree *DT) {
1224 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001225}
Chris Lattnere3453782009-11-10 01:08:51 +00001226
1227/// SimplifyInstruction - See if we can compute a simplified version of this
1228/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00001229Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1230 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00001231 Value *Result;
1232
Chris Lattnere3453782009-11-10 01:08:51 +00001233 switch (I->getOpcode()) {
1234 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001235 Result = ConstantFoldInstruction(I, TD);
1236 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001237 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001238 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1239 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1240 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1241 TD, DT);
1242 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001243 case Instruction::Sub:
1244 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1245 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1246 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1247 TD, DT);
1248 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00001249 case Instruction::Mul:
1250 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1251 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001252 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001253 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1254 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001255 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001256 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1257 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001258 case Instruction::Xor:
1259 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1260 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001261 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001262 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1263 I->getOperand(0), I->getOperand(1), TD, DT);
1264 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001265 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001266 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1267 I->getOperand(0), I->getOperand(1), TD, DT);
1268 break;
Chris Lattner04754262010-04-20 05:32:14 +00001269 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001270 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1271 I->getOperand(2), TD, DT);
1272 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001273 case Instruction::GetElementPtr: {
1274 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001275 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1276 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001277 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001278 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001279 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1280 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001281 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001282
1283 /// If called on unreachable code, the above logic may report that the
1284 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001285 /// detecting that case here, returning a safe value instead.
1286 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001287}
1288
Chris Lattner40d8c282009-11-10 22:26:15 +00001289/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1290/// delete the From instruction. In addition to a basic RAUW, this does a
1291/// recursive simplification of the newly formed instructions. This catches
1292/// things where one simplification exposes other opportunities. This only
1293/// simplifies and deletes scalar operations, it does not change the CFG.
1294///
1295void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001296 const TargetData *TD,
1297 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001298 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001299
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001300 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1301 // we can know if it gets deleted out from under us or replaced in a
1302 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001303 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001304 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001305
Chris Lattner40d8c282009-11-10 22:26:15 +00001306 while (!From->use_empty()) {
1307 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001308 Use &TheUse = From->use_begin().getUse();
1309 Instruction *User = cast<Instruction>(TheUse.getUser());
1310 TheUse = To;
1311
1312 // Check to see if the instruction can be folded due to the operand
1313 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1314 // the 'or' with -1.
1315 Value *SimplifiedVal;
1316 {
1317 // Sanity check to make sure 'User' doesn't dangle across
1318 // SimplifyInstruction.
1319 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001320
Duncan Sandseff05812010-11-14 18:36:10 +00001321 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001322 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001323 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001324
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001325 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001326 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001327 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1328 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001329
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001330 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001331
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001332 // If the recursive simplification ended up revisiting and deleting
1333 // 'From' then we're done.
1334 if (From == 0)
1335 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001336 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001337
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001338 // If 'From' has value handles referring to it, do a real RAUW to update them.
1339 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001340
Chris Lattner40d8c282009-11-10 22:26:15 +00001341 From->eraseFromParent();
1342}