blob: 9dd5f050c5897967e8e632c2204e22b5dd7c7a78 [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
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
21#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000022#include "llvm/Analysis/InstructionSimplify.h"
23#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000024#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000025#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000026#include "llvm/Support/ConstantRange.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000027#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000028#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000029#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000030using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000031using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000032
Chris Lattner81a0dc92011-02-09 17:15:04 +000033enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000034
Duncan Sandsa3c44a52010-12-22 09:40:51 +000035STATISTIC(NumExpand, "Number of expansions");
36STATISTIC(NumFactor , "Number of factorizations");
37STATISTIC(NumReassoc, "Number of reassociations");
38
Duncan Sands82fdab32010-12-21 14:00:22 +000039static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
40 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000041static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000042 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000043static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000044 const DominatorTree *, unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000045static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
46 const DominatorTree *, unsigned);
47static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
48 const DominatorTree *, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000049
50/// ValueDominatesPHI - Does the given value dominate the specified phi node?
51static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
52 Instruction *I = dyn_cast<Instruction>(V);
53 if (!I)
54 // Arguments and constants dominate all instructions.
55 return true;
56
57 // If we have a DominatorTree then do a precise test.
58 if (DT)
59 return DT->dominates(I, P);
60
61 // Otherwise, if the instruction is in the entry block, and is not an invoke,
62 // then it obviously dominates all phi nodes.
63 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
64 !isa<InvokeInst>(I))
65 return true;
66
67 return false;
68}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000069
Duncan Sands3421d902010-12-21 13:32:22 +000070/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
71/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
72/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
73/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
74/// Returns the simplified value, or null if no simplification was performed.
75static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +000076 unsigned OpcToExpand, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +000077 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +000078 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000079 // Recursion is always used, so bail out at once if we already hit the limit.
80 if (!MaxRecurse--)
81 return 0;
82
83 // Check whether the expression has the form "(A op' B) op C".
84 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
85 if (Op0->getOpcode() == OpcodeToExpand) {
86 // It does! Try turning it into "(A op C) op' (B op C)".
87 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
88 // Do "A op C" and "B op C" both simplify?
89 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
90 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
91 // They do! Return "L op' R" if it simplifies or is already available.
92 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +000093 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
94 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +000095 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000096 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +000097 }
Duncan Sands3421d902010-12-21 13:32:22 +000098 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +000099 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
100 MaxRecurse)) {
101 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000102 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000103 }
Duncan Sands3421d902010-12-21 13:32:22 +0000104 }
105 }
106
107 // Check whether the expression has the form "A op (B op' C)".
108 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
109 if (Op1->getOpcode() == OpcodeToExpand) {
110 // It does! Try turning it into "(A op B) op' (A op C)".
111 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
112 // Do "A op B" and "A op C" both simplify?
113 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
114 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
115 // They do! Return "L op' R" if it simplifies or is already available.
116 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000117 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
118 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000119 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000120 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000121 }
Duncan Sands3421d902010-12-21 13:32:22 +0000122 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000123 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
124 MaxRecurse)) {
125 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000126 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000127 }
Duncan Sands3421d902010-12-21 13:32:22 +0000128 }
129 }
130
131 return 0;
132}
133
134/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
135/// using the operation OpCodeToExtract. For example, when Opcode is Add and
136/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
137/// Returns the simplified value, or null if no simplification was performed.
138static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000139 unsigned OpcToExtract, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +0000140 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000141 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000142 // Recursion is always used, so bail out at once if we already hit the limit.
143 if (!MaxRecurse--)
144 return 0;
145
146 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
147 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
148
149 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
150 !Op1 || Op1->getOpcode() != OpcodeToExtract)
151 return 0;
152
153 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000154 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
155 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000156
157 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
158 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
159 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000160 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
161 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000162 // Form "A op' (B op DD)" if it simplifies completely.
163 // Does "B op DD" simplify?
164 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
165 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000166 // If V equals B then "A op' V" is just the LHS. If V equals DD then
167 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000168 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000169 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000170 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000171 }
Duncan Sands3421d902010-12-21 13:32:22 +0000172 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000173 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
174 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000175 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000176 }
Duncan Sands3421d902010-12-21 13:32:22 +0000177 }
178 }
179
180 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
181 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
182 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000183 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
184 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000185 // Form "(A op CC) op' B" if it simplifies completely..
186 // Does "A op CC" simplify?
187 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
188 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000189 // If V equals A then "V op' B" is just the LHS. If V equals CC then
190 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000191 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000192 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000193 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000194 }
Duncan Sands3421d902010-12-21 13:32:22 +0000195 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000196 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
197 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000198 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000199 }
Duncan Sands3421d902010-12-21 13:32:22 +0000200 }
201 }
202
203 return 0;
204}
205
206/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
207/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000208static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000209 const TargetData *TD,
210 const DominatorTree *DT,
211 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000212 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000213 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
214
215 // Recursion is always used, so bail out at once if we already hit the limit.
216 if (!MaxRecurse--)
217 return 0;
218
219 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
220 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
221
222 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
223 if (Op0 && Op0->getOpcode() == Opcode) {
224 Value *A = Op0->getOperand(0);
225 Value *B = Op0->getOperand(1);
226 Value *C = RHS;
227
228 // Does "B op C" simplify?
229 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
230 // It does! Return "A op V" if it simplifies or is already available.
231 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000232 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000233 // Otherwise return "A op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000234 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
235 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000236 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000237 }
Duncan Sands566edb02010-12-21 08:49:00 +0000238 }
239 }
240
241 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
242 if (Op1 && Op1->getOpcode() == Opcode) {
243 Value *A = LHS;
244 Value *B = Op1->getOperand(0);
245 Value *C = Op1->getOperand(1);
246
247 // Does "A op B" simplify?
248 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
249 // It does! Return "V op C" if it simplifies or is already available.
250 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000251 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000252 // Otherwise return "V op C" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000253 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
254 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000255 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000256 }
Duncan Sands566edb02010-12-21 08:49:00 +0000257 }
258 }
259
260 // The remaining transforms require commutativity as well as associativity.
261 if (!Instruction::isCommutative(Opcode))
262 return 0;
263
264 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
265 if (Op0 && Op0->getOpcode() == Opcode) {
266 Value *A = Op0->getOperand(0);
267 Value *B = Op0->getOperand(1);
268 Value *C = RHS;
269
270 // Does "C op A" simplify?
271 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
272 // It does! Return "V op B" if it simplifies or is already available.
273 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000274 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000275 // Otherwise return "V op B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000276 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
277 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000278 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000279 }
Duncan Sands566edb02010-12-21 08:49:00 +0000280 }
281 }
282
283 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
284 if (Op1 && Op1->getOpcode() == Opcode) {
285 Value *A = LHS;
286 Value *B = Op1->getOperand(0);
287 Value *C = Op1->getOperand(1);
288
289 // Does "C op A" simplify?
290 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
291 // It does! Return "B op V" if it simplifies or is already available.
292 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000293 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000294 // Otherwise return "B op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000295 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
296 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000297 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000298 }
Duncan Sands566edb02010-12-21 08:49:00 +0000299 }
300 }
301
302 return 0;
303}
304
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000305/// ThreadBinOpOverSelect - In the case of a binary operation with a select
306/// instruction as an operand, try to simplify the binop by seeing whether
307/// evaluating it on both branches of the select results in the same value.
308/// Returns the common value if so, otherwise returns null.
309static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000310 const TargetData *TD,
311 const DominatorTree *DT,
312 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000313 // Recursion is always used, so bail out at once if we already hit the limit.
314 if (!MaxRecurse--)
315 return 0;
316
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000317 SelectInst *SI;
318 if (isa<SelectInst>(LHS)) {
319 SI = cast<SelectInst>(LHS);
320 } else {
321 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
322 SI = cast<SelectInst>(RHS);
323 }
324
325 // Evaluate the BinOp on the true and false branches of the select.
326 Value *TV;
327 Value *FV;
328 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000329 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
330 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000331 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000332 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
333 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000334 }
335
Duncan Sands7cf85e72011-01-01 16:12:09 +0000336 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000337 // If they both failed to simplify then return null.
338 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000339 return TV;
340
341 // If one branch simplified to undef, return the other one.
342 if (TV && isa<UndefValue>(TV))
343 return FV;
344 if (FV && isa<UndefValue>(FV))
345 return TV;
346
347 // If applying the operation did not change the true and false select values,
348 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000349 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000350 return SI;
351
352 // If one branch simplified and the other did not, and the simplified
353 // value is equal to the unsimplified one, return the simplified value.
354 // For example, select (cond, X, X & Z) & Z -> X & Z.
355 if ((FV && !TV) || (TV && !FV)) {
356 // Check that the simplified value has the form "X op Y" where "op" is the
357 // same as the original operation.
358 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
359 if (Simplified && Simplified->getOpcode() == Opcode) {
360 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
361 // We already know that "op" is the same as for the simplified value. See
362 // if the operands match too. If so, return the simplified value.
363 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
364 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
365 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000366 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
367 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000368 return Simplified;
369 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000370 Simplified->getOperand(1) == UnsimplifiedLHS &&
371 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000372 return Simplified;
373 }
374 }
375
376 return 0;
377}
378
379/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
380/// try to simplify the comparison by seeing whether both branches of the select
381/// result in the same value. Returns the common value if so, otherwise returns
382/// null.
383static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000384 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000385 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000386 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000387 // Recursion is always used, so bail out at once if we already hit the limit.
388 if (!MaxRecurse--)
389 return 0;
390
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000391 // Make sure the select is on the LHS.
392 if (!isa<SelectInst>(LHS)) {
393 std::swap(LHS, RHS);
394 Pred = CmpInst::getSwappedPredicate(Pred);
395 }
396 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
397 SelectInst *SI = cast<SelectInst>(LHS);
398
Duncan Sands50ca4d32011-02-03 09:37:39 +0000399 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000400 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000401 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000402 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000403 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000404 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000405 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000406 // It does! If they simplified to the same value, then use it as the
407 // result of the original comparison.
Duncan Sands124708d2011-01-01 20:08:02 +0000408 if (TCmp == FCmp)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000409 return TCmp;
Duncan Sands50ca4d32011-02-03 09:37:39 +0000410 Value *Cond = SI->getCondition();
411 // If the false value simplified to false, then the result of the compare
412 // is equal to "Cond && TCmp". This also catches the case when the false
413 // value simplified to false and the true value to true, returning "Cond".
414 if (match(FCmp, m_Zero()))
415 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
416 return V;
417 // If the true value simplified to true, then the result of the compare
418 // is equal to "Cond || FCmp".
419 if (match(TCmp, m_One()))
420 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
421 return V;
422 // Finally, if the false value simplified to true and the true value to
423 // false, then the result of the compare is equal to "!Cond".
424 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
425 if (Value *V =
426 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
427 TD, DT, MaxRecurse))
428 return V;
429 }
430 }
431
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000432 return 0;
433}
434
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000435/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
436/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
437/// it on the incoming phi values yields the same result for every value. If so
438/// returns the common value, otherwise returns null.
439static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000440 const TargetData *TD, const DominatorTree *DT,
441 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000442 // Recursion is always used, so bail out at once if we already hit the limit.
443 if (!MaxRecurse--)
444 return 0;
445
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000446 PHINode *PI;
447 if (isa<PHINode>(LHS)) {
448 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000449 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
450 if (!ValueDominatesPHI(RHS, PI, DT))
451 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000452 } else {
453 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
454 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000455 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
456 if (!ValueDominatesPHI(LHS, PI, DT))
457 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000458 }
459
460 // Evaluate the BinOp on the incoming phi values.
461 Value *CommonValue = 0;
462 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000463 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000464 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000465 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000466 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000467 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
468 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000469 // If the operation failed to simplify, or simplified to a different value
470 // to previously, then give up.
471 if (!V || (CommonValue && V != CommonValue))
472 return 0;
473 CommonValue = V;
474 }
475
476 return CommonValue;
477}
478
479/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
480/// try to simplify the comparison by seeing whether comparing with all of the
481/// incoming phi values yields the same result every time. If so returns the
482/// common result, otherwise returns null.
483static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000484 const TargetData *TD, const DominatorTree *DT,
485 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000486 // Recursion is always used, so bail out at once if we already hit the limit.
487 if (!MaxRecurse--)
488 return 0;
489
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000490 // Make sure the phi is on the LHS.
491 if (!isa<PHINode>(LHS)) {
492 std::swap(LHS, RHS);
493 Pred = CmpInst::getSwappedPredicate(Pred);
494 }
495 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
496 PHINode *PI = cast<PHINode>(LHS);
497
Duncan Sands18450092010-11-16 12:16:38 +0000498 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
499 if (!ValueDominatesPHI(RHS, PI, DT))
500 return 0;
501
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000502 // Evaluate the BinOp on the incoming phi values.
503 Value *CommonValue = 0;
504 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000505 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000506 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000507 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000508 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000509 // If the operation failed to simplify, or simplified to a different value
510 // to previously, then give up.
511 if (!V || (CommonValue && V != CommonValue))
512 return 0;
513 CommonValue = V;
514 }
515
516 return CommonValue;
517}
518
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000519/// SimplifyAddInst - Given operands for an Add, see if we can
520/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000521static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
522 const TargetData *TD, const DominatorTree *DT,
523 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000524 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
525 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
526 Constant *Ops[] = { CLHS, CRHS };
527 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
528 Ops, 2, TD);
529 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000530
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000531 // Canonicalize the constant to the RHS.
532 std::swap(Op0, Op1);
533 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000534
Duncan Sandsfea3b212010-12-15 14:07:39 +0000535 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000536 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000537 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000538
Duncan Sandsfea3b212010-12-15 14:07:39 +0000539 // X + 0 -> X
540 if (match(Op1, m_Zero()))
541 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000542
Duncan Sandsfea3b212010-12-15 14:07:39 +0000543 // X + (Y - X) -> Y
544 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000545 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000546 Value *Y = 0;
547 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
548 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000549 return Y;
550
551 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000552 if (match(Op0, m_Not(m_Specific(Op1))) ||
553 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000554 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000555
Duncan Sands82fdab32010-12-21 14:00:22 +0000556 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000557 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000558 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
559 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000560
Duncan Sands566edb02010-12-21 08:49:00 +0000561 // Try some generic simplifications for associative operations.
562 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
563 MaxRecurse))
564 return V;
565
Duncan Sands3421d902010-12-21 13:32:22 +0000566 // Mul distributes over Add. Try some generic simplifications based on this.
567 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
568 TD, DT, MaxRecurse))
569 return V;
570
Duncan Sands87689cf2010-11-19 09:20:39 +0000571 // Threading Add over selects and phi nodes is pointless, so don't bother.
572 // Threading over the select in "A + select(cond, B, C)" means evaluating
573 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
574 // only if B and C are equal. If B and C are equal then (since we assume
575 // that operands have already been simplified) "select(cond, B, C)" should
576 // have been simplified to the common value of B and C already. Analysing
577 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
578 // for threading over phi nodes.
579
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000580 return 0;
581}
582
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000583Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
584 const TargetData *TD, const DominatorTree *DT) {
585 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
586}
587
Duncan Sandsfea3b212010-12-15 14:07:39 +0000588/// SimplifySubInst - Given operands for a Sub, see if we can
589/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000590static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000591 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000592 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000593 if (Constant *CLHS = dyn_cast<Constant>(Op0))
594 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
595 Constant *Ops[] = { CLHS, CRHS };
596 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
597 Ops, 2, TD);
598 }
599
600 // X - undef -> undef
601 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000602 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000603 return UndefValue::get(Op0->getType());
604
605 // X - 0 -> X
606 if (match(Op1, m_Zero()))
607 return Op0;
608
609 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000610 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000611 return Constant::getNullValue(Op0->getType());
612
Duncan Sandsfe02c692011-01-18 09:24:58 +0000613 // (X*2) - X -> X
614 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000615 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000616 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
617 match(Op0, m_Shl(m_Specific(Op1), m_One())))
618 return Op1;
619
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000620 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
621 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
622 Value *Y = 0, *Z = Op1;
623 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
624 // See if "V === Y - Z" simplifies.
625 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
626 // It does! Now see if "X + V" simplifies.
627 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
628 MaxRecurse-1)) {
629 // It does, we successfully reassociated!
630 ++NumReassoc;
631 return W;
632 }
633 // See if "V === X - Z" simplifies.
634 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
635 // It does! Now see if "Y + V" simplifies.
636 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
637 MaxRecurse-1)) {
638 // It does, we successfully reassociated!
639 ++NumReassoc;
640 return W;
641 }
642 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000643
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000644 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
645 // For example, X - (X + 1) -> -1
646 X = Op0;
647 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
648 // See if "V === X - Y" simplifies.
649 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
650 // It does! Now see if "V - Z" simplifies.
651 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
652 MaxRecurse-1)) {
653 // It does, we successfully reassociated!
654 ++NumReassoc;
655 return W;
656 }
657 // See if "V === X - Z" simplifies.
658 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
659 // It does! Now see if "V - Y" simplifies.
660 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
661 MaxRecurse-1)) {
662 // It does, we successfully reassociated!
663 ++NumReassoc;
664 return W;
665 }
666 }
667
668 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
669 // For example, X - (X - Y) -> Y.
670 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000671 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
672 // See if "V === Z - X" simplifies.
673 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000674 // It does! Now see if "V + Y" simplifies.
Duncan Sandsc087e202011-01-14 15:26:10 +0000675 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
676 MaxRecurse-1)) {
677 // It does, we successfully reassociated!
678 ++NumReassoc;
679 return W;
680 }
681
Duncan Sands3421d902010-12-21 13:32:22 +0000682 // Mul distributes over Sub. Try some generic simplifications based on this.
683 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
684 TD, DT, MaxRecurse))
685 return V;
686
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000687 // i1 sub -> xor.
688 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
689 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
690 return V;
691
Duncan Sandsfea3b212010-12-15 14:07:39 +0000692 // Threading Sub over selects and phi nodes is pointless, so don't bother.
693 // Threading over the select in "A - select(cond, B, C)" means evaluating
694 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
695 // only if B and C are equal. If B and C are equal then (since we assume
696 // that operands have already been simplified) "select(cond, B, C)" should
697 // have been simplified to the common value of B and C already. Analysing
698 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
699 // for threading over phi nodes.
700
701 return 0;
702}
703
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000704Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
705 const TargetData *TD, const DominatorTree *DT) {
706 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
707}
708
Duncan Sands82fdab32010-12-21 14:00:22 +0000709/// SimplifyMulInst - Given operands for a Mul, see if we can
710/// fold the result. If not, this returns null.
711static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
712 const DominatorTree *DT, unsigned MaxRecurse) {
713 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
714 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
715 Constant *Ops[] = { CLHS, CRHS };
716 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
717 Ops, 2, TD);
718 }
719
720 // Canonicalize the constant to the RHS.
721 std::swap(Op0, Op1);
722 }
723
724 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000725 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000726 return Constant::getNullValue(Op0->getType());
727
728 // X * 0 -> 0
729 if (match(Op1, m_Zero()))
730 return Op1;
731
732 // X * 1 -> X
733 if (match(Op1, m_One()))
734 return Op0;
735
Duncan Sands1895e982011-01-30 18:03:50 +0000736 // (X / Y) * Y -> X if the division is exact.
737 Value *X = 0, *Y = 0;
Chris Lattneraeaf3d42011-02-09 17:00:45 +0000738 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
739 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
Chris Lattnerc6ee9182011-02-06 22:05:31 +0000740 BinaryOperator *Div = cast<BinaryOperator>(Y == Op1 ? Op0 : Op1);
741 if (Div->isExact())
Duncan Sands1895e982011-01-30 18:03:50 +0000742 return X;
743 }
744
Nick Lewycky54138802011-01-29 19:55:23 +0000745 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000746 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000747 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
748 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000749
750 // Try some generic simplifications for associative operations.
751 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
752 MaxRecurse))
753 return V;
754
755 // Mul distributes over Add. Try some generic simplifications based on this.
756 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
757 TD, DT, MaxRecurse))
758 return V;
759
760 // If the operation is with the result of a select instruction, check whether
761 // operating on either branch of the select always yields the same value.
762 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
763 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
764 MaxRecurse))
765 return V;
766
767 // If the operation is with the result of a phi instruction, check whether
768 // operating on all incoming values of the phi always yields the same value.
769 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
770 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
771 MaxRecurse))
772 return V;
773
774 return 0;
775}
776
777Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
778 const DominatorTree *DT) {
779 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
780}
781
Duncan Sands593faa52011-01-28 16:51:11 +0000782/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
783/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000784static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands593faa52011-01-28 16:51:11 +0000785 const TargetData *TD, const DominatorTree *DT,
786 unsigned MaxRecurse) {
787 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
788 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
789 Constant *Ops[] = { C0, C1 };
790 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
791 }
792 }
793
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000794 bool isSigned = Opcode == Instruction::SDiv;
795
Duncan Sands593faa52011-01-28 16:51:11 +0000796 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000797 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000798 return Op1;
799
800 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000801 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000802 return Constant::getNullValue(Op0->getType());
803
804 // 0 / X -> 0, we don't need to preserve faults!
805 if (match(Op0, m_Zero()))
806 return Op0;
807
808 // X / 1 -> X
809 if (match(Op1, m_One()))
810 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000811
812 if (Op0->getType()->isIntegerTy(1))
813 // It can't be division by zero, hence it must be division by one.
814 return Op0;
815
816 // X / X -> 1
817 if (Op0 == Op1)
818 return ConstantInt::get(Op0->getType(), 1);
819
820 // (X * Y) / Y -> X if the multiplication does not overflow.
821 Value *X = 0, *Y = 0;
822 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
823 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands4b720712011-02-02 20:52:00 +0000824 BinaryOperator *Mul = cast<BinaryOperator>(Op0);
825 // If the Mul knows it does not overflow, then we are good to go.
826 if ((isSigned && Mul->hasNoSignedWrap()) ||
827 (!isSigned && Mul->hasNoUnsignedWrap()))
828 return X;
Duncan Sands593faa52011-01-28 16:51:11 +0000829 // If X has the form X = A / Y then X * Y cannot overflow.
830 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
831 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
832 return X;
833 }
834
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000835 // (X rem Y) / Y -> 0
836 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
837 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
838 return Constant::getNullValue(Op0->getType());
839
840 // If the operation is with the result of a select instruction, check whether
841 // operating on either branch of the select always yields the same value.
842 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
843 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
844 return V;
845
846 // If the operation is with the result of a phi instruction, check whether
847 // operating on all incoming values of the phi always yields the same value.
848 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
849 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
850 return V;
851
Duncan Sands593faa52011-01-28 16:51:11 +0000852 return 0;
853}
854
855/// SimplifySDivInst - Given operands for an SDiv, see if we can
856/// fold the result. If not, this returns null.
857static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
858 const DominatorTree *DT, unsigned MaxRecurse) {
859 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
860 return V;
861
Duncan Sands593faa52011-01-28 16:51:11 +0000862 return 0;
863}
864
865Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000866 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000867 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
868}
869
870/// SimplifyUDivInst - Given operands for a UDiv, see if we can
871/// fold the result. If not, this returns null.
872static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
873 const DominatorTree *DT, unsigned MaxRecurse) {
874 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
875 return V;
876
Duncan Sands593faa52011-01-28 16:51:11 +0000877 return 0;
878}
879
880Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000881 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000882 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
883}
884
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000885static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
886 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000887 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000888 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000889 return Op0;
890
891 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000892 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000893 return Op1;
894
895 return 0;
896}
897
898Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
899 const DominatorTree *DT) {
900 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
901}
902
Duncan Sandscf80bc12011-01-14 14:44:12 +0000903/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +0000904/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +0000905static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
906 const TargetData *TD, const DominatorTree *DT,
907 unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +0000908 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
909 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
910 Constant *Ops[] = { C0, C1 };
Duncan Sandscf80bc12011-01-14 14:44:12 +0000911 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
Duncan Sandsc43cee32011-01-14 00:37:45 +0000912 }
913 }
914
Duncan Sandscf80bc12011-01-14 14:44:12 +0000915 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +0000916 if (match(Op0, m_Zero()))
917 return Op0;
918
Duncan Sandscf80bc12011-01-14 14:44:12 +0000919 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +0000920 if (match(Op1, m_Zero()))
921 return Op0;
922
Duncan Sandscf80bc12011-01-14 14:44:12 +0000923 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000924 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +0000925 return Op1;
926
927 // Shifting by the bitwidth or more is undefined.
928 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
929 if (CI->getValue().getLimitedValue() >=
930 Op0->getType()->getScalarSizeInBits())
931 return UndefValue::get(Op0->getType());
932
Duncan Sandscf80bc12011-01-14 14:44:12 +0000933 // If the operation is with the result of a select instruction, check whether
934 // operating on either branch of the select always yields the same value.
935 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
936 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
937 return V;
938
939 // If the operation is with the result of a phi instruction, check whether
940 // operating on all incoming values of the phi always yields the same value.
941 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
942 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
943 return V;
944
945 return 0;
946}
947
948/// SimplifyShlInst - Given operands for an Shl, see if we can
949/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +0000950static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
951 const TargetData *TD, const DominatorTree *DT,
952 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +0000953 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
954 return V;
955
956 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000957 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +0000958 return Constant::getNullValue(Op0->getType());
959
Chris Lattner81a0dc92011-02-09 17:15:04 +0000960 // (X >> A) << A -> X
961 Value *X;
962 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
963 cast<PossiblyExactOperator>(Op0)->isExact())
964 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +0000965 return 0;
966}
967
Chris Lattner81a0dc92011-02-09 17:15:04 +0000968Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
969 const TargetData *TD, const DominatorTree *DT) {
970 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +0000971}
972
973/// SimplifyLShrInst - Given operands for an LShr, see if we can
974/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +0000975static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
976 const TargetData *TD, const DominatorTree *DT,
977 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +0000978 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
979 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +0000980
981 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000982 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +0000983 return Constant::getNullValue(Op0->getType());
984
Chris Lattner81a0dc92011-02-09 17:15:04 +0000985 // (X << A) >> A -> X
986 Value *X;
987 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
988 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
989 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +0000990
Duncan Sandsc43cee32011-01-14 00:37:45 +0000991 return 0;
992}
993
Chris Lattner81a0dc92011-02-09 17:15:04 +0000994Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
995 const TargetData *TD, const DominatorTree *DT) {
996 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +0000997}
998
999/// SimplifyAShrInst - Given operands for an AShr, see if we can
1000/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001001static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1002 const TargetData *TD, const DominatorTree *DT,
1003 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001004 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1005 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001006
1007 // all ones >>a X -> all ones
1008 if (match(Op0, m_AllOnes()))
1009 return Op0;
1010
1011 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001012 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001013 return Constant::getAllOnesValue(Op0->getType());
1014
Chris Lattner81a0dc92011-02-09 17:15:04 +00001015 // (X << A) >> A -> X
1016 Value *X;
1017 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1018 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1019 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001020
Duncan Sandsc43cee32011-01-14 00:37:45 +00001021 return 0;
1022}
1023
Chris Lattner81a0dc92011-02-09 17:15:04 +00001024Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1025 const TargetData *TD, const DominatorTree *DT) {
1026 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001027}
1028
Chris Lattnerd06094f2009-11-10 00:55:12 +00001029/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001030/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001031static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001032 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001033 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1034 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1035 Constant *Ops[] = { CLHS, CRHS };
1036 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1037 Ops, 2, TD);
1038 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001039
Chris Lattnerd06094f2009-11-10 00:55:12 +00001040 // Canonicalize the constant to the RHS.
1041 std::swap(Op0, Op1);
1042 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001043
Chris Lattnerd06094f2009-11-10 00:55:12 +00001044 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001045 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001046 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001047
Chris Lattnerd06094f2009-11-10 00:55:12 +00001048 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001049 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001050 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001051
Duncan Sands2b749872010-11-17 18:52:15 +00001052 // X & 0 = 0
1053 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001054 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001055
Duncan Sands2b749872010-11-17 18:52:15 +00001056 // X & -1 = X
1057 if (match(Op1, m_AllOnes()))
1058 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001059
Chris Lattnerd06094f2009-11-10 00:55:12 +00001060 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001061 if (match(Op0, m_Not(m_Specific(Op1))) ||
1062 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001063 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001064
Chris Lattnerd06094f2009-11-10 00:55:12 +00001065 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001066 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001067 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001068 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001069 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001070
Chris Lattnerd06094f2009-11-10 00:55:12 +00001071 // A & (A | ?) = A
1072 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001073 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001074 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001075
Duncan Sands566edb02010-12-21 08:49:00 +00001076 // Try some generic simplifications for associative operations.
1077 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1078 MaxRecurse))
1079 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001080
Duncan Sands3421d902010-12-21 13:32:22 +00001081 // And distributes over Or. Try some generic simplifications based on this.
1082 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1083 TD, DT, MaxRecurse))
1084 return V;
1085
1086 // And distributes over Xor. Try some generic simplifications based on this.
1087 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1088 TD, DT, MaxRecurse))
1089 return V;
1090
1091 // Or distributes over And. Try some generic simplifications based on this.
1092 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1093 TD, DT, MaxRecurse))
1094 return V;
1095
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001096 // If the operation is with the result of a select instruction, check whether
1097 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001098 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001099 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001100 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001101 return V;
1102
1103 // If the operation is with the result of a phi instruction, check whether
1104 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001105 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001106 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001107 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001108 return V;
1109
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001110 return 0;
1111}
1112
Duncan Sands18450092010-11-16 12:16:38 +00001113Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1114 const DominatorTree *DT) {
1115 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001116}
1117
Chris Lattnerd06094f2009-11-10 00:55:12 +00001118/// SimplifyOrInst - Given operands for an Or, see if we can
1119/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001120static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001121 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001122 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1123 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1124 Constant *Ops[] = { CLHS, CRHS };
1125 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1126 Ops, 2, TD);
1127 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001128
Chris Lattnerd06094f2009-11-10 00:55:12 +00001129 // Canonicalize the constant to the RHS.
1130 std::swap(Op0, Op1);
1131 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001132
Chris Lattnerd06094f2009-11-10 00:55:12 +00001133 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001134 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001135 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001136
Chris Lattnerd06094f2009-11-10 00:55:12 +00001137 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001138 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001139 return Op0;
1140
Duncan Sands2b749872010-11-17 18:52:15 +00001141 // X | 0 = X
1142 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001143 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001144
Duncan Sands2b749872010-11-17 18:52:15 +00001145 // X | -1 = -1
1146 if (match(Op1, m_AllOnes()))
1147 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001148
Chris Lattnerd06094f2009-11-10 00:55:12 +00001149 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001150 if (match(Op0, m_Not(m_Specific(Op1))) ||
1151 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001152 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001153
Chris Lattnerd06094f2009-11-10 00:55:12 +00001154 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001155 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001156 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001157 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001158 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001159
Chris Lattnerd06094f2009-11-10 00:55:12 +00001160 // A | (A & ?) = A
1161 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001162 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001163 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001164
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001165 // ~(A & ?) | A = -1
1166 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1167 (A == Op1 || B == Op1))
1168 return Constant::getAllOnesValue(Op1->getType());
1169
1170 // A | ~(A & ?) = -1
1171 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1172 (A == Op0 || B == Op0))
1173 return Constant::getAllOnesValue(Op0->getType());
1174
Duncan Sands566edb02010-12-21 08:49:00 +00001175 // Try some generic simplifications for associative operations.
1176 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1177 MaxRecurse))
1178 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001179
Duncan Sands3421d902010-12-21 13:32:22 +00001180 // Or distributes over And. Try some generic simplifications based on this.
1181 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1182 TD, DT, MaxRecurse))
1183 return V;
1184
1185 // And distributes over Or. Try some generic simplifications based on this.
1186 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1187 TD, DT, 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>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001193 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, 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>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001200 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001201 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001202 return V;
1203
Chris Lattnerd06094f2009-11-10 00:55:12 +00001204 return 0;
1205}
1206
Duncan Sands18450092010-11-16 12:16:38 +00001207Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1208 const DominatorTree *DT) {
1209 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001210}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001211
Duncan Sands2b749872010-11-17 18:52:15 +00001212/// SimplifyXorInst - Given operands for a Xor, see if we can
1213/// fold the result. If not, this returns null.
1214static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1215 const DominatorTree *DT, unsigned MaxRecurse) {
1216 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1217 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1218 Constant *Ops[] = { CLHS, CRHS };
1219 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1220 Ops, 2, TD);
1221 }
1222
1223 // Canonicalize the constant to the RHS.
1224 std::swap(Op0, Op1);
1225 }
1226
1227 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001228 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001229 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001230
1231 // A ^ 0 = A
1232 if (match(Op1, m_Zero()))
1233 return Op0;
1234
1235 // A ^ A = 0
Duncan Sands124708d2011-01-01 20:08:02 +00001236 if (Op0 == Op1)
Duncan Sands2b749872010-11-17 18:52:15 +00001237 return Constant::getNullValue(Op0->getType());
1238
1239 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001240 if (match(Op0, m_Not(m_Specific(Op1))) ||
1241 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001242 return Constant::getAllOnesValue(Op0->getType());
1243
Duncan Sands566edb02010-12-21 08:49:00 +00001244 // Try some generic simplifications for associative operations.
1245 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1246 MaxRecurse))
1247 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001248
Duncan Sands3421d902010-12-21 13:32:22 +00001249 // And distributes over Xor. Try some generic simplifications based on this.
1250 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1251 TD, DT, MaxRecurse))
1252 return V;
1253
Duncan Sands87689cf2010-11-19 09:20:39 +00001254 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1255 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1256 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1257 // only if B and C are equal. If B and C are equal then (since we assume
1258 // that operands have already been simplified) "select(cond, B, C)" should
1259 // have been simplified to the common value of B and C already. Analysing
1260 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1261 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001262
1263 return 0;
1264}
1265
1266Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1267 const DominatorTree *DT) {
1268 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1269}
1270
Chris Lattner210c5d42009-11-09 23:55:12 +00001271static const Type *GetCompareTy(Value *Op) {
1272 return CmpInst::makeCmpResultType(Op->getType());
1273}
1274
Chris Lattner9dbb4292009-11-09 23:28:39 +00001275/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1276/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001277static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001278 const TargetData *TD, const DominatorTree *DT,
1279 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001280 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001281 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001282
Chris Lattnerd06094f2009-11-10 00:55:12 +00001283 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001284 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1285 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001286
1287 // If we have a constant, make sure it is on the RHS.
1288 std::swap(LHS, RHS);
1289 Pred = CmpInst::getSwappedPredicate(Pred);
1290 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001291
Duncan Sands6dc91252011-01-13 08:56:29 +00001292 const Type *ITy = GetCompareTy(LHS); // The return type.
1293 const Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001294
Chris Lattner210c5d42009-11-09 23:55:12 +00001295 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001296 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1297 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001298 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001299 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001300
Duncan Sands6dc91252011-01-13 08:56:29 +00001301 // Special case logic when the operands have i1 type.
1302 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1303 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1304 switch (Pred) {
1305 default: break;
1306 case ICmpInst::ICMP_EQ:
1307 // X == 1 -> X
1308 if (match(RHS, m_One()))
1309 return LHS;
1310 break;
1311 case ICmpInst::ICMP_NE:
1312 // X != 0 -> X
1313 if (match(RHS, m_Zero()))
1314 return LHS;
1315 break;
1316 case ICmpInst::ICMP_UGT:
1317 // X >u 0 -> X
1318 if (match(RHS, m_Zero()))
1319 return LHS;
1320 break;
1321 case ICmpInst::ICMP_UGE:
1322 // X >=u 1 -> X
1323 if (match(RHS, m_One()))
1324 return LHS;
1325 break;
1326 case ICmpInst::ICMP_SLT:
1327 // X <s 0 -> X
1328 if (match(RHS, m_Zero()))
1329 return LHS;
1330 break;
1331 case ICmpInst::ICMP_SLE:
1332 // X <=s -1 -> X
1333 if (match(RHS, m_One()))
1334 return LHS;
1335 break;
1336 }
1337 }
1338
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001339 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1340 // different addresses, and what's more the address of a stack variable is
1341 // never null or equal to the address of a global. Note that generalizing
1342 // to the case where LHS is a global variable address or null is pointless,
1343 // since if both LHS and RHS are constants then we already constant folded
1344 // the compare, and if only one of them is then we moved it to RHS already.
1345 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1346 isa<ConstantPointerNull>(RHS)))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001347 // We already know that LHS != RHS.
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001348 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1349
1350 // If we are comparing with zero then try hard since this is a common case.
1351 if (match(RHS, m_Zero())) {
1352 bool LHSKnownNonNegative, LHSKnownNegative;
1353 switch (Pred) {
1354 default:
1355 assert(false && "Unknown ICmp predicate!");
1356 case ICmpInst::ICMP_ULT:
1357 return ConstantInt::getFalse(LHS->getContext());
1358 case ICmpInst::ICMP_UGE:
1359 return ConstantInt::getTrue(LHS->getContext());
1360 case ICmpInst::ICMP_EQ:
1361 case ICmpInst::ICMP_ULE:
1362 if (isKnownNonZero(LHS, TD))
1363 return ConstantInt::getFalse(LHS->getContext());
1364 break;
1365 case ICmpInst::ICMP_NE:
1366 case ICmpInst::ICMP_UGT:
1367 if (isKnownNonZero(LHS, TD))
1368 return ConstantInt::getTrue(LHS->getContext());
1369 break;
1370 case ICmpInst::ICMP_SLT:
1371 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1372 if (LHSKnownNegative)
1373 return ConstantInt::getTrue(LHS->getContext());
1374 if (LHSKnownNonNegative)
1375 return ConstantInt::getFalse(LHS->getContext());
1376 break;
1377 case ICmpInst::ICMP_SLE:
1378 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1379 if (LHSKnownNegative)
1380 return ConstantInt::getTrue(LHS->getContext());
1381 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1382 return ConstantInt::getFalse(LHS->getContext());
1383 break;
1384 case ICmpInst::ICMP_SGE:
1385 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1386 if (LHSKnownNegative)
1387 return ConstantInt::getFalse(LHS->getContext());
1388 if (LHSKnownNonNegative)
1389 return ConstantInt::getTrue(LHS->getContext());
1390 break;
1391 case ICmpInst::ICMP_SGT:
1392 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1393 if (LHSKnownNegative)
1394 return ConstantInt::getFalse(LHS->getContext());
1395 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1396 return ConstantInt::getTrue(LHS->getContext());
1397 break;
1398 }
1399 }
1400
1401 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001402 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001403 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1404 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1405 if (RHS_CR.isEmptySet())
1406 return ConstantInt::getFalse(CI->getContext());
1407 if (RHS_CR.isFullSet())
1408 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001409
Nick Lewycky3a73e342011-03-04 07:00:57 +00001410 // Many binary operators with constant RHS have easy to compute constant
1411 // range. Use them to check whether the comparison is a tautology.
1412 uint32_t Width = CI->getBitWidth();
1413 APInt Lower = APInt(Width, 0);
1414 APInt Upper = APInt(Width, 0);
1415 ConstantInt *CI2;
1416 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1417 // 'urem x, CI2' produces [0, CI2).
1418 Upper = CI2->getValue();
1419 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1420 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1421 Upper = CI2->getValue().abs();
1422 Lower = (-Upper) + 1;
1423 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1424 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1425 APInt NegOne = APInt::getAllOnesValue(Width);
1426 if (!CI2->isZero())
1427 Upper = NegOne.udiv(CI2->getValue()) + 1;
1428 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1429 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1430 APInt IntMin = APInt::getSignedMinValue(Width);
1431 APInt IntMax = APInt::getSignedMaxValue(Width);
1432 APInt Val = CI2->getValue().abs();
1433 if (!Val.isMinValue()) {
1434 Lower = IntMin.sdiv(Val);
1435 Upper = IntMax.sdiv(Val) + 1;
1436 }
1437 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1438 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1439 APInt NegOne = APInt::getAllOnesValue(Width);
1440 if (CI2->getValue().ult(Width))
1441 Upper = NegOne.lshr(CI2->getValue()) + 1;
1442 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1443 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1444 APInt IntMin = APInt::getSignedMinValue(Width);
1445 APInt IntMax = APInt::getSignedMaxValue(Width);
1446 if (CI2->getValue().ult(Width)) {
1447 Lower = IntMin.ashr(CI2->getValue());
1448 Upper = IntMax.ashr(CI2->getValue()) + 1;
1449 }
1450 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1451 // 'or x, CI2' produces [CI2, UINT_MAX].
1452 Lower = CI2->getValue();
1453 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1454 // 'and x, CI2' produces [0, CI2].
1455 Upper = CI2->getValue() + 1;
1456 }
1457 if (Lower != Upper) {
1458 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1459 if (RHS_CR.contains(LHS_CR))
1460 return ConstantInt::getTrue(RHS->getContext());
1461 if (RHS_CR.inverse().contains(LHS_CR))
1462 return ConstantInt::getFalse(RHS->getContext());
1463 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001464 }
1465
Duncan Sands9d32f602011-01-20 13:21:55 +00001466 // Compare of cast, for example (zext X) != 0 -> X != 0
1467 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1468 Instruction *LI = cast<CastInst>(LHS);
1469 Value *SrcOp = LI->getOperand(0);
1470 const Type *SrcTy = SrcOp->getType();
1471 const Type *DstTy = LI->getType();
1472
1473 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1474 // if the integer type is the same size as the pointer type.
1475 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1476 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1477 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1478 // Transfer the cast to the constant.
1479 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1480 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1481 TD, DT, MaxRecurse-1))
1482 return V;
1483 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1484 if (RI->getOperand(0)->getType() == SrcTy)
1485 // Compare without the cast.
1486 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1487 TD, DT, MaxRecurse-1))
1488 return V;
1489 }
1490 }
1491
1492 if (isa<ZExtInst>(LHS)) {
1493 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1494 // same type.
1495 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1496 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1497 // Compare X and Y. Note that signed predicates become unsigned.
1498 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1499 SrcOp, RI->getOperand(0), TD, DT,
1500 MaxRecurse-1))
1501 return V;
1502 }
1503 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1504 // too. If not, then try to deduce the result of the comparison.
1505 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1506 // Compute the constant that would happen if we truncated to SrcTy then
1507 // reextended to DstTy.
1508 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1509 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1510
1511 // If the re-extended constant didn't change then this is effectively
1512 // also a case of comparing two zero-extended values.
1513 if (RExt == CI && MaxRecurse)
1514 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1515 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1516 return V;
1517
1518 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1519 // there. Use this to work out the result of the comparison.
1520 if (RExt != CI) {
1521 switch (Pred) {
1522 default:
1523 assert(false && "Unknown ICmp predicate!");
1524 // LHS <u RHS.
1525 case ICmpInst::ICMP_EQ:
1526 case ICmpInst::ICMP_UGT:
1527 case ICmpInst::ICMP_UGE:
1528 return ConstantInt::getFalse(CI->getContext());
1529
1530 case ICmpInst::ICMP_NE:
1531 case ICmpInst::ICMP_ULT:
1532 case ICmpInst::ICMP_ULE:
1533 return ConstantInt::getTrue(CI->getContext());
1534
1535 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1536 // is non-negative then LHS <s RHS.
1537 case ICmpInst::ICMP_SGT:
1538 case ICmpInst::ICMP_SGE:
1539 return CI->getValue().isNegative() ?
1540 ConstantInt::getTrue(CI->getContext()) :
1541 ConstantInt::getFalse(CI->getContext());
1542
1543 case ICmpInst::ICMP_SLT:
1544 case ICmpInst::ICMP_SLE:
1545 return CI->getValue().isNegative() ?
1546 ConstantInt::getFalse(CI->getContext()) :
1547 ConstantInt::getTrue(CI->getContext());
1548 }
1549 }
1550 }
1551 }
1552
1553 if (isa<SExtInst>(LHS)) {
1554 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1555 // same type.
1556 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1557 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1558 // Compare X and Y. Note that the predicate does not change.
1559 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1560 TD, DT, MaxRecurse-1))
1561 return V;
1562 }
1563 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1564 // too. If not, then try to deduce the result of the comparison.
1565 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1566 // Compute the constant that would happen if we truncated to SrcTy then
1567 // reextended to DstTy.
1568 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1569 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1570
1571 // If the re-extended constant didn't change then this is effectively
1572 // also a case of comparing two sign-extended values.
1573 if (RExt == CI && MaxRecurse)
1574 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1575 MaxRecurse-1))
1576 return V;
1577
1578 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1579 // bits there. Use this to work out the result of the comparison.
1580 if (RExt != CI) {
1581 switch (Pred) {
1582 default:
1583 assert(false && "Unknown ICmp predicate!");
1584 case ICmpInst::ICMP_EQ:
1585 return ConstantInt::getFalse(CI->getContext());
1586 case ICmpInst::ICMP_NE:
1587 return ConstantInt::getTrue(CI->getContext());
1588
1589 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1590 // LHS >s RHS.
1591 case ICmpInst::ICMP_SGT:
1592 case ICmpInst::ICMP_SGE:
1593 return CI->getValue().isNegative() ?
1594 ConstantInt::getTrue(CI->getContext()) :
1595 ConstantInt::getFalse(CI->getContext());
1596 case ICmpInst::ICMP_SLT:
1597 case ICmpInst::ICMP_SLE:
1598 return CI->getValue().isNegative() ?
1599 ConstantInt::getFalse(CI->getContext()) :
1600 ConstantInt::getTrue(CI->getContext());
1601
1602 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1603 // LHS >u RHS.
1604 case ICmpInst::ICMP_UGT:
1605 case ICmpInst::ICMP_UGE:
1606 // Comparison is true iff the LHS <s 0.
1607 if (MaxRecurse)
1608 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1609 Constant::getNullValue(SrcTy),
1610 TD, DT, MaxRecurse-1))
1611 return V;
1612 break;
1613 case ICmpInst::ICMP_ULT:
1614 case ICmpInst::ICMP_ULE:
1615 // Comparison is true iff the LHS >=s 0.
1616 if (MaxRecurse)
1617 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1618 Constant::getNullValue(SrcTy),
1619 TD, DT, MaxRecurse-1))
1620 return V;
1621 break;
1622 }
1623 }
1624 }
1625 }
1626 }
1627
Duncan Sands52fb8462011-02-13 17:15:40 +00001628 // Special logic for binary operators.
1629 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1630 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1631 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001632 // Analyze the case when either LHS or RHS is an add instruction.
1633 Value *A = 0, *B = 0, *C = 0, *D = 0;
1634 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1635 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1636 if (LBO && LBO->getOpcode() == Instruction::Add) {
1637 A = LBO->getOperand(0); B = LBO->getOperand(1);
1638 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1639 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1640 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1641 }
1642 if (RBO && RBO->getOpcode() == Instruction::Add) {
1643 C = RBO->getOperand(0); D = RBO->getOperand(1);
1644 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1645 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1646 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1647 }
1648
1649 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1650 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1651 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1652 Constant::getNullValue(RHS->getType()),
1653 TD, DT, MaxRecurse-1))
1654 return V;
1655
1656 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1657 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1658 if (Value *V = SimplifyICmpInst(Pred,
1659 Constant::getNullValue(LHS->getType()),
1660 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1661 return V;
1662
1663 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1664 if (A && C && (A == C || A == D || B == C || B == D) &&
1665 NoLHSWrapProblem && NoRHSWrapProblem) {
1666 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1667 Value *Y = (A == C || A == D) ? B : A;
1668 Value *Z = (C == A || C == B) ? D : C;
1669 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1670 return V;
1671 }
1672 }
1673
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001674 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00001675 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001676 switch (Pred) {
1677 default:
1678 break;
Nick Lewycky78679272011-03-04 10:06:52 +00001679 case ICmpInst::ICMP_SGT:
1680 case ICmpInst::ICMP_SGE:
1681 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1682 if (!KnownNonNegative)
1683 break;
1684 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001685 case ICmpInst::ICMP_EQ:
1686 case ICmpInst::ICMP_UGT:
1687 case ICmpInst::ICMP_UGE:
1688 return ConstantInt::getFalse(RHS->getContext());
Nick Lewycky78679272011-03-04 10:06:52 +00001689 case ICmpInst::ICMP_SLT:
1690 case ICmpInst::ICMP_SLE:
1691 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1692 if (!KnownNonNegative)
1693 break;
1694 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001695 case ICmpInst::ICMP_NE:
1696 case ICmpInst::ICMP_ULT:
1697 case ICmpInst::ICMP_ULE:
1698 return ConstantInt::getTrue(RHS->getContext());
1699 }
1700 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001701 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1702 bool KnownNonNegative, KnownNegative;
1703 switch (Pred) {
1704 default:
1705 break;
1706 case ICmpInst::ICMP_SGT:
1707 case ICmpInst::ICMP_SGE:
1708 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1709 if (!KnownNonNegative)
1710 break;
1711 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001712 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001713 case ICmpInst::ICMP_UGT:
1714 case ICmpInst::ICMP_UGE:
1715 return ConstantInt::getTrue(RHS->getContext());
1716 case ICmpInst::ICMP_SLT:
1717 case ICmpInst::ICMP_SLE:
1718 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1719 if (!KnownNonNegative)
1720 break;
1721 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001722 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001723 case ICmpInst::ICMP_ULT:
1724 case ICmpInst::ICMP_ULE:
1725 return ConstantInt::getFalse(RHS->getContext());
1726 }
1727 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001728
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001729 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1730 LBO->getOperand(1) == RBO->getOperand(1)) {
1731 switch (LBO->getOpcode()) {
1732 default: break;
1733 case Instruction::UDiv:
1734 case Instruction::LShr:
1735 if (ICmpInst::isSigned(Pred))
1736 break;
1737 // fall-through
1738 case Instruction::SDiv:
1739 case Instruction::AShr:
1740 if (!LBO->isExact() && !RBO->isExact())
1741 break;
1742 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1743 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1744 return V;
1745 break;
1746 case Instruction::Shl: {
1747 bool NUW = LBO->hasNoUnsignedWrap() && LBO->hasNoUnsignedWrap();
1748 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1749 if (!NUW && !NSW)
1750 break;
1751 if (!NSW && ICmpInst::isSigned(Pred))
1752 break;
1753 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1754 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1755 return V;
1756 break;
1757 }
1758 }
1759 }
1760
Duncan Sands1ac7c992010-11-07 16:12:23 +00001761 // If the comparison is with the result of a select instruction, check whether
1762 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001763 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1764 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001765 return V;
1766
1767 // If the comparison is with the result of a phi instruction, check whether
1768 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001769 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1770 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001771 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00001772
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001773 return 0;
1774}
1775
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001776Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001777 const TargetData *TD, const DominatorTree *DT) {
1778 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001779}
1780
Chris Lattner9dbb4292009-11-09 23:28:39 +00001781/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1782/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001783static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001784 const TargetData *TD, const DominatorTree *DT,
1785 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001786 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1787 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1788
Chris Lattnerd06094f2009-11-10 00:55:12 +00001789 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001790 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1791 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00001792
Chris Lattnerd06094f2009-11-10 00:55:12 +00001793 // If we have a constant, make sure it is on the RHS.
1794 std::swap(LHS, RHS);
1795 Pred = CmpInst::getSwappedPredicate(Pred);
1796 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001797
Chris Lattner210c5d42009-11-09 23:55:12 +00001798 // Fold trivial predicates.
1799 if (Pred == FCmpInst::FCMP_FALSE)
1800 return ConstantInt::get(GetCompareTy(LHS), 0);
1801 if (Pred == FCmpInst::FCMP_TRUE)
1802 return ConstantInt::get(GetCompareTy(LHS), 1);
1803
Chris Lattner210c5d42009-11-09 23:55:12 +00001804 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1805 return UndefValue::get(GetCompareTy(LHS));
1806
1807 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00001808 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001809 if (CmpInst::isTrueWhenEqual(Pred))
1810 return ConstantInt::get(GetCompareTy(LHS), 1);
1811 if (CmpInst::isFalseWhenEqual(Pred))
1812 return ConstantInt::get(GetCompareTy(LHS), 0);
1813 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001814
Chris Lattner210c5d42009-11-09 23:55:12 +00001815 // Handle fcmp with constant RHS
1816 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1817 // If the constant is a nan, see if we can fold the comparison based on it.
1818 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1819 if (CFP->getValueAPF().isNaN()) {
1820 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1821 return ConstantInt::getFalse(CFP->getContext());
1822 assert(FCmpInst::isUnordered(Pred) &&
1823 "Comparison must be either ordered or unordered!");
1824 // True if unordered.
1825 return ConstantInt::getTrue(CFP->getContext());
1826 }
Dan Gohman6b617a72010-02-22 04:06:03 +00001827 // Check whether the constant is an infinity.
1828 if (CFP->getValueAPF().isInfinity()) {
1829 if (CFP->getValueAPF().isNegative()) {
1830 switch (Pred) {
1831 case FCmpInst::FCMP_OLT:
1832 // No value is ordered and less than negative infinity.
1833 return ConstantInt::getFalse(CFP->getContext());
1834 case FCmpInst::FCMP_UGE:
1835 // All values are unordered with or at least negative infinity.
1836 return ConstantInt::getTrue(CFP->getContext());
1837 default:
1838 break;
1839 }
1840 } else {
1841 switch (Pred) {
1842 case FCmpInst::FCMP_OGT:
1843 // No value is ordered and greater than infinity.
1844 return ConstantInt::getFalse(CFP->getContext());
1845 case FCmpInst::FCMP_ULE:
1846 // All values are unordered with and at most infinity.
1847 return ConstantInt::getTrue(CFP->getContext());
1848 default:
1849 break;
1850 }
1851 }
1852 }
Chris Lattner210c5d42009-11-09 23:55:12 +00001853 }
1854 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001855
Duncan Sands92826de2010-11-07 16:46:25 +00001856 // If the comparison is with the result of a select instruction, check whether
1857 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001858 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1859 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001860 return V;
1861
1862 // If the comparison is with the result of a phi instruction, check whether
1863 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001864 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1865 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001866 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00001867
Chris Lattner9dbb4292009-11-09 23:28:39 +00001868 return 0;
1869}
1870
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001871Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001872 const TargetData *TD, const DominatorTree *DT) {
1873 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001874}
1875
Chris Lattner04754262010-04-20 05:32:14 +00001876/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1877/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00001878Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1879 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00001880 // select true, X, Y -> X
1881 // select false, X, Y -> Y
1882 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1883 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001884
Chris Lattner04754262010-04-20 05:32:14 +00001885 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00001886 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00001887 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001888
Chris Lattner04754262010-04-20 05:32:14 +00001889 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1890 return FalseVal;
1891 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1892 return TrueVal;
1893 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1894 if (isa<Constant>(TrueVal))
1895 return TrueVal;
1896 return FalseVal;
1897 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001898
Chris Lattner04754262010-04-20 05:32:14 +00001899 return 0;
1900}
1901
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001902/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1903/// fold the result. If not, this returns null.
1904Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00001905 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001906 // The type of the GEP pointer operand.
1907 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1908
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001909 // getelementptr P -> P.
1910 if (NumOps == 1)
1911 return Ops[0];
1912
Duncan Sands85bbff62010-11-22 13:42:49 +00001913 if (isa<UndefValue>(Ops[0])) {
1914 // Compute the (pointer) type returned by the GEP instruction.
1915 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1916 NumOps-1);
1917 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1918 return UndefValue::get(GEPTy);
1919 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001920
Duncan Sandse60d79f2010-11-21 13:53:09 +00001921 if (NumOps == 2) {
1922 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001923 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1924 if (C->isZero())
1925 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00001926 // getelementptr P, N -> P if P points to a type of zero size.
1927 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001928 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00001929 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00001930 return Ops[0];
1931 }
1932 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001933
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001934 // Check to see if this is constant foldable.
1935 for (unsigned i = 0; i != NumOps; ++i)
1936 if (!isa<Constant>(Ops[i]))
1937 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001938
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001939 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1940 (Constant *const*)Ops+1, NumOps-1);
1941}
1942
Duncan Sandsff103412010-11-17 04:30:22 +00001943/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1944static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1945 // If all of the PHI's incoming values are the same then replace the PHI node
1946 // with the common value.
1947 Value *CommonValue = 0;
1948 bool HasUndefInput = false;
1949 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1950 Value *Incoming = PN->getIncomingValue(i);
1951 // If the incoming value is the phi node itself, it can safely be skipped.
1952 if (Incoming == PN) continue;
1953 if (isa<UndefValue>(Incoming)) {
1954 // Remember that we saw an undef value, but otherwise ignore them.
1955 HasUndefInput = true;
1956 continue;
1957 }
1958 if (CommonValue && Incoming != CommonValue)
1959 return 0; // Not the same, bail out.
1960 CommonValue = Incoming;
1961 }
1962
1963 // If CommonValue is null then all of the incoming values were either undef or
1964 // equal to the phi node itself.
1965 if (!CommonValue)
1966 return UndefValue::get(PN->getType());
1967
1968 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1969 // instruction, we cannot return X as the result of the PHI node unless it
1970 // dominates the PHI block.
1971 if (HasUndefInput)
1972 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1973
1974 return CommonValue;
1975}
1976
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001977
Chris Lattnerd06094f2009-11-10 00:55:12 +00001978//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00001979
Chris Lattnerd06094f2009-11-10 00:55:12 +00001980/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1981/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001982static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001983 const TargetData *TD, const DominatorTree *DT,
1984 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001985 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00001986 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00001987 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001988 TD, DT, MaxRecurse);
1989 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00001990 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001991 TD, DT, MaxRecurse);
1992 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands593faa52011-01-28 16:51:11 +00001993 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
1994 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001995 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00001996 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00001997 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001998 TD, DT, MaxRecurse);
1999 case Instruction::LShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002000 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002001 case Instruction::AShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002002 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002003 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002004 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002005 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002006 default:
2007 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2008 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2009 Constant *COps[] = {CLHS, CRHS};
2010 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
2011 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002012
Duncan Sands566edb02010-12-21 08:49:00 +00002013 // If the operation is associative, try some generic simplifications.
2014 if (Instruction::isAssociative(Opcode))
2015 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2016 MaxRecurse))
2017 return V;
2018
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002019 // If the operation is with the result of a select instruction, check whether
2020 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002021 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00002022 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002023 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002024 return V;
2025
2026 // If the operation is with the result of a phi instruction, check whether
2027 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002028 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2029 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002030 return V;
2031
Chris Lattnerd06094f2009-11-10 00:55:12 +00002032 return 0;
2033 }
2034}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002035
Duncan Sands12a86f52010-11-14 11:23:23 +00002036Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002037 const TargetData *TD, const DominatorTree *DT) {
2038 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002039}
2040
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002041/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2042/// fold the result.
2043static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002044 const TargetData *TD, const DominatorTree *DT,
2045 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002046 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00002047 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2048 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002049}
2050
2051Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002052 const TargetData *TD, const DominatorTree *DT) {
2053 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002054}
Chris Lattnere3453782009-11-10 01:08:51 +00002055
2056/// SimplifyInstruction - See if we can compute a simplified version of this
2057/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002058Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2059 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002060 Value *Result;
2061
Chris Lattnere3453782009-11-10 01:08:51 +00002062 switch (I->getOpcode()) {
2063 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002064 Result = ConstantFoldInstruction(I, TD);
2065 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002066 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002067 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2068 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2069 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2070 TD, DT);
2071 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002072 case Instruction::Sub:
2073 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2074 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2075 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2076 TD, DT);
2077 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002078 case Instruction::Mul:
2079 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2080 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002081 case Instruction::SDiv:
2082 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2083 break;
2084 case Instruction::UDiv:
2085 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2086 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002087 case Instruction::FDiv:
2088 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2089 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002090 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002091 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2092 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2093 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2094 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002095 break;
2096 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002097 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2098 cast<BinaryOperator>(I)->isExact(),
2099 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002100 break;
2101 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002102 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2103 cast<BinaryOperator>(I)->isExact(),
2104 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002105 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002106 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002107 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2108 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002109 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002110 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2111 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002112 case Instruction::Xor:
2113 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2114 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002115 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002116 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2117 I->getOperand(0), I->getOperand(1), TD, DT);
2118 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002119 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002120 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2121 I->getOperand(0), I->getOperand(1), TD, DT);
2122 break;
Chris Lattner04754262010-04-20 05:32:14 +00002123 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002124 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2125 I->getOperand(2), TD, DT);
2126 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002127 case Instruction::GetElementPtr: {
2128 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00002129 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
2130 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002131 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002132 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002133 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2134 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002135 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002136
2137 /// If called on unreachable code, the above logic may report that the
2138 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002139 /// detecting that case here, returning a safe value instead.
2140 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002141}
2142
Chris Lattner40d8c282009-11-10 22:26:15 +00002143/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2144/// delete the From instruction. In addition to a basic RAUW, this does a
2145/// recursive simplification of the newly formed instructions. This catches
2146/// things where one simplification exposes other opportunities. This only
2147/// simplifies and deletes scalar operations, it does not change the CFG.
2148///
2149void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002150 const TargetData *TD,
2151 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002152 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002153
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002154 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2155 // we can know if it gets deleted out from under us or replaced in a
2156 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002157 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002158 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002159
Chris Lattner40d8c282009-11-10 22:26:15 +00002160 while (!From->use_empty()) {
2161 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002162 Use &TheUse = From->use_begin().getUse();
2163 Instruction *User = cast<Instruction>(TheUse.getUser());
2164 TheUse = To;
2165
2166 // Check to see if the instruction can be folded due to the operand
2167 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2168 // the 'or' with -1.
2169 Value *SimplifiedVal;
2170 {
2171 // Sanity check to make sure 'User' doesn't dangle across
2172 // SimplifyInstruction.
2173 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002174
Duncan Sandseff05812010-11-14 18:36:10 +00002175 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002176 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002177 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002178
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002179 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00002180 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002181 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2182 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002183
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002184 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002185
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002186 // If the recursive simplification ended up revisiting and deleting
2187 // 'From' then we're done.
2188 if (From == 0)
2189 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002190 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002191
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002192 // If 'From' has value handles referring to it, do a real RAUW to update them.
2193 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002194
Chris Lattner40d8c282009-11-10 22:26:15 +00002195 From->eraseFromParent();
2196}