blob: c85e2293f00ba6f54284b83d29c2743f2776c1f7 [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 Sands3421d902010-12-21 13:32:22 +000056/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
57/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
58/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
59/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
60/// Returns the simplified value, or null if no simplification was performed.
61static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
62 unsigned OpcodeToExpand, const TargetData *TD,
63 const DominatorTree *DT, unsigned MaxRecurse) {
64 // Recursion is always used, so bail out at once if we already hit the limit.
65 if (!MaxRecurse--)
66 return 0;
67
68 // Check whether the expression has the form "(A op' B) op C".
69 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
70 if (Op0->getOpcode() == OpcodeToExpand) {
71 // It does! Try turning it into "(A op C) op' (B op C)".
72 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
73 // Do "A op C" and "B op C" both simplify?
74 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
75 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
76 // They do! Return "L op' R" if it simplifies or is already available.
77 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
78 if ((L == A && R == B) ||
79 (Instruction::isCommutative(OpcodeToExpand) && L == B && R == A))
80 return LHS;
81 // Otherwise return "L op' R" if it simplifies.
82 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,MaxRecurse))
83 return V;
84 }
85 }
86
87 // Check whether the expression has the form "A op (B op' C)".
88 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
89 if (Op1->getOpcode() == OpcodeToExpand) {
90 // It does! Try turning it into "(A op B) op' (A op C)".
91 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
92 // Do "A op B" and "A op C" both simplify?
93 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
94 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
95 // They do! Return "L op' R" if it simplifies or is already available.
96 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
97 if ((L == B && R == C) ||
98 (Instruction::isCommutative(OpcodeToExpand) && L == C && R == B))
99 return RHS;
100 // Otherwise return "L op' R" if it simplifies.
101 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,MaxRecurse))
102 return V;
103 }
104 }
105
106 return 0;
107}
108
109/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
110/// using the operation OpCodeToExtract. For example, when Opcode is Add and
111/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
112/// Returns the simplified value, or null if no simplification was performed.
113static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
114 unsigned OpcodeToExtract, const TargetData *TD,
115 const DominatorTree *DT, unsigned MaxRecurse) {
116 // Recursion is always used, so bail out at once if we already hit the limit.
117 if (!MaxRecurse--)
118 return 0;
119
120 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
121 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
122
123 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
124 !Op1 || Op1->getOpcode() != OpcodeToExtract)
125 return 0;
126
127 // The expression has the form "(A op' B) op (C op' D)".
128 Value *A = Op0->getOperand(0); Value *B = Op0->getOperand(1);
129 Value *C = Op1->getOperand(0); Value *D = Op1->getOperand(1);
130
131 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
132 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
133 // commutative case, "(A op' B) op (C op' A)"?
134 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
135 Value *DD = A == C ? D : C;
136 // Form "A op' (B op DD)" if it simplifies completely.
137 // Does "B op DD" simplify?
138 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
139 // It does! Return "A op' V" if it simplifies or is already available.
140 // If V equals B then "A op' V" is just the LHS.
141 if (V == B) return LHS;
142 // Otherwise return "A op' V" if it simplifies.
143 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse))
144 return W;
145 }
146 }
147
148 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
149 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
150 // commutative case, "(A op' B) op (B op' D)"?
151 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
152 Value *CC = B == D ? C : D;
153 // Form "(A op CC) op' B" if it simplifies completely..
154 // Does "A op CC" simplify?
155 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
156 // It does! Return "V op' B" if it simplifies or is already available.
157 // If V equals A then "V op' B" is just the LHS.
158 if (V == B) return LHS;
159 // Otherwise return "V op' B" if it simplifies.
160 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse))
161 return W;
162 }
163 }
164
165 return 0;
166}
167
168/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
169/// operations. Returns the simpler value, or null if none was found.
Duncan Sands566edb02010-12-21 08:49:00 +0000170static Value *SimplifyAssociativeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
171 const TargetData *TD,
172 const DominatorTree *DT,
173 unsigned MaxRecurse) {
174 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
175
176 // Recursion is always used, so bail out at once if we already hit the limit.
177 if (!MaxRecurse--)
178 return 0;
179
180 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
181 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
182
183 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
184 if (Op0 && Op0->getOpcode() == Opcode) {
185 Value *A = Op0->getOperand(0);
186 Value *B = Op0->getOperand(1);
187 Value *C = RHS;
188
189 // Does "B op C" simplify?
190 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
191 // It does! Return "A op V" if it simplifies or is already available.
192 // If V equals B then "A op V" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000193 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000194 // Otherwise return "A op V" if it simplifies.
195 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse))
196 return W;
197 }
198 }
199
200 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
201 if (Op1 && Op1->getOpcode() == Opcode) {
202 Value *A = LHS;
203 Value *B = Op1->getOperand(0);
204 Value *C = Op1->getOperand(1);
205
206 // Does "A op B" simplify?
207 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
208 // It does! Return "V op C" if it simplifies or is already available.
209 // If V equals B then "V op C" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000210 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000211 // Otherwise return "V op C" if it simplifies.
212 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse))
213 return W;
214 }
215 }
216
217 // The remaining transforms require commutativity as well as associativity.
218 if (!Instruction::isCommutative(Opcode))
219 return 0;
220
221 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
222 if (Op0 && Op0->getOpcode() == Opcode) {
223 Value *A = Op0->getOperand(0);
224 Value *B = Op0->getOperand(1);
225 Value *C = RHS;
226
227 // Does "C op A" simplify?
228 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
229 // It does! Return "V op B" if it simplifies or is already available.
230 // If V equals A then "V op B" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000231 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000232 // Otherwise return "V op B" if it simplifies.
233 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse))
234 return W;
235 }
236 }
237
238 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
239 if (Op1 && Op1->getOpcode() == Opcode) {
240 Value *A = LHS;
241 Value *B = Op1->getOperand(0);
242 Value *C = Op1->getOperand(1);
243
244 // Does "C op A" simplify?
245 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
246 // It does! Return "B op V" if it simplifies or is already available.
247 // If V equals C then "B op V" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000248 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000249 // Otherwise return "B op V" if it simplifies.
250 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse))
251 return W;
252 }
253 }
254
255 return 0;
256}
257
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000258/// ThreadBinOpOverSelect - In the case of a binary operation with a select
259/// instruction as an operand, try to simplify the binop by seeing whether
260/// evaluating it on both branches of the select results in the same value.
261/// Returns the common value if so, otherwise returns null.
262static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000263 const TargetData *TD,
264 const DominatorTree *DT,
265 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000266 // Recursion is always used, so bail out at once if we already hit the limit.
267 if (!MaxRecurse--)
268 return 0;
269
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000270 SelectInst *SI;
271 if (isa<SelectInst>(LHS)) {
272 SI = cast<SelectInst>(LHS);
273 } else {
274 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
275 SI = cast<SelectInst>(RHS);
276 }
277
278 // Evaluate the BinOp on the true and false branches of the select.
279 Value *TV;
280 Value *FV;
281 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000282 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
283 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000284 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000285 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
286 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000287 }
288
289 // If they simplified to the same value, then return the common value.
290 // If they both failed to simplify then return null.
291 if (TV == FV)
292 return TV;
293
294 // If one branch simplified to undef, return the other one.
295 if (TV && isa<UndefValue>(TV))
296 return FV;
297 if (FV && isa<UndefValue>(FV))
298 return TV;
299
300 // If applying the operation did not change the true and false select values,
301 // then the result of the binop is the select itself.
302 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
303 return SI;
304
305 // If one branch simplified and the other did not, and the simplified
306 // value is equal to the unsimplified one, return the simplified value.
307 // For example, select (cond, X, X & Z) & Z -> X & Z.
308 if ((FV && !TV) || (TV && !FV)) {
309 // Check that the simplified value has the form "X op Y" where "op" is the
310 // same as the original operation.
311 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
312 if (Simplified && Simplified->getOpcode() == Opcode) {
313 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
314 // We already know that "op" is the same as for the simplified value. See
315 // if the operands match too. If so, return the simplified value.
316 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
317 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
318 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
319 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
320 Simplified->getOperand(1) == UnsimplifiedRHS)
321 return Simplified;
322 if (Simplified->isCommutative() &&
323 Simplified->getOperand(1) == UnsimplifiedLHS &&
324 Simplified->getOperand(0) == UnsimplifiedRHS)
325 return Simplified;
326 }
327 }
328
329 return 0;
330}
331
332/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
333/// try to simplify the comparison by seeing whether both branches of the select
334/// result in the same value. Returns the common value if so, otherwise returns
335/// null.
336static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000337 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000338 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000339 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000340 // Recursion is always used, so bail out at once if we already hit the limit.
341 if (!MaxRecurse--)
342 return 0;
343
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000344 // Make sure the select is on the LHS.
345 if (!isa<SelectInst>(LHS)) {
346 std::swap(LHS, RHS);
347 Pred = CmpInst::getSwappedPredicate(Pred);
348 }
349 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
350 SelectInst *SI = cast<SelectInst>(LHS);
351
352 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
353 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000354 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000355 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000356 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000357 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000358 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000359 // It does! If they simplified to the same value, then use it as the
360 // result of the original comparison.
361 if (TCmp == FCmp)
362 return TCmp;
363 return 0;
364}
365
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000366/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
367/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
368/// it on the incoming phi values yields the same result for every value. If so
369/// returns the common value, otherwise returns null.
370static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000371 const TargetData *TD, const DominatorTree *DT,
372 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000373 // Recursion is always used, so bail out at once if we already hit the limit.
374 if (!MaxRecurse--)
375 return 0;
376
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000377 PHINode *PI;
378 if (isa<PHINode>(LHS)) {
379 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000380 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
381 if (!ValueDominatesPHI(RHS, PI, DT))
382 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000383 } else {
384 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
385 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000386 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
387 if (!ValueDominatesPHI(LHS, PI, DT))
388 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000389 }
390
391 // Evaluate the BinOp on the incoming phi values.
392 Value *CommonValue = 0;
393 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000394 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000395 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000396 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000397 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000398 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
399 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000400 // If the operation failed to simplify, or simplified to a different value
401 // to previously, then give up.
402 if (!V || (CommonValue && V != CommonValue))
403 return 0;
404 CommonValue = V;
405 }
406
407 return CommonValue;
408}
409
410/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
411/// try to simplify the comparison by seeing whether comparing with all of the
412/// incoming phi values yields the same result every time. If so returns the
413/// common result, otherwise returns null.
414static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000415 const TargetData *TD, const DominatorTree *DT,
416 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000417 // Recursion is always used, so bail out at once if we already hit the limit.
418 if (!MaxRecurse--)
419 return 0;
420
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000421 // Make sure the phi is on the LHS.
422 if (!isa<PHINode>(LHS)) {
423 std::swap(LHS, RHS);
424 Pred = CmpInst::getSwappedPredicate(Pred);
425 }
426 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
427 PHINode *PI = cast<PHINode>(LHS);
428
Duncan Sands18450092010-11-16 12:16:38 +0000429 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
430 if (!ValueDominatesPHI(RHS, PI, DT))
431 return 0;
432
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000433 // Evaluate the BinOp on the incoming phi values.
434 Value *CommonValue = 0;
435 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000436 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000437 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000438 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000439 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000440 // If the operation failed to simplify, or simplified to a different value
441 // to previously, then give up.
442 if (!V || (CommonValue && V != CommonValue))
443 return 0;
444 CommonValue = V;
445 }
446
447 return CommonValue;
448}
449
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000450/// SimplifyAddInst - Given operands for an Add, see if we can
451/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000452static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
453 const TargetData *TD, const DominatorTree *DT,
454 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000455 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
456 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
457 Constant *Ops[] = { CLHS, CRHS };
458 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
459 Ops, 2, TD);
460 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000461
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000462 // Canonicalize the constant to the RHS.
463 std::swap(Op0, Op1);
464 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000465
Duncan Sandsfea3b212010-12-15 14:07:39 +0000466 // X + undef -> undef
467 if (isa<UndefValue>(Op1))
468 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000469
Duncan Sandsfea3b212010-12-15 14:07:39 +0000470 // X + 0 -> X
471 if (match(Op1, m_Zero()))
472 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000473
Duncan Sandsfea3b212010-12-15 14:07:39 +0000474 // X + (Y - X) -> Y
475 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000476 // Eg: X + -X -> 0
Duncan Sandsfea3b212010-12-15 14:07:39 +0000477 Value *Y = 0;
478 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
479 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
480 return Y;
481
482 // X + ~X -> -1 since ~X = -X-1
483 if (match(Op0, m_Not(m_Specific(Op1))) ||
484 match(Op1, m_Not(m_Specific(Op0))))
485 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000486
Duncan Sands566edb02010-12-21 08:49:00 +0000487 // Try some generic simplifications for associative operations.
488 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
489 MaxRecurse))
490 return V;
491
Duncan Sands3421d902010-12-21 13:32:22 +0000492 // Mul distributes over Add. Try some generic simplifications based on this.
493 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
494 TD, DT, MaxRecurse))
495 return V;
496
Duncan Sands87689cf2010-11-19 09:20:39 +0000497 // Threading Add over selects and phi nodes is pointless, so don't bother.
498 // Threading over the select in "A + select(cond, B, C)" means evaluating
499 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
500 // only if B and C are equal. If B and C are equal then (since we assume
501 // that operands have already been simplified) "select(cond, B, C)" should
502 // have been simplified to the common value of B and C already. Analysing
503 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
504 // for threading over phi nodes.
505
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000506 return 0;
507}
508
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000509Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
510 const TargetData *TD, const DominatorTree *DT) {
511 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
512}
513
Duncan Sandsfea3b212010-12-15 14:07:39 +0000514/// SimplifySubInst - Given operands for a Sub, see if we can
515/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000516static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000517 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000518 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000519 if (Constant *CLHS = dyn_cast<Constant>(Op0))
520 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
521 Constant *Ops[] = { CLHS, CRHS };
522 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
523 Ops, 2, TD);
524 }
525
526 // X - undef -> undef
527 // undef - X -> undef
528 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
529 return UndefValue::get(Op0->getType());
530
531 // X - 0 -> X
532 if (match(Op1, m_Zero()))
533 return Op0;
534
535 // X - X -> 0
536 if (Op0 == Op1)
537 return Constant::getNullValue(Op0->getType());
538
539 // (X + Y) - Y -> X
540 // (Y + X) - Y -> X
541 Value *X = 0;
542 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
543 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
544 return X;
545
Duncan Sands3421d902010-12-21 13:32:22 +0000546 // Mul distributes over Sub. Try some generic simplifications based on this.
547 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
548 TD, DT, MaxRecurse))
549 return V;
550
Duncan Sandsfea3b212010-12-15 14:07:39 +0000551 // Threading Sub over selects and phi nodes is pointless, so don't bother.
552 // Threading over the select in "A - select(cond, B, C)" means evaluating
553 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
554 // only if B and C are equal. If B and C are equal then (since we assume
555 // that operands have already been simplified) "select(cond, B, C)" should
556 // have been simplified to the common value of B and C already. Analysing
557 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
558 // for threading over phi nodes.
559
560 return 0;
561}
562
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000563Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
564 const TargetData *TD, const DominatorTree *DT) {
565 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
566}
567
Chris Lattnerd06094f2009-11-10 00:55:12 +0000568/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000569/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000570static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000571 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000572 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
573 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
574 Constant *Ops[] = { CLHS, CRHS };
575 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
576 Ops, 2, TD);
577 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000578
Chris Lattnerd06094f2009-11-10 00:55:12 +0000579 // Canonicalize the constant to the RHS.
580 std::swap(Op0, Op1);
581 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000582
Chris Lattnerd06094f2009-11-10 00:55:12 +0000583 // X & undef -> 0
584 if (isa<UndefValue>(Op1))
585 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000586
Chris Lattnerd06094f2009-11-10 00:55:12 +0000587 // X & X = X
588 if (Op0 == Op1)
589 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000590
Duncan Sands2b749872010-11-17 18:52:15 +0000591 // X & 0 = 0
592 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000593 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000594
Duncan Sands2b749872010-11-17 18:52:15 +0000595 // X & -1 = X
596 if (match(Op1, m_AllOnes()))
597 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000598
Chris Lattnerd06094f2009-11-10 00:55:12 +0000599 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000600 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000601 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
602 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000603 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000604
Chris Lattnerd06094f2009-11-10 00:55:12 +0000605 // (A | ?) & A = A
606 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
607 (A == Op1 || B == Op1))
608 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000609
Chris Lattnerd06094f2009-11-10 00:55:12 +0000610 // A & (A | ?) = A
611 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
612 (A == Op0 || B == Op0))
613 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000614
Duncan Sands566edb02010-12-21 08:49:00 +0000615 // Try some generic simplifications for associative operations.
616 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
617 MaxRecurse))
618 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000619
Duncan Sands3421d902010-12-21 13:32:22 +0000620 // And distributes over Or. Try some generic simplifications based on this.
621 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
622 TD, DT, MaxRecurse))
623 return V;
624
625 // And distributes over Xor. Try some generic simplifications based on this.
626 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
627 TD, DT, MaxRecurse))
628 return V;
629
630 // Or distributes over And. Try some generic simplifications based on this.
631 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
632 TD, DT, MaxRecurse))
633 return V;
634
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000635 // If the operation is with the result of a select instruction, check whether
636 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000637 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000638 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000639 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000640 return V;
641
642 // If the operation is with the result of a phi instruction, check whether
643 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000644 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000645 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000646 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000647 return V;
648
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000649 return 0;
650}
651
Duncan Sands18450092010-11-16 12:16:38 +0000652Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
653 const DominatorTree *DT) {
654 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000655}
656
Chris Lattnerd06094f2009-11-10 00:55:12 +0000657/// SimplifyOrInst - Given operands for an Or, see if we can
658/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000659static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000660 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000661 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
662 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
663 Constant *Ops[] = { CLHS, CRHS };
664 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
665 Ops, 2, TD);
666 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000667
Chris Lattnerd06094f2009-11-10 00:55:12 +0000668 // Canonicalize the constant to the RHS.
669 std::swap(Op0, Op1);
670 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000671
Chris Lattnerd06094f2009-11-10 00:55:12 +0000672 // X | undef -> -1
673 if (isa<UndefValue>(Op1))
674 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000675
Chris Lattnerd06094f2009-11-10 00:55:12 +0000676 // X | X = X
677 if (Op0 == Op1)
678 return Op0;
679
Duncan Sands2b749872010-11-17 18:52:15 +0000680 // X | 0 = X
681 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000682 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000683
Duncan Sands2b749872010-11-17 18:52:15 +0000684 // X | -1 = -1
685 if (match(Op1, m_AllOnes()))
686 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000687
Chris Lattnerd06094f2009-11-10 00:55:12 +0000688 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000689 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000690 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
691 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000692 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000693
Chris Lattnerd06094f2009-11-10 00:55:12 +0000694 // (A & ?) | A = A
695 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
696 (A == Op1 || B == Op1))
697 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000698
Chris Lattnerd06094f2009-11-10 00:55:12 +0000699 // A | (A & ?) = A
700 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
701 (A == Op0 || B == Op0))
702 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000703
Duncan Sands566edb02010-12-21 08:49:00 +0000704 // Try some generic simplifications for associative operations.
705 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
706 MaxRecurse))
707 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000708
Duncan Sands3421d902010-12-21 13:32:22 +0000709 // Or distributes over And. Try some generic simplifications based on this.
710 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
711 TD, DT, MaxRecurse))
712 return V;
713
714 // And distributes over Or. Try some generic simplifications based on this.
715 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
716 TD, DT, MaxRecurse))
717 return V;
718
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000719 // If the operation is with the result of a select instruction, check whether
720 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000721 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000722 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000723 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000724 return V;
725
726 // If the operation is with the result of a phi instruction, check whether
727 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000728 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000729 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000730 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000731 return V;
732
Chris Lattnerd06094f2009-11-10 00:55:12 +0000733 return 0;
734}
735
Duncan Sands18450092010-11-16 12:16:38 +0000736Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
737 const DominatorTree *DT) {
738 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000739}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000740
Duncan Sands2b749872010-11-17 18:52:15 +0000741/// SimplifyXorInst - Given operands for a Xor, see if we can
742/// fold the result. If not, this returns null.
743static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
744 const DominatorTree *DT, unsigned MaxRecurse) {
745 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
746 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
747 Constant *Ops[] = { CLHS, CRHS };
748 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
749 Ops, 2, TD);
750 }
751
752 // Canonicalize the constant to the RHS.
753 std::swap(Op0, Op1);
754 }
755
756 // A ^ undef -> undef
757 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000758 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000759
760 // A ^ 0 = A
761 if (match(Op1, m_Zero()))
762 return Op0;
763
764 // A ^ A = 0
765 if (Op0 == Op1)
766 return Constant::getNullValue(Op0->getType());
767
768 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +0000769 Value *A = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000770 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
771 (match(Op1, m_Not(m_Value(A))) && A == Op0))
772 return Constant::getAllOnesValue(Op0->getType());
773
Duncan Sands566edb02010-12-21 08:49:00 +0000774 // Try some generic simplifications for associative operations.
775 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
776 MaxRecurse))
777 return V;
Duncan Sands2b749872010-11-17 18:52:15 +0000778
Duncan Sands3421d902010-12-21 13:32:22 +0000779 // And distributes over Xor. Try some generic simplifications based on this.
780 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
781 TD, DT, MaxRecurse))
782 return V;
783
Duncan Sands87689cf2010-11-19 09:20:39 +0000784 // Threading Xor over selects and phi nodes is pointless, so don't bother.
785 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
786 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
787 // only if B and C are equal. If B and C are equal then (since we assume
788 // that operands have already been simplified) "select(cond, B, C)" should
789 // have been simplified to the common value of B and C already. Analysing
790 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
791 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000792
793 return 0;
794}
795
796Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
797 const DominatorTree *DT) {
798 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
799}
800
Chris Lattner210c5d42009-11-09 23:55:12 +0000801static const Type *GetCompareTy(Value *Op) {
802 return CmpInst::makeCmpResultType(Op->getType());
803}
804
Chris Lattner9dbb4292009-11-09 23:28:39 +0000805/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
806/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000807static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000808 const TargetData *TD, const DominatorTree *DT,
809 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000810 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000811 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000812
Chris Lattnerd06094f2009-11-10 00:55:12 +0000813 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000814 if (Constant *CRHS = dyn_cast<Constant>(RHS))
815 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000816
817 // If we have a constant, make sure it is on the RHS.
818 std::swap(LHS, RHS);
819 Pred = CmpInst::getSwappedPredicate(Pred);
820 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000821
Chris Lattner210c5d42009-11-09 23:55:12 +0000822 // ITy - This is the return type of the compare we're considering.
823 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000824
Chris Lattner210c5d42009-11-09 23:55:12 +0000825 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000826 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
827 // because X could be 0.
828 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000829 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000830
Chris Lattner210c5d42009-11-09 23:55:12 +0000831 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
832 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000833 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000834 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000835 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000836 isa<ConstantPointerNull>(RHS)))
837 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000838
Chris Lattner210c5d42009-11-09 23:55:12 +0000839 // See if we are doing a comparison with a constant.
840 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
841 // If we have an icmp le or icmp ge instruction, turn it into the
842 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
843 // them being folded in the code below.
844 switch (Pred) {
845 default: break;
846 case ICmpInst::ICMP_ULE:
847 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
848 return ConstantInt::getTrue(CI->getContext());
849 break;
850 case ICmpInst::ICMP_SLE:
851 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
852 return ConstantInt::getTrue(CI->getContext());
853 break;
854 case ICmpInst::ICMP_UGE:
855 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
856 return ConstantInt::getTrue(CI->getContext());
857 break;
858 case ICmpInst::ICMP_SGE:
859 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
860 return ConstantInt::getTrue(CI->getContext());
861 break;
862 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000863 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000864
865 // If the comparison is with the result of a select instruction, check whether
866 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000867 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
868 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000869 return V;
870
871 // If the comparison is with the result of a phi instruction, check whether
872 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +0000873 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
874 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000875 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000876
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000877 return 0;
878}
879
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000880Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000881 const TargetData *TD, const DominatorTree *DT) {
882 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000883}
884
Chris Lattner9dbb4292009-11-09 23:28:39 +0000885/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
886/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000887static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000888 const TargetData *TD, const DominatorTree *DT,
889 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000890 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
891 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
892
Chris Lattnerd06094f2009-11-10 00:55:12 +0000893 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000894 if (Constant *CRHS = dyn_cast<Constant>(RHS))
895 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000896
Chris Lattnerd06094f2009-11-10 00:55:12 +0000897 // If we have a constant, make sure it is on the RHS.
898 std::swap(LHS, RHS);
899 Pred = CmpInst::getSwappedPredicate(Pred);
900 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000901
Chris Lattner210c5d42009-11-09 23:55:12 +0000902 // Fold trivial predicates.
903 if (Pred == FCmpInst::FCMP_FALSE)
904 return ConstantInt::get(GetCompareTy(LHS), 0);
905 if (Pred == FCmpInst::FCMP_TRUE)
906 return ConstantInt::get(GetCompareTy(LHS), 1);
907
Chris Lattner210c5d42009-11-09 23:55:12 +0000908 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
909 return UndefValue::get(GetCompareTy(LHS));
910
911 // fcmp x,x -> true/false. Not all compares are foldable.
912 if (LHS == RHS) {
913 if (CmpInst::isTrueWhenEqual(Pred))
914 return ConstantInt::get(GetCompareTy(LHS), 1);
915 if (CmpInst::isFalseWhenEqual(Pred))
916 return ConstantInt::get(GetCompareTy(LHS), 0);
917 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000918
Chris Lattner210c5d42009-11-09 23:55:12 +0000919 // Handle fcmp with constant RHS
920 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
921 // If the constant is a nan, see if we can fold the comparison based on it.
922 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
923 if (CFP->getValueAPF().isNaN()) {
924 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
925 return ConstantInt::getFalse(CFP->getContext());
926 assert(FCmpInst::isUnordered(Pred) &&
927 "Comparison must be either ordered or unordered!");
928 // True if unordered.
929 return ConstantInt::getTrue(CFP->getContext());
930 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000931 // Check whether the constant is an infinity.
932 if (CFP->getValueAPF().isInfinity()) {
933 if (CFP->getValueAPF().isNegative()) {
934 switch (Pred) {
935 case FCmpInst::FCMP_OLT:
936 // No value is ordered and less than negative infinity.
937 return ConstantInt::getFalse(CFP->getContext());
938 case FCmpInst::FCMP_UGE:
939 // All values are unordered with or at least negative infinity.
940 return ConstantInt::getTrue(CFP->getContext());
941 default:
942 break;
943 }
944 } else {
945 switch (Pred) {
946 case FCmpInst::FCMP_OGT:
947 // No value is ordered and greater than infinity.
948 return ConstantInt::getFalse(CFP->getContext());
949 case FCmpInst::FCMP_ULE:
950 // All values are unordered with and at most infinity.
951 return ConstantInt::getTrue(CFP->getContext());
952 default:
953 break;
954 }
955 }
956 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000957 }
958 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000959
Duncan Sands92826de2010-11-07 16:46:25 +0000960 // If the comparison is with the result of a select instruction, check whether
961 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000962 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
963 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000964 return V;
965
966 // If the comparison is with the result of a phi instruction, check whether
967 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +0000968 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
969 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000970 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000971
Chris Lattner9dbb4292009-11-09 23:28:39 +0000972 return 0;
973}
974
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000975Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000976 const TargetData *TD, const DominatorTree *DT) {
977 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000978}
979
Chris Lattner04754262010-04-20 05:32:14 +0000980/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
981/// the result. If not, this returns null.
982Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000983 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000984 // select true, X, Y -> X
985 // select false, X, Y -> Y
986 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
987 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000988
Chris Lattner04754262010-04-20 05:32:14 +0000989 // select C, X, X -> X
990 if (TrueVal == FalseVal)
991 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000992
Chris Lattner04754262010-04-20 05:32:14 +0000993 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
994 return FalseVal;
995 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
996 return TrueVal;
997 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
998 if (isa<Constant>(TrueVal))
999 return TrueVal;
1000 return FalseVal;
1001 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001002
Chris Lattner04754262010-04-20 05:32:14 +00001003 return 0;
1004}
1005
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001006/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1007/// fold the result. If not, this returns null.
1008Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00001009 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001010 // The type of the GEP pointer operand.
1011 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1012
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001013 // getelementptr P -> P.
1014 if (NumOps == 1)
1015 return Ops[0];
1016
Duncan Sands85bbff62010-11-22 13:42:49 +00001017 if (isa<UndefValue>(Ops[0])) {
1018 // Compute the (pointer) type returned by the GEP instruction.
1019 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1020 NumOps-1);
1021 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1022 return UndefValue::get(GEPTy);
1023 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001024
Duncan Sandse60d79f2010-11-21 13:53:09 +00001025 if (NumOps == 2) {
1026 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001027 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1028 if (C->isZero())
1029 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00001030 // getelementptr P, N -> P if P points to a type of zero size.
1031 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001032 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00001033 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00001034 return Ops[0];
1035 }
1036 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001037
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001038 // Check to see if this is constant foldable.
1039 for (unsigned i = 0; i != NumOps; ++i)
1040 if (!isa<Constant>(Ops[i]))
1041 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001042
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001043 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1044 (Constant *const*)Ops+1, NumOps-1);
1045}
1046
Duncan Sandsff103412010-11-17 04:30:22 +00001047/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1048static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1049 // If all of the PHI's incoming values are the same then replace the PHI node
1050 // with the common value.
1051 Value *CommonValue = 0;
1052 bool HasUndefInput = false;
1053 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1054 Value *Incoming = PN->getIncomingValue(i);
1055 // If the incoming value is the phi node itself, it can safely be skipped.
1056 if (Incoming == PN) continue;
1057 if (isa<UndefValue>(Incoming)) {
1058 // Remember that we saw an undef value, but otherwise ignore them.
1059 HasUndefInput = true;
1060 continue;
1061 }
1062 if (CommonValue && Incoming != CommonValue)
1063 return 0; // Not the same, bail out.
1064 CommonValue = Incoming;
1065 }
1066
1067 // If CommonValue is null then all of the incoming values were either undef or
1068 // equal to the phi node itself.
1069 if (!CommonValue)
1070 return UndefValue::get(PN->getType());
1071
1072 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1073 // instruction, we cannot return X as the result of the PHI node unless it
1074 // dominates the PHI block.
1075 if (HasUndefInput)
1076 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1077
1078 return CommonValue;
1079}
1080
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001081
Chris Lattnerd06094f2009-11-10 00:55:12 +00001082//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00001083
Chris Lattnerd06094f2009-11-10 00:55:12 +00001084/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1085/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001086static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001087 const TargetData *TD, const DominatorTree *DT,
1088 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001089 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +00001090 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1091 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsee9a2e32010-12-20 14:47:04 +00001092 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
1093 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1094 /* isNUW */ false, TD, DT,
1095 MaxRecurse);
1096 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1097 /* isNUW */ false, TD, DT,
1098 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001099 default:
1100 if (Constant *CLHS = dyn_cast<Constant>(LHS))
1101 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1102 Constant *COps[] = {CLHS, CRHS};
1103 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1104 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001105
Duncan Sands566edb02010-12-21 08:49:00 +00001106 // If the operation is associative, try some generic simplifications.
1107 if (Instruction::isAssociative(Opcode))
1108 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1109 MaxRecurse))
1110 return V;
1111
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001112 // If the operation is with the result of a select instruction, check whether
1113 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001114 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00001115 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001116 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001117 return V;
1118
1119 // If the operation is with the result of a phi instruction, check whether
1120 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001121 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1122 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001123 return V;
1124
Chris Lattnerd06094f2009-11-10 00:55:12 +00001125 return 0;
1126 }
1127}
Chris Lattner9dbb4292009-11-09 23:28:39 +00001128
Duncan Sands12a86f52010-11-14 11:23:23 +00001129Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001130 const TargetData *TD, const DominatorTree *DT) {
1131 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00001132}
1133
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001134/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1135/// fold the result.
1136static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001137 const TargetData *TD, const DominatorTree *DT,
1138 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001139 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00001140 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1141 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001142}
1143
1144Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001145 const TargetData *TD, const DominatorTree *DT) {
1146 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001147}
Chris Lattnere3453782009-11-10 01:08:51 +00001148
1149/// SimplifyInstruction - See if we can compute a simplified version of this
1150/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00001151Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1152 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00001153 Value *Result;
1154
Chris Lattnere3453782009-11-10 01:08:51 +00001155 switch (I->getOpcode()) {
1156 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001157 Result = ConstantFoldInstruction(I, TD);
1158 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001159 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001160 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1161 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1162 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1163 TD, DT);
1164 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001165 case Instruction::Sub:
1166 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1167 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1168 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1169 TD, DT);
1170 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001171 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001172 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1173 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001174 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001175 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1176 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001177 case Instruction::Xor:
1178 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1179 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001180 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001181 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1182 I->getOperand(0), I->getOperand(1), TD, DT);
1183 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001184 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001185 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1186 I->getOperand(0), I->getOperand(1), TD, DT);
1187 break;
Chris Lattner04754262010-04-20 05:32:14 +00001188 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001189 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1190 I->getOperand(2), TD, DT);
1191 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001192 case Instruction::GetElementPtr: {
1193 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001194 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1195 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001196 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001197 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001198 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1199 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001200 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001201
1202 /// If called on unreachable code, the above logic may report that the
1203 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001204 /// detecting that case here, returning a safe value instead.
1205 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001206}
1207
Chris Lattner40d8c282009-11-10 22:26:15 +00001208/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1209/// delete the From instruction. In addition to a basic RAUW, this does a
1210/// recursive simplification of the newly formed instructions. This catches
1211/// things where one simplification exposes other opportunities. This only
1212/// simplifies and deletes scalar operations, it does not change the CFG.
1213///
1214void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001215 const TargetData *TD,
1216 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001217 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001218
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001219 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1220 // we can know if it gets deleted out from under us or replaced in a
1221 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001222 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001223 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001224
Chris Lattner40d8c282009-11-10 22:26:15 +00001225 while (!From->use_empty()) {
1226 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001227 Use &TheUse = From->use_begin().getUse();
1228 Instruction *User = cast<Instruction>(TheUse.getUser());
1229 TheUse = To;
1230
1231 // Check to see if the instruction can be folded due to the operand
1232 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1233 // the 'or' with -1.
1234 Value *SimplifiedVal;
1235 {
1236 // Sanity check to make sure 'User' doesn't dangle across
1237 // SimplifyInstruction.
1238 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001239
Duncan Sandseff05812010-11-14 18:36:10 +00001240 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001241 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001242 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001243
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001244 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001245 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001246 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1247 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001248
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001249 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001250
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001251 // If the recursive simplification ended up revisiting and deleting
1252 // 'From' then we're done.
1253 if (From == 0)
1254 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001255 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001256
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001257 // If 'From' has value handles referring to it, do a real RAUW to update them.
1258 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001259
Chris Lattner40d8c282009-11-10 22:26:15 +00001260 From->eraseFromParent();
1261}