blob: 7c43a9d5c3d094801db33526121e1bd91827a3d2 [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"
Jay Foad562b84b2011-04-11 09:35:34 +000021#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000022#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000023#include "llvm/Analysis/InstructionSimplify.h"
24#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000025#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000026#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000027#include "llvm/Support/ConstantRange.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000028#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000029#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000030#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000031using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000032using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000033
Chris Lattner81a0dc92011-02-09 17:15:04 +000034enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000035
Duncan Sandsa3c44a52010-12-22 09:40:51 +000036STATISTIC(NumExpand, "Number of expansions");
37STATISTIC(NumFactor , "Number of factorizations");
38STATISTIC(NumReassoc, "Number of reassociations");
39
Duncan Sands82fdab32010-12-21 14:00:22 +000040static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000042static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000043 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000044static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000045 const DominatorTree *, unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000046static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
47 const DominatorTree *, unsigned);
48static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
49 const DominatorTree *, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000050
51/// ValueDominatesPHI - Does the given value dominate the specified phi node?
52static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
53 Instruction *I = dyn_cast<Instruction>(V);
54 if (!I)
55 // Arguments and constants dominate all instructions.
56 return true;
57
58 // If we have a DominatorTree then do a precise test.
59 if (DT)
60 return DT->dominates(I, P);
61
62 // Otherwise, if the instruction is in the entry block, and is not an invoke,
63 // then it obviously dominates all phi nodes.
64 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
65 !isa<InvokeInst>(I))
66 return true;
67
68 return false;
69}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000070
Duncan Sands3421d902010-12-21 13:32:22 +000071/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
72/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
73/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
74/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
75/// Returns the simplified value, or null if no simplification was performed.
76static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +000077 unsigned OpcToExpand, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +000078 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +000079 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000080 // Recursion is always used, so bail out at once if we already hit the limit.
81 if (!MaxRecurse--)
82 return 0;
83
84 // Check whether the expression has the form "(A op' B) op C".
85 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
86 if (Op0->getOpcode() == OpcodeToExpand) {
87 // It does! Try turning it into "(A op C) op' (B op C)".
88 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
89 // Do "A op C" and "B op C" both simplify?
90 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
91 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
92 // They do! Return "L op' R" if it simplifies or is already available.
93 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +000094 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
95 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +000096 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000097 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +000098 }
Duncan Sands3421d902010-12-21 13:32:22 +000099 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000100 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
101 MaxRecurse)) {
102 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000103 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000104 }
Duncan Sands3421d902010-12-21 13:32:22 +0000105 }
106 }
107
108 // Check whether the expression has the form "A op (B op' C)".
109 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
110 if (Op1->getOpcode() == OpcodeToExpand) {
111 // It does! Try turning it into "(A op B) op' (A op C)".
112 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
113 // Do "A op B" and "A op C" both simplify?
114 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
115 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
116 // They do! Return "L op' R" if it simplifies or is already available.
117 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000118 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
119 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000120 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000121 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000122 }
Duncan Sands3421d902010-12-21 13:32:22 +0000123 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000124 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
125 MaxRecurse)) {
126 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000127 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000128 }
Duncan Sands3421d902010-12-21 13:32:22 +0000129 }
130 }
131
132 return 0;
133}
134
135/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
136/// using the operation OpCodeToExtract. For example, when Opcode is Add and
137/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
138/// Returns the simplified value, or null if no simplification was performed.
139static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000140 unsigned OpcToExtract, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +0000141 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000142 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000143 // Recursion is always used, so bail out at once if we already hit the limit.
144 if (!MaxRecurse--)
145 return 0;
146
147 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
148 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
149
150 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
151 !Op1 || Op1->getOpcode() != OpcodeToExtract)
152 return 0;
153
154 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000155 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
156 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000157
158 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
159 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
160 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000161 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
162 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000163 // Form "A op' (B op DD)" if it simplifies completely.
164 // Does "B op DD" simplify?
165 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
166 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000167 // If V equals B then "A op' V" is just the LHS. If V equals DD then
168 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000169 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000170 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000171 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000172 }
Duncan Sands3421d902010-12-21 13:32:22 +0000173 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000174 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
175 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000176 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000177 }
Duncan Sands3421d902010-12-21 13:32:22 +0000178 }
179 }
180
181 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
182 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
183 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000184 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
185 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000186 // Form "(A op CC) op' B" if it simplifies completely..
187 // Does "A op CC" simplify?
188 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
189 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000190 // If V equals A then "V op' B" is just the LHS. If V equals CC then
191 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000192 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000193 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000194 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000195 }
Duncan Sands3421d902010-12-21 13:32:22 +0000196 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000197 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
198 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000199 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000200 }
Duncan Sands3421d902010-12-21 13:32:22 +0000201 }
202 }
203
204 return 0;
205}
206
207/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
208/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000209static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000210 const TargetData *TD,
211 const DominatorTree *DT,
212 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000213 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000214 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
215
216 // Recursion is always used, so bail out at once if we already hit the limit.
217 if (!MaxRecurse--)
218 return 0;
219
220 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
221 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
222
223 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
224 if (Op0 && Op0->getOpcode() == Opcode) {
225 Value *A = Op0->getOperand(0);
226 Value *B = Op0->getOperand(1);
227 Value *C = RHS;
228
229 // Does "B op C" simplify?
230 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
231 // It does! Return "A op V" if it simplifies or is already available.
232 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000233 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000234 // Otherwise return "A op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000235 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
236 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000237 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000238 }
Duncan Sands566edb02010-12-21 08:49:00 +0000239 }
240 }
241
242 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
243 if (Op1 && Op1->getOpcode() == Opcode) {
244 Value *A = LHS;
245 Value *B = Op1->getOperand(0);
246 Value *C = Op1->getOperand(1);
247
248 // Does "A op B" simplify?
249 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
250 // It does! Return "V op C" if it simplifies or is already available.
251 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000252 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000253 // Otherwise return "V op C" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000254 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
255 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000256 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000257 }
Duncan Sands566edb02010-12-21 08:49:00 +0000258 }
259 }
260
261 // The remaining transforms require commutativity as well as associativity.
262 if (!Instruction::isCommutative(Opcode))
263 return 0;
264
265 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
266 if (Op0 && Op0->getOpcode() == Opcode) {
267 Value *A = Op0->getOperand(0);
268 Value *B = Op0->getOperand(1);
269 Value *C = RHS;
270
271 // Does "C op A" simplify?
272 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
273 // It does! Return "V op B" if it simplifies or is already available.
274 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000275 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000276 // Otherwise return "V op B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000277 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
278 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000279 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000280 }
Duncan Sands566edb02010-12-21 08:49:00 +0000281 }
282 }
283
284 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
285 if (Op1 && Op1->getOpcode() == Opcode) {
286 Value *A = LHS;
287 Value *B = Op1->getOperand(0);
288 Value *C = Op1->getOperand(1);
289
290 // Does "C op A" simplify?
291 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
292 // It does! Return "B op V" if it simplifies or is already available.
293 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000294 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000295 // Otherwise return "B op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000296 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
297 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000298 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000299 }
Duncan Sands566edb02010-12-21 08:49:00 +0000300 }
301 }
302
303 return 0;
304}
305
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000306/// ThreadBinOpOverSelect - In the case of a binary operation with a select
307/// instruction as an operand, try to simplify the binop by seeing whether
308/// evaluating it on both branches of the select results in the same value.
309/// Returns the common value if so, otherwise returns null.
310static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000311 const TargetData *TD,
312 const DominatorTree *DT,
313 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000314 // Recursion is always used, so bail out at once if we already hit the limit.
315 if (!MaxRecurse--)
316 return 0;
317
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000318 SelectInst *SI;
319 if (isa<SelectInst>(LHS)) {
320 SI = cast<SelectInst>(LHS);
321 } else {
322 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
323 SI = cast<SelectInst>(RHS);
324 }
325
326 // Evaluate the BinOp on the true and false branches of the select.
327 Value *TV;
328 Value *FV;
329 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000330 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
331 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000332 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000333 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
334 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000335 }
336
Duncan Sands7cf85e72011-01-01 16:12:09 +0000337 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000338 // If they both failed to simplify then return null.
339 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000340 return TV;
341
342 // If one branch simplified to undef, return the other one.
343 if (TV && isa<UndefValue>(TV))
344 return FV;
345 if (FV && isa<UndefValue>(FV))
346 return TV;
347
348 // If applying the operation did not change the true and false select values,
349 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000350 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000351 return SI;
352
353 // If one branch simplified and the other did not, and the simplified
354 // value is equal to the unsimplified one, return the simplified value.
355 // For example, select (cond, X, X & Z) & Z -> X & Z.
356 if ((FV && !TV) || (TV && !FV)) {
357 // Check that the simplified value has the form "X op Y" where "op" is the
358 // same as the original operation.
359 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
360 if (Simplified && Simplified->getOpcode() == Opcode) {
361 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
362 // We already know that "op" is the same as for the simplified value. See
363 // if the operands match too. If so, return the simplified value.
364 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
365 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
366 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000367 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
368 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000369 return Simplified;
370 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000371 Simplified->getOperand(1) == UnsimplifiedLHS &&
372 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000373 return Simplified;
374 }
375 }
376
377 return 0;
378}
379
380/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
381/// try to simplify the comparison by seeing whether both branches of the select
382/// result in the same value. Returns the common value if so, otherwise returns
383/// null.
384static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000385 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000386 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000387 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000388 // Recursion is always used, so bail out at once if we already hit the limit.
389 if (!MaxRecurse--)
390 return 0;
391
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000392 // Make sure the select is on the LHS.
393 if (!isa<SelectInst>(LHS)) {
394 std::swap(LHS, RHS);
395 Pred = CmpInst::getSwappedPredicate(Pred);
396 }
397 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
398 SelectInst *SI = cast<SelectInst>(LHS);
399
Duncan Sands50ca4d32011-02-03 09:37:39 +0000400 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000401 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000402 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000403 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000404 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000405 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000406 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000407 // It does! If they simplified to the same value, then use it as the
408 // result of the original comparison.
Duncan Sands124708d2011-01-01 20:08:02 +0000409 if (TCmp == FCmp)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000410 return TCmp;
Duncan Sands50ca4d32011-02-03 09:37:39 +0000411 Value *Cond = SI->getCondition();
412 // If the false value simplified to false, then the result of the compare
413 // is equal to "Cond && TCmp". This also catches the case when the false
414 // value simplified to false and the true value to true, returning "Cond".
415 if (match(FCmp, m_Zero()))
416 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
417 return V;
418 // If the true value simplified to true, then the result of the compare
419 // is equal to "Cond || FCmp".
420 if (match(TCmp, m_One()))
421 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
422 return V;
423 // Finally, if the false value simplified to true and the true value to
424 // false, then the result of the compare is equal to "!Cond".
425 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
426 if (Value *V =
427 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
428 TD, DT, MaxRecurse))
429 return V;
430 }
431 }
432
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000433 return 0;
434}
435
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000436/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
437/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
438/// it on the incoming phi values yields the same result for every value. If so
439/// returns the common value, otherwise returns null.
440static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000441 const TargetData *TD, const DominatorTree *DT,
442 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000443 // Recursion is always used, so bail out at once if we already hit the limit.
444 if (!MaxRecurse--)
445 return 0;
446
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000447 PHINode *PI;
448 if (isa<PHINode>(LHS)) {
449 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000450 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
451 if (!ValueDominatesPHI(RHS, PI, DT))
452 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000453 } else {
454 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
455 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000456 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
457 if (!ValueDominatesPHI(LHS, PI, DT))
458 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000459 }
460
461 // Evaluate the BinOp on the incoming phi values.
462 Value *CommonValue = 0;
463 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000464 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000465 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000466 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000467 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000468 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
469 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000470 // If the operation failed to simplify, or simplified to a different value
471 // to previously, then give up.
472 if (!V || (CommonValue && V != CommonValue))
473 return 0;
474 CommonValue = V;
475 }
476
477 return CommonValue;
478}
479
480/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
481/// try to simplify the comparison by seeing whether comparing with all of the
482/// incoming phi values yields the same result every time. If so returns the
483/// common result, otherwise returns null.
484static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000485 const TargetData *TD, const DominatorTree *DT,
486 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000487 // Recursion is always used, so bail out at once if we already hit the limit.
488 if (!MaxRecurse--)
489 return 0;
490
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000491 // Make sure the phi is on the LHS.
492 if (!isa<PHINode>(LHS)) {
493 std::swap(LHS, RHS);
494 Pred = CmpInst::getSwappedPredicate(Pred);
495 }
496 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
497 PHINode *PI = cast<PHINode>(LHS);
498
Duncan Sands18450092010-11-16 12:16:38 +0000499 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
500 if (!ValueDominatesPHI(RHS, PI, DT))
501 return 0;
502
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000503 // Evaluate the BinOp on the incoming phi values.
504 Value *CommonValue = 0;
505 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000506 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000507 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000508 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000509 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000510 // If the operation failed to simplify, or simplified to a different value
511 // to previously, then give up.
512 if (!V || (CommonValue && V != CommonValue))
513 return 0;
514 CommonValue = V;
515 }
516
517 return CommonValue;
518}
519
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000520/// SimplifyAddInst - Given operands for an Add, see if we can
521/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000522static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
523 const TargetData *TD, const DominatorTree *DT,
524 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000525 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
526 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
527 Constant *Ops[] = { CLHS, CRHS };
528 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
529 Ops, 2, TD);
530 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000531
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000532 // Canonicalize the constant to the RHS.
533 std::swap(Op0, Op1);
534 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000535
Duncan Sandsfea3b212010-12-15 14:07:39 +0000536 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000537 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000538 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000539
Duncan Sandsfea3b212010-12-15 14:07:39 +0000540 // X + 0 -> X
541 if (match(Op1, m_Zero()))
542 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000543
Duncan Sandsfea3b212010-12-15 14:07:39 +0000544 // X + (Y - X) -> Y
545 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000546 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000547 Value *Y = 0;
548 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
549 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000550 return Y;
551
552 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000553 if (match(Op0, m_Not(m_Specific(Op1))) ||
554 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000555 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000556
Duncan Sands82fdab32010-12-21 14:00:22 +0000557 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000558 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000559 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
560 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000561
Duncan Sands566edb02010-12-21 08:49:00 +0000562 // Try some generic simplifications for associative operations.
563 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
564 MaxRecurse))
565 return V;
566
Duncan Sands3421d902010-12-21 13:32:22 +0000567 // Mul distributes over Add. Try some generic simplifications based on this.
568 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
569 TD, DT, MaxRecurse))
570 return V;
571
Duncan Sands87689cf2010-11-19 09:20:39 +0000572 // Threading Add over selects and phi nodes is pointless, so don't bother.
573 // Threading over the select in "A + select(cond, B, C)" means evaluating
574 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
575 // only if B and C are equal. If B and C are equal then (since we assume
576 // that operands have already been simplified) "select(cond, B, C)" should
577 // have been simplified to the common value of B and C already. Analysing
578 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
579 // for threading over phi nodes.
580
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000581 return 0;
582}
583
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000584Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
585 const TargetData *TD, const DominatorTree *DT) {
586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
587}
588
Duncan Sandsfea3b212010-12-15 14:07:39 +0000589/// SimplifySubInst - Given operands for a Sub, see if we can
590/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000591static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000592 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000593 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000594 if (Constant *CLHS = dyn_cast<Constant>(Op0))
595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596 Constant *Ops[] = { CLHS, CRHS };
597 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
598 Ops, 2, TD);
599 }
600
601 // X - undef -> undef
602 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000603 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000604 return UndefValue::get(Op0->getType());
605
606 // X - 0 -> X
607 if (match(Op1, m_Zero()))
608 return Op0;
609
610 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000611 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000612 return Constant::getNullValue(Op0->getType());
613
Duncan Sandsfe02c692011-01-18 09:24:58 +0000614 // (X*2) - X -> X
615 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000616 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000617 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
618 match(Op0, m_Shl(m_Specific(Op1), m_One())))
619 return Op1;
620
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000621 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
622 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
623 Value *Y = 0, *Z = Op1;
624 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
625 // See if "V === Y - Z" simplifies.
626 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
627 // It does! Now see if "X + V" simplifies.
628 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
629 MaxRecurse-1)) {
630 // It does, we successfully reassociated!
631 ++NumReassoc;
632 return W;
633 }
634 // See if "V === X - Z" simplifies.
635 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
636 // It does! Now see if "Y + V" simplifies.
637 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
638 MaxRecurse-1)) {
639 // It does, we successfully reassociated!
640 ++NumReassoc;
641 return W;
642 }
643 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000644
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000645 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
646 // For example, X - (X + 1) -> -1
647 X = Op0;
648 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
649 // See if "V === X - Y" simplifies.
650 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
651 // It does! Now see if "V - Z" simplifies.
652 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
653 MaxRecurse-1)) {
654 // It does, we successfully reassociated!
655 ++NumReassoc;
656 return W;
657 }
658 // See if "V === X - Z" simplifies.
659 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
660 // It does! Now see if "V - Y" simplifies.
661 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
662 MaxRecurse-1)) {
663 // It does, we successfully reassociated!
664 ++NumReassoc;
665 return W;
666 }
667 }
668
669 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
670 // For example, X - (X - Y) -> Y.
671 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000672 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
673 // See if "V === Z - X" simplifies.
674 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000675 // It does! Now see if "V + Y" simplifies.
Duncan Sandsc087e202011-01-14 15:26:10 +0000676 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
677 MaxRecurse-1)) {
678 // It does, we successfully reassociated!
679 ++NumReassoc;
680 return W;
681 }
682
Duncan Sands3421d902010-12-21 13:32:22 +0000683 // Mul distributes over Sub. Try some generic simplifications based on this.
684 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
685 TD, DT, MaxRecurse))
686 return V;
687
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000688 // i1 sub -> xor.
689 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
690 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
691 return V;
692
Duncan Sandsfea3b212010-12-15 14:07:39 +0000693 // Threading Sub over selects and phi nodes is pointless, so don't bother.
694 // Threading over the select in "A - select(cond, B, C)" means evaluating
695 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
696 // only if B and C are equal. If B and C are equal then (since we assume
697 // that operands have already been simplified) "select(cond, B, C)" should
698 // have been simplified to the common value of B and C already. Analysing
699 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
700 // for threading over phi nodes.
701
702 return 0;
703}
704
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000705Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
706 const TargetData *TD, const DominatorTree *DT) {
707 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
708}
709
Duncan Sands82fdab32010-12-21 14:00:22 +0000710/// SimplifyMulInst - Given operands for a Mul, see if we can
711/// fold the result. If not, this returns null.
712static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
713 const DominatorTree *DT, unsigned MaxRecurse) {
714 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
715 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
716 Constant *Ops[] = { CLHS, CRHS };
717 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
718 Ops, 2, TD);
719 }
720
721 // Canonicalize the constant to the RHS.
722 std::swap(Op0, Op1);
723 }
724
725 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000726 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000727 return Constant::getNullValue(Op0->getType());
728
729 // X * 0 -> 0
730 if (match(Op1, m_Zero()))
731 return Op1;
732
733 // X * 1 -> X
734 if (match(Op1, m_One()))
735 return Op0;
736
Duncan Sands1895e982011-01-30 18:03:50 +0000737 // (X / Y) * Y -> X if the division is exact.
738 Value *X = 0, *Y = 0;
Chris Lattneraeaf3d42011-02-09 17:00:45 +0000739 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
740 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
Chris Lattnerc6ee9182011-02-06 22:05:31 +0000741 BinaryOperator *Div = cast<BinaryOperator>(Y == Op1 ? Op0 : Op1);
742 if (Div->isExact())
Duncan Sands1895e982011-01-30 18:03:50 +0000743 return X;
744 }
745
Nick Lewycky54138802011-01-29 19:55:23 +0000746 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000747 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000748 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
749 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000750
751 // Try some generic simplifications for associative operations.
752 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
753 MaxRecurse))
754 return V;
755
756 // Mul distributes over Add. Try some generic simplifications based on this.
757 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
758 TD, DT, MaxRecurse))
759 return V;
760
761 // If the operation is with the result of a select instruction, check whether
762 // operating on either branch of the select always yields the same value.
763 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
764 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
765 MaxRecurse))
766 return V;
767
768 // If the operation is with the result of a phi instruction, check whether
769 // operating on all incoming values of the phi always yields the same value.
770 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
771 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
772 MaxRecurse))
773 return V;
774
775 return 0;
776}
777
778Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
779 const DominatorTree *DT) {
780 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
781}
782
Duncan Sands593faa52011-01-28 16:51:11 +0000783/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
784/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000785static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands593faa52011-01-28 16:51:11 +0000786 const TargetData *TD, const DominatorTree *DT,
787 unsigned MaxRecurse) {
788 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
789 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
790 Constant *Ops[] = { C0, C1 };
791 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
792 }
793 }
794
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000795 bool isSigned = Opcode == Instruction::SDiv;
796
Duncan Sands593faa52011-01-28 16:51:11 +0000797 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000798 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000799 return Op1;
800
801 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000802 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000803 return Constant::getNullValue(Op0->getType());
804
805 // 0 / X -> 0, we don't need to preserve faults!
806 if (match(Op0, m_Zero()))
807 return Op0;
808
809 // X / 1 -> X
810 if (match(Op1, m_One()))
811 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000812
813 if (Op0->getType()->isIntegerTy(1))
814 // It can't be division by zero, hence it must be division by one.
815 return Op0;
816
817 // X / X -> 1
818 if (Op0 == Op1)
819 return ConstantInt::get(Op0->getType(), 1);
820
821 // (X * Y) / Y -> X if the multiplication does not overflow.
822 Value *X = 0, *Y = 0;
823 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
824 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands4b720712011-02-02 20:52:00 +0000825 BinaryOperator *Mul = cast<BinaryOperator>(Op0);
826 // If the Mul knows it does not overflow, then we are good to go.
827 if ((isSigned && Mul->hasNoSignedWrap()) ||
828 (!isSigned && Mul->hasNoUnsignedWrap()))
829 return X;
Duncan Sands593faa52011-01-28 16:51:11 +0000830 // If X has the form X = A / Y then X * Y cannot overflow.
831 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
832 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
833 return X;
834 }
835
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000836 // (X rem Y) / Y -> 0
837 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
838 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
839 return Constant::getNullValue(Op0->getType());
840
841 // If the operation is with the result of a select instruction, check whether
842 // operating on either branch of the select always yields the same value.
843 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
844 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
845 return V;
846
847 // If the operation is with the result of a phi instruction, check whether
848 // operating on all incoming values of the phi always yields the same value.
849 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
850 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
851 return V;
852
Duncan Sands593faa52011-01-28 16:51:11 +0000853 return 0;
854}
855
856/// SimplifySDivInst - Given operands for an SDiv, see if we can
857/// fold the result. If not, this returns null.
858static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
859 const DominatorTree *DT, unsigned MaxRecurse) {
860 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
861 return V;
862
Duncan Sands593faa52011-01-28 16:51:11 +0000863 return 0;
864}
865
866Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000867 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000868 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
869}
870
871/// SimplifyUDivInst - Given operands for a UDiv, see if we can
872/// fold the result. If not, this returns null.
873static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
874 const DominatorTree *DT, unsigned MaxRecurse) {
875 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
876 return V;
877
Duncan Sands593faa52011-01-28 16:51:11 +0000878 return 0;
879}
880
881Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000882 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000883 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
884}
885
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000886static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
887 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000888 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000889 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000890 return Op0;
891
892 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000893 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000894 return Op1;
895
896 return 0;
897}
898
899Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
900 const DominatorTree *DT) {
901 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
902}
903
Duncan Sandsf24ed772011-05-02 16:27:02 +0000904/// SimplifyRem - Given operands for an SRem or URem, see if we can
905/// fold the result. If not, this returns null.
906static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
907 const TargetData *TD, const DominatorTree *DT,
908 unsigned MaxRecurse) {
909 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
910 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
911 Constant *Ops[] = { C0, C1 };
912 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
913 }
914 }
915
Duncan Sandsf24ed772011-05-02 16:27:02 +0000916 // X % undef -> undef
917 if (match(Op1, m_Undef()))
918 return Op1;
919
920 // undef % X -> 0
921 if (match(Op0, m_Undef()))
922 return Constant::getNullValue(Op0->getType());
923
924 // 0 % X -> 0, we don't need to preserve faults!
925 if (match(Op0, m_Zero()))
926 return Op0;
927
928 // X % 0 -> undef, we don't need to preserve faults!
929 if (match(Op1, m_Zero()))
930 return UndefValue::get(Op0->getType());
931
932 // X % 1 -> 0
933 if (match(Op1, m_One()))
934 return Constant::getNullValue(Op0->getType());
935
936 if (Op0->getType()->isIntegerTy(1))
937 // It can't be remainder by zero, hence it must be remainder by one.
938 return Constant::getNullValue(Op0->getType());
939
940 // X % X -> 0
941 if (Op0 == Op1)
942 return Constant::getNullValue(Op0->getType());
943
944 // If the operation is with the result of a select instruction, check whether
945 // operating on either branch of the select always yields the same value.
946 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
947 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
948 return V;
949
950 // If the operation is with the result of a phi instruction, check whether
951 // operating on all incoming values of the phi always yields the same value.
952 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
953 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
954 return V;
955
956 return 0;
957}
958
959/// SimplifySRemInst - Given operands for an SRem, see if we can
960/// fold the result. If not, this returns null.
961static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
962 const DominatorTree *DT, unsigned MaxRecurse) {
963 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
964 return V;
965
966 return 0;
967}
968
969Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
970 const DominatorTree *DT) {
971 return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
972}
973
974/// SimplifyURemInst - Given operands for a URem, see if we can
975/// fold the result. If not, this returns null.
976static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
977 const DominatorTree *DT, unsigned MaxRecurse) {
978 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
979 return V;
980
981 return 0;
982}
983
984Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
985 const DominatorTree *DT) {
986 return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
987}
988
989static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
990 const DominatorTree *, unsigned) {
991 // undef % X -> undef (the undef could be a snan).
992 if (match(Op0, m_Undef()))
993 return Op0;
994
995 // X % undef -> undef
996 if (match(Op1, m_Undef()))
997 return Op1;
998
999 return 0;
1000}
1001
1002Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1003 const DominatorTree *DT) {
1004 return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1005}
1006
Duncan Sandscf80bc12011-01-14 14:44:12 +00001007/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001008/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001009static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1010 const TargetData *TD, const DominatorTree *DT,
1011 unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001012 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1013 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1014 Constant *Ops[] = { C0, C1 };
Duncan Sandscf80bc12011-01-14 14:44:12 +00001015 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001016 }
1017 }
1018
Duncan Sandscf80bc12011-01-14 14:44:12 +00001019 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001020 if (match(Op0, m_Zero()))
1021 return Op0;
1022
Duncan Sandscf80bc12011-01-14 14:44:12 +00001023 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001024 if (match(Op1, m_Zero()))
1025 return Op0;
1026
Duncan Sandscf80bc12011-01-14 14:44:12 +00001027 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001028 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001029 return Op1;
1030
1031 // Shifting by the bitwidth or more is undefined.
1032 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1033 if (CI->getValue().getLimitedValue() >=
1034 Op0->getType()->getScalarSizeInBits())
1035 return UndefValue::get(Op0->getType());
1036
Duncan Sandscf80bc12011-01-14 14:44:12 +00001037 // If the operation is with the result of a select instruction, check whether
1038 // operating on either branch of the select always yields the same value.
1039 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1040 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1041 return V;
1042
1043 // If the operation is with the result of a phi instruction, check whether
1044 // operating on all incoming values of the phi always yields the same value.
1045 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1046 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1047 return V;
1048
1049 return 0;
1050}
1051
1052/// SimplifyShlInst - Given operands for an Shl, see if we can
1053/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001054static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1055 const TargetData *TD, const DominatorTree *DT,
1056 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001057 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1058 return V;
1059
1060 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001061 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001062 return Constant::getNullValue(Op0->getType());
1063
Chris Lattner81a0dc92011-02-09 17:15:04 +00001064 // (X >> A) << A -> X
1065 Value *X;
1066 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1067 cast<PossiblyExactOperator>(Op0)->isExact())
1068 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001069 return 0;
1070}
1071
Chris Lattner81a0dc92011-02-09 17:15:04 +00001072Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1073 const TargetData *TD, const DominatorTree *DT) {
1074 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001075}
1076
1077/// SimplifyLShrInst - Given operands for an LShr, see if we can
1078/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001079static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1080 const TargetData *TD, const DominatorTree *DT,
1081 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001082 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1083 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001084
1085 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001086 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001087 return Constant::getNullValue(Op0->getType());
1088
Chris Lattner81a0dc92011-02-09 17:15:04 +00001089 // (X << A) >> A -> X
1090 Value *X;
1091 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1092 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1093 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001094
Duncan Sandsc43cee32011-01-14 00:37:45 +00001095 return 0;
1096}
1097
Chris Lattner81a0dc92011-02-09 17:15:04 +00001098Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1099 const TargetData *TD, const DominatorTree *DT) {
1100 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001101}
1102
1103/// SimplifyAShrInst - Given operands for an AShr, see if we can
1104/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001105static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1106 const TargetData *TD, const DominatorTree *DT,
1107 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001108 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1109 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001110
1111 // all ones >>a X -> all ones
1112 if (match(Op0, m_AllOnes()))
1113 return Op0;
1114
1115 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001116 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001117 return Constant::getAllOnesValue(Op0->getType());
1118
Chris Lattner81a0dc92011-02-09 17:15:04 +00001119 // (X << A) >> A -> X
1120 Value *X;
1121 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1122 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1123 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001124
Duncan Sandsc43cee32011-01-14 00:37:45 +00001125 return 0;
1126}
1127
Chris Lattner81a0dc92011-02-09 17:15:04 +00001128Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1129 const TargetData *TD, const DominatorTree *DT) {
1130 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001131}
1132
Chris Lattnerd06094f2009-11-10 00:55:12 +00001133/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001134/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001135static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001136 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001137 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1138 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1139 Constant *Ops[] = { CLHS, CRHS };
1140 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1141 Ops, 2, TD);
1142 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001143
Chris Lattnerd06094f2009-11-10 00:55:12 +00001144 // Canonicalize the constant to the RHS.
1145 std::swap(Op0, Op1);
1146 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001147
Chris Lattnerd06094f2009-11-10 00:55:12 +00001148 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001149 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001150 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001151
Chris Lattnerd06094f2009-11-10 00:55:12 +00001152 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001153 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001154 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001155
Duncan Sands2b749872010-11-17 18:52:15 +00001156 // X & 0 = 0
1157 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001158 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001159
Duncan Sands2b749872010-11-17 18:52:15 +00001160 // X & -1 = X
1161 if (match(Op1, m_AllOnes()))
1162 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001163
Chris Lattnerd06094f2009-11-10 00:55:12 +00001164 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001165 if (match(Op0, m_Not(m_Specific(Op1))) ||
1166 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001167 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001168
Chris Lattnerd06094f2009-11-10 00:55:12 +00001169 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001170 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001171 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001172 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001173 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001174
Chris Lattnerd06094f2009-11-10 00:55:12 +00001175 // A & (A | ?) = A
1176 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001177 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001178 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001179
Duncan Sands566edb02010-12-21 08:49:00 +00001180 // Try some generic simplifications for associative operations.
1181 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1182 MaxRecurse))
1183 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001184
Duncan Sands3421d902010-12-21 13:32:22 +00001185 // And distributes over Or. Try some generic simplifications based on this.
1186 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1187 TD, DT, MaxRecurse))
1188 return V;
1189
1190 // And distributes over Xor. Try some generic simplifications based on this.
1191 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1192 TD, DT, MaxRecurse))
1193 return V;
1194
1195 // Or distributes over And. Try some generic simplifications based on this.
1196 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1197 TD, DT, MaxRecurse))
1198 return V;
1199
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001200 // If the operation is with the result of a select instruction, check whether
1201 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001202 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001203 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001204 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001205 return V;
1206
1207 // If the operation is with the result of a phi instruction, check whether
1208 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001209 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001210 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001211 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001212 return V;
1213
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001214 return 0;
1215}
1216
Duncan Sands18450092010-11-16 12:16:38 +00001217Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1218 const DominatorTree *DT) {
1219 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001220}
1221
Chris Lattnerd06094f2009-11-10 00:55:12 +00001222/// SimplifyOrInst - Given operands for an Or, see if we can
1223/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001224static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001225 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001226 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1227 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1228 Constant *Ops[] = { CLHS, CRHS };
1229 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1230 Ops, 2, TD);
1231 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001232
Chris Lattnerd06094f2009-11-10 00:55:12 +00001233 // Canonicalize the constant to the RHS.
1234 std::swap(Op0, Op1);
1235 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001236
Chris Lattnerd06094f2009-11-10 00:55:12 +00001237 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001238 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001239 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001240
Chris Lattnerd06094f2009-11-10 00:55:12 +00001241 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001242 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001243 return Op0;
1244
Duncan Sands2b749872010-11-17 18:52:15 +00001245 // X | 0 = X
1246 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001247 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001248
Duncan Sands2b749872010-11-17 18:52:15 +00001249 // X | -1 = -1
1250 if (match(Op1, m_AllOnes()))
1251 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001252
Chris Lattnerd06094f2009-11-10 00:55:12 +00001253 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001254 if (match(Op0, m_Not(m_Specific(Op1))) ||
1255 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001256 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001257
Chris Lattnerd06094f2009-11-10 00:55:12 +00001258 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001259 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001260 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001261 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001262 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001263
Chris Lattnerd06094f2009-11-10 00:55:12 +00001264 // A | (A & ?) = A
1265 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001266 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001267 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001268
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001269 // ~(A & ?) | A = -1
1270 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1271 (A == Op1 || B == Op1))
1272 return Constant::getAllOnesValue(Op1->getType());
1273
1274 // A | ~(A & ?) = -1
1275 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1276 (A == Op0 || B == Op0))
1277 return Constant::getAllOnesValue(Op0->getType());
1278
Duncan Sands566edb02010-12-21 08:49:00 +00001279 // Try some generic simplifications for associative operations.
1280 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1281 MaxRecurse))
1282 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001283
Duncan Sands3421d902010-12-21 13:32:22 +00001284 // Or distributes over And. Try some generic simplifications based on this.
1285 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1286 TD, DT, MaxRecurse))
1287 return V;
1288
1289 // And distributes over Or. Try some generic simplifications based on this.
1290 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1291 TD, DT, MaxRecurse))
1292 return V;
1293
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001294 // If the operation is with the result of a select instruction, check whether
1295 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001296 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001297 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001298 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001299 return V;
1300
1301 // If the operation is with the result of a phi instruction, check whether
1302 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001303 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001304 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001305 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001306 return V;
1307
Chris Lattnerd06094f2009-11-10 00:55:12 +00001308 return 0;
1309}
1310
Duncan Sands18450092010-11-16 12:16:38 +00001311Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1312 const DominatorTree *DT) {
1313 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001314}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001315
Duncan Sands2b749872010-11-17 18:52:15 +00001316/// SimplifyXorInst - Given operands for a Xor, see if we can
1317/// fold the result. If not, this returns null.
1318static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1319 const DominatorTree *DT, unsigned MaxRecurse) {
1320 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1321 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1322 Constant *Ops[] = { CLHS, CRHS };
1323 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1324 Ops, 2, TD);
1325 }
1326
1327 // Canonicalize the constant to the RHS.
1328 std::swap(Op0, Op1);
1329 }
1330
1331 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001332 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001333 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001334
1335 // A ^ 0 = A
1336 if (match(Op1, m_Zero()))
1337 return Op0;
1338
1339 // A ^ A = 0
Duncan Sands124708d2011-01-01 20:08:02 +00001340 if (Op0 == Op1)
Duncan Sands2b749872010-11-17 18:52:15 +00001341 return Constant::getNullValue(Op0->getType());
1342
1343 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001344 if (match(Op0, m_Not(m_Specific(Op1))) ||
1345 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001346 return Constant::getAllOnesValue(Op0->getType());
1347
Duncan Sands566edb02010-12-21 08:49:00 +00001348 // Try some generic simplifications for associative operations.
1349 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1350 MaxRecurse))
1351 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001352
Duncan Sands3421d902010-12-21 13:32:22 +00001353 // And distributes over Xor. Try some generic simplifications based on this.
1354 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1355 TD, DT, MaxRecurse))
1356 return V;
1357
Duncan Sands87689cf2010-11-19 09:20:39 +00001358 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1359 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1360 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1361 // only if B and C are equal. If B and C are equal then (since we assume
1362 // that operands have already been simplified) "select(cond, B, C)" should
1363 // have been simplified to the common value of B and C already. Analysing
1364 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1365 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001366
1367 return 0;
1368}
1369
1370Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1371 const DominatorTree *DT) {
1372 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1373}
1374
Chris Lattner210c5d42009-11-09 23:55:12 +00001375static const Type *GetCompareTy(Value *Op) {
1376 return CmpInst::makeCmpResultType(Op->getType());
1377}
1378
Chris Lattner9dbb4292009-11-09 23:28:39 +00001379/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1380/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001381static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001382 const TargetData *TD, const DominatorTree *DT,
1383 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001384 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001385 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001386
Chris Lattnerd06094f2009-11-10 00:55:12 +00001387 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001388 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1389 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001390
1391 // If we have a constant, make sure it is on the RHS.
1392 std::swap(LHS, RHS);
1393 Pred = CmpInst::getSwappedPredicate(Pred);
1394 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001395
Duncan Sands6dc91252011-01-13 08:56:29 +00001396 const Type *ITy = GetCompareTy(LHS); // The return type.
1397 const Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001398
Chris Lattner210c5d42009-11-09 23:55:12 +00001399 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001400 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1401 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001402 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001403 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001404
Duncan Sands6dc91252011-01-13 08:56:29 +00001405 // Special case logic when the operands have i1 type.
1406 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1407 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1408 switch (Pred) {
1409 default: break;
1410 case ICmpInst::ICMP_EQ:
1411 // X == 1 -> X
1412 if (match(RHS, m_One()))
1413 return LHS;
1414 break;
1415 case ICmpInst::ICMP_NE:
1416 // X != 0 -> X
1417 if (match(RHS, m_Zero()))
1418 return LHS;
1419 break;
1420 case ICmpInst::ICMP_UGT:
1421 // X >u 0 -> X
1422 if (match(RHS, m_Zero()))
1423 return LHS;
1424 break;
1425 case ICmpInst::ICMP_UGE:
1426 // X >=u 1 -> X
1427 if (match(RHS, m_One()))
1428 return LHS;
1429 break;
1430 case ICmpInst::ICMP_SLT:
1431 // X <s 0 -> X
1432 if (match(RHS, m_Zero()))
1433 return LHS;
1434 break;
1435 case ICmpInst::ICMP_SLE:
1436 // X <=s -1 -> X
1437 if (match(RHS, m_One()))
1438 return LHS;
1439 break;
1440 }
1441 }
1442
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001443 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1444 // different addresses, and what's more the address of a stack variable is
1445 // never null or equal to the address of a global. Note that generalizing
1446 // to the case where LHS is a global variable address or null is pointless,
1447 // since if both LHS and RHS are constants then we already constant folded
1448 // the compare, and if only one of them is then we moved it to RHS already.
1449 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1450 isa<ConstantPointerNull>(RHS)))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001451 // We already know that LHS != RHS.
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001452 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1453
1454 // If we are comparing with zero then try hard since this is a common case.
1455 if (match(RHS, m_Zero())) {
1456 bool LHSKnownNonNegative, LHSKnownNegative;
1457 switch (Pred) {
1458 default:
1459 assert(false && "Unknown ICmp predicate!");
1460 case ICmpInst::ICMP_ULT:
Duncan Sands448a6d32011-05-02 18:51:41 +00001461 // getNullValue also works for vectors, unlike getFalse.
1462 return Constant::getNullValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001463 case ICmpInst::ICMP_UGE:
Duncan Sands448a6d32011-05-02 18:51:41 +00001464 // getAllOnesValue also works for vectors, unlike getTrue.
1465 return ConstantInt::getAllOnesValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001466 case ICmpInst::ICMP_EQ:
1467 case ICmpInst::ICMP_ULE:
1468 if (isKnownNonZero(LHS, TD))
Duncan Sands448a6d32011-05-02 18:51:41 +00001469 return Constant::getNullValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001470 break;
1471 case ICmpInst::ICMP_NE:
1472 case ICmpInst::ICMP_UGT:
1473 if (isKnownNonZero(LHS, TD))
Duncan Sands448a6d32011-05-02 18:51:41 +00001474 return ConstantInt::getAllOnesValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001475 break;
1476 case ICmpInst::ICMP_SLT:
1477 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1478 if (LHSKnownNegative)
Duncan Sands448a6d32011-05-02 18:51:41 +00001479 return ConstantInt::getAllOnesValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001480 if (LHSKnownNonNegative)
Duncan Sands448a6d32011-05-02 18:51:41 +00001481 return Constant::getNullValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001482 break;
1483 case ICmpInst::ICMP_SLE:
1484 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1485 if (LHSKnownNegative)
Duncan Sands448a6d32011-05-02 18:51:41 +00001486 return ConstantInt::getAllOnesValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001487 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sands448a6d32011-05-02 18:51:41 +00001488 return Constant::getNullValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001489 break;
1490 case ICmpInst::ICMP_SGE:
1491 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1492 if (LHSKnownNegative)
Duncan Sands448a6d32011-05-02 18:51:41 +00001493 return Constant::getNullValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001494 if (LHSKnownNonNegative)
Duncan Sands448a6d32011-05-02 18:51:41 +00001495 return ConstantInt::getAllOnesValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001496 break;
1497 case ICmpInst::ICMP_SGT:
1498 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1499 if (LHSKnownNegative)
Duncan Sands448a6d32011-05-02 18:51:41 +00001500 return Constant::getNullValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001501 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sands448a6d32011-05-02 18:51:41 +00001502 return ConstantInt::getAllOnesValue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001503 break;
1504 }
1505 }
1506
1507 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001508 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001509 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1510 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1511 if (RHS_CR.isEmptySet())
1512 return ConstantInt::getFalse(CI->getContext());
1513 if (RHS_CR.isFullSet())
1514 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001515
Nick Lewycky3a73e342011-03-04 07:00:57 +00001516 // Many binary operators with constant RHS have easy to compute constant
1517 // range. Use them to check whether the comparison is a tautology.
1518 uint32_t Width = CI->getBitWidth();
1519 APInt Lower = APInt(Width, 0);
1520 APInt Upper = APInt(Width, 0);
1521 ConstantInt *CI2;
1522 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1523 // 'urem x, CI2' produces [0, CI2).
1524 Upper = CI2->getValue();
1525 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1526 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1527 Upper = CI2->getValue().abs();
1528 Lower = (-Upper) + 1;
1529 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1530 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1531 APInt NegOne = APInt::getAllOnesValue(Width);
1532 if (!CI2->isZero())
1533 Upper = NegOne.udiv(CI2->getValue()) + 1;
1534 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1535 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1536 APInt IntMin = APInt::getSignedMinValue(Width);
1537 APInt IntMax = APInt::getSignedMaxValue(Width);
1538 APInt Val = CI2->getValue().abs();
1539 if (!Val.isMinValue()) {
1540 Lower = IntMin.sdiv(Val);
1541 Upper = IntMax.sdiv(Val) + 1;
1542 }
1543 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1544 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1545 APInt NegOne = APInt::getAllOnesValue(Width);
1546 if (CI2->getValue().ult(Width))
1547 Upper = NegOne.lshr(CI2->getValue()) + 1;
1548 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1549 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1550 APInt IntMin = APInt::getSignedMinValue(Width);
1551 APInt IntMax = APInt::getSignedMaxValue(Width);
1552 if (CI2->getValue().ult(Width)) {
1553 Lower = IntMin.ashr(CI2->getValue());
1554 Upper = IntMax.ashr(CI2->getValue()) + 1;
1555 }
1556 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1557 // 'or x, CI2' produces [CI2, UINT_MAX].
1558 Lower = CI2->getValue();
1559 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1560 // 'and x, CI2' produces [0, CI2].
1561 Upper = CI2->getValue() + 1;
1562 }
1563 if (Lower != Upper) {
1564 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1565 if (RHS_CR.contains(LHS_CR))
1566 return ConstantInt::getTrue(RHS->getContext());
1567 if (RHS_CR.inverse().contains(LHS_CR))
1568 return ConstantInt::getFalse(RHS->getContext());
1569 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001570 }
1571
Duncan Sands9d32f602011-01-20 13:21:55 +00001572 // Compare of cast, for example (zext X) != 0 -> X != 0
1573 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1574 Instruction *LI = cast<CastInst>(LHS);
1575 Value *SrcOp = LI->getOperand(0);
1576 const Type *SrcTy = SrcOp->getType();
1577 const Type *DstTy = LI->getType();
1578
1579 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1580 // if the integer type is the same size as the pointer type.
1581 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1582 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1583 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1584 // Transfer the cast to the constant.
1585 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1586 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1587 TD, DT, MaxRecurse-1))
1588 return V;
1589 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1590 if (RI->getOperand(0)->getType() == SrcTy)
1591 // Compare without the cast.
1592 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1593 TD, DT, MaxRecurse-1))
1594 return V;
1595 }
1596 }
1597
1598 if (isa<ZExtInst>(LHS)) {
1599 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1600 // same type.
1601 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1602 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1603 // Compare X and Y. Note that signed predicates become unsigned.
1604 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1605 SrcOp, RI->getOperand(0), TD, DT,
1606 MaxRecurse-1))
1607 return V;
1608 }
1609 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1610 // too. If not, then try to deduce the result of the comparison.
1611 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1612 // Compute the constant that would happen if we truncated to SrcTy then
1613 // reextended to DstTy.
1614 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1615 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1616
1617 // If the re-extended constant didn't change then this is effectively
1618 // also a case of comparing two zero-extended values.
1619 if (RExt == CI && MaxRecurse)
1620 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1621 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1622 return V;
1623
1624 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1625 // there. Use this to work out the result of the comparison.
1626 if (RExt != CI) {
1627 switch (Pred) {
1628 default:
1629 assert(false && "Unknown ICmp predicate!");
1630 // LHS <u RHS.
1631 case ICmpInst::ICMP_EQ:
1632 case ICmpInst::ICMP_UGT:
1633 case ICmpInst::ICMP_UGE:
1634 return ConstantInt::getFalse(CI->getContext());
1635
1636 case ICmpInst::ICMP_NE:
1637 case ICmpInst::ICMP_ULT:
1638 case ICmpInst::ICMP_ULE:
1639 return ConstantInt::getTrue(CI->getContext());
1640
1641 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1642 // is non-negative then LHS <s RHS.
1643 case ICmpInst::ICMP_SGT:
1644 case ICmpInst::ICMP_SGE:
1645 return CI->getValue().isNegative() ?
1646 ConstantInt::getTrue(CI->getContext()) :
1647 ConstantInt::getFalse(CI->getContext());
1648
1649 case ICmpInst::ICMP_SLT:
1650 case ICmpInst::ICMP_SLE:
1651 return CI->getValue().isNegative() ?
1652 ConstantInt::getFalse(CI->getContext()) :
1653 ConstantInt::getTrue(CI->getContext());
1654 }
1655 }
1656 }
1657 }
1658
1659 if (isa<SExtInst>(LHS)) {
1660 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1661 // same type.
1662 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1663 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1664 // Compare X and Y. Note that the predicate does not change.
1665 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1666 TD, DT, MaxRecurse-1))
1667 return V;
1668 }
1669 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1670 // too. If not, then try to deduce the result of the comparison.
1671 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1672 // Compute the constant that would happen if we truncated to SrcTy then
1673 // reextended to DstTy.
1674 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1675 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1676
1677 // If the re-extended constant didn't change then this is effectively
1678 // also a case of comparing two sign-extended values.
1679 if (RExt == CI && MaxRecurse)
1680 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1681 MaxRecurse-1))
1682 return V;
1683
1684 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1685 // bits there. Use this to work out the result of the comparison.
1686 if (RExt != CI) {
1687 switch (Pred) {
1688 default:
1689 assert(false && "Unknown ICmp predicate!");
1690 case ICmpInst::ICMP_EQ:
1691 return ConstantInt::getFalse(CI->getContext());
1692 case ICmpInst::ICMP_NE:
1693 return ConstantInt::getTrue(CI->getContext());
1694
1695 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1696 // LHS >s RHS.
1697 case ICmpInst::ICMP_SGT:
1698 case ICmpInst::ICMP_SGE:
1699 return CI->getValue().isNegative() ?
1700 ConstantInt::getTrue(CI->getContext()) :
1701 ConstantInt::getFalse(CI->getContext());
1702 case ICmpInst::ICMP_SLT:
1703 case ICmpInst::ICMP_SLE:
1704 return CI->getValue().isNegative() ?
1705 ConstantInt::getFalse(CI->getContext()) :
1706 ConstantInt::getTrue(CI->getContext());
1707
1708 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1709 // LHS >u RHS.
1710 case ICmpInst::ICMP_UGT:
1711 case ICmpInst::ICMP_UGE:
1712 // Comparison is true iff the LHS <s 0.
1713 if (MaxRecurse)
1714 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1715 Constant::getNullValue(SrcTy),
1716 TD, DT, MaxRecurse-1))
1717 return V;
1718 break;
1719 case ICmpInst::ICMP_ULT:
1720 case ICmpInst::ICMP_ULE:
1721 // Comparison is true iff the LHS >=s 0.
1722 if (MaxRecurse)
1723 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1724 Constant::getNullValue(SrcTy),
1725 TD, DT, MaxRecurse-1))
1726 return V;
1727 break;
1728 }
1729 }
1730 }
1731 }
1732 }
1733
Duncan Sands52fb8462011-02-13 17:15:40 +00001734 // Special logic for binary operators.
1735 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1736 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1737 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001738 // Analyze the case when either LHS or RHS is an add instruction.
1739 Value *A = 0, *B = 0, *C = 0, *D = 0;
1740 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1741 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1742 if (LBO && LBO->getOpcode() == Instruction::Add) {
1743 A = LBO->getOperand(0); B = LBO->getOperand(1);
1744 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1745 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1746 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1747 }
1748 if (RBO && RBO->getOpcode() == Instruction::Add) {
1749 C = RBO->getOperand(0); D = RBO->getOperand(1);
1750 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1751 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1752 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1753 }
1754
1755 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1756 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1757 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1758 Constant::getNullValue(RHS->getType()),
1759 TD, DT, MaxRecurse-1))
1760 return V;
1761
1762 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1763 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1764 if (Value *V = SimplifyICmpInst(Pred,
1765 Constant::getNullValue(LHS->getType()),
1766 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1767 return V;
1768
1769 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1770 if (A && C && (A == C || A == D || B == C || B == D) &&
1771 NoLHSWrapProblem && NoRHSWrapProblem) {
1772 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1773 Value *Y = (A == C || A == D) ? B : A;
1774 Value *Z = (C == A || C == B) ? D : C;
1775 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1776 return V;
1777 }
1778 }
1779
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001780 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00001781 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001782 switch (Pred) {
1783 default:
1784 break;
Nick Lewycky78679272011-03-04 10:06:52 +00001785 case ICmpInst::ICMP_SGT:
1786 case ICmpInst::ICMP_SGE:
1787 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1788 if (!KnownNonNegative)
1789 break;
1790 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001791 case ICmpInst::ICMP_EQ:
1792 case ICmpInst::ICMP_UGT:
1793 case ICmpInst::ICMP_UGE:
Duncan Sands448a6d32011-05-02 18:51:41 +00001794 // getNullValue also works for vectors, unlike getFalse.
1795 return Constant::getNullValue(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00001796 case ICmpInst::ICMP_SLT:
1797 case ICmpInst::ICMP_SLE:
1798 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1799 if (!KnownNonNegative)
1800 break;
1801 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001802 case ICmpInst::ICMP_NE:
1803 case ICmpInst::ICMP_ULT:
1804 case ICmpInst::ICMP_ULE:
Duncan Sands448a6d32011-05-02 18:51:41 +00001805 // getAllOnesValue also works for vectors, unlike getTrue.
1806 return Constant::getAllOnesValue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001807 }
1808 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001809 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1810 bool KnownNonNegative, KnownNegative;
1811 switch (Pred) {
1812 default:
1813 break;
1814 case ICmpInst::ICMP_SGT:
1815 case ICmpInst::ICMP_SGE:
1816 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1817 if (!KnownNonNegative)
1818 break;
1819 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001820 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001821 case ICmpInst::ICMP_UGT:
1822 case ICmpInst::ICMP_UGE:
Duncan Sands448a6d32011-05-02 18:51:41 +00001823 // getAllOnesValue also works for vectors, unlike getTrue.
1824 return Constant::getAllOnesValue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001825 case ICmpInst::ICMP_SLT:
1826 case ICmpInst::ICMP_SLE:
1827 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1828 if (!KnownNonNegative)
1829 break;
1830 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001831 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001832 case ICmpInst::ICMP_ULT:
1833 case ICmpInst::ICMP_ULE:
Duncan Sands448a6d32011-05-02 18:51:41 +00001834 // getNullValue also works for vectors, unlike getFalse.
1835 return Constant::getNullValue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001836 }
1837 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001838
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001839 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1840 LBO->getOperand(1) == RBO->getOperand(1)) {
1841 switch (LBO->getOpcode()) {
1842 default: break;
1843 case Instruction::UDiv:
1844 case Instruction::LShr:
1845 if (ICmpInst::isSigned(Pred))
1846 break;
1847 // fall-through
1848 case Instruction::SDiv:
1849 case Instruction::AShr:
1850 if (!LBO->isExact() && !RBO->isExact())
1851 break;
1852 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1853 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1854 return V;
1855 break;
1856 case Instruction::Shl: {
1857 bool NUW = LBO->hasNoUnsignedWrap() && LBO->hasNoUnsignedWrap();
1858 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1859 if (!NUW && !NSW)
1860 break;
1861 if (!NSW && ICmpInst::isSigned(Pred))
1862 break;
1863 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1864 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1865 return V;
1866 break;
1867 }
1868 }
1869 }
1870
Duncan Sands1ac7c992010-11-07 16:12:23 +00001871 // If the comparison is with the result of a select instruction, check whether
1872 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001873 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1874 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001875 return V;
1876
1877 // If the comparison is with the result of a phi instruction, check whether
1878 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001879 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1880 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001881 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00001882
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001883 return 0;
1884}
1885
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001886Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001887 const TargetData *TD, const DominatorTree *DT) {
1888 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001889}
1890
Chris Lattner9dbb4292009-11-09 23:28:39 +00001891/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1892/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001893static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001894 const TargetData *TD, const DominatorTree *DT,
1895 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001896 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1897 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1898
Chris Lattnerd06094f2009-11-10 00:55:12 +00001899 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001900 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1901 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00001902
Chris Lattnerd06094f2009-11-10 00:55:12 +00001903 // If we have a constant, make sure it is on the RHS.
1904 std::swap(LHS, RHS);
1905 Pred = CmpInst::getSwappedPredicate(Pred);
1906 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001907
Chris Lattner210c5d42009-11-09 23:55:12 +00001908 // Fold trivial predicates.
1909 if (Pred == FCmpInst::FCMP_FALSE)
1910 return ConstantInt::get(GetCompareTy(LHS), 0);
1911 if (Pred == FCmpInst::FCMP_TRUE)
1912 return ConstantInt::get(GetCompareTy(LHS), 1);
1913
Chris Lattner210c5d42009-11-09 23:55:12 +00001914 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1915 return UndefValue::get(GetCompareTy(LHS));
1916
1917 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00001918 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001919 if (CmpInst::isTrueWhenEqual(Pred))
1920 return ConstantInt::get(GetCompareTy(LHS), 1);
1921 if (CmpInst::isFalseWhenEqual(Pred))
1922 return ConstantInt::get(GetCompareTy(LHS), 0);
1923 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001924
Chris Lattner210c5d42009-11-09 23:55:12 +00001925 // Handle fcmp with constant RHS
1926 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1927 // If the constant is a nan, see if we can fold the comparison based on it.
1928 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1929 if (CFP->getValueAPF().isNaN()) {
1930 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1931 return ConstantInt::getFalse(CFP->getContext());
1932 assert(FCmpInst::isUnordered(Pred) &&
1933 "Comparison must be either ordered or unordered!");
1934 // True if unordered.
1935 return ConstantInt::getTrue(CFP->getContext());
1936 }
Dan Gohman6b617a72010-02-22 04:06:03 +00001937 // Check whether the constant is an infinity.
1938 if (CFP->getValueAPF().isInfinity()) {
1939 if (CFP->getValueAPF().isNegative()) {
1940 switch (Pred) {
1941 case FCmpInst::FCMP_OLT:
1942 // No value is ordered and less than negative infinity.
1943 return ConstantInt::getFalse(CFP->getContext());
1944 case FCmpInst::FCMP_UGE:
1945 // All values are unordered with or at least negative infinity.
1946 return ConstantInt::getTrue(CFP->getContext());
1947 default:
1948 break;
1949 }
1950 } else {
1951 switch (Pred) {
1952 case FCmpInst::FCMP_OGT:
1953 // No value is ordered and greater than infinity.
1954 return ConstantInt::getFalse(CFP->getContext());
1955 case FCmpInst::FCMP_ULE:
1956 // All values are unordered with and at most infinity.
1957 return ConstantInt::getTrue(CFP->getContext());
1958 default:
1959 break;
1960 }
1961 }
1962 }
Chris Lattner210c5d42009-11-09 23:55:12 +00001963 }
1964 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001965
Duncan Sands92826de2010-11-07 16:46:25 +00001966 // If the comparison is with the result of a select instruction, check whether
1967 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001968 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1969 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001970 return V;
1971
1972 // If the comparison is with the result of a phi instruction, check whether
1973 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001974 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1975 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001976 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00001977
Chris Lattner9dbb4292009-11-09 23:28:39 +00001978 return 0;
1979}
1980
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001981Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001982 const TargetData *TD, const DominatorTree *DT) {
1983 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001984}
1985
Chris Lattner04754262010-04-20 05:32:14 +00001986/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1987/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00001988Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1989 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00001990 // select true, X, Y -> X
1991 // select false, X, Y -> Y
1992 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1993 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001994
Chris Lattner04754262010-04-20 05:32:14 +00001995 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00001996 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00001997 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001998
Chris Lattner04754262010-04-20 05:32:14 +00001999 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2000 return FalseVal;
2001 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2002 return TrueVal;
2003 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2004 if (isa<Constant>(TrueVal))
2005 return TrueVal;
2006 return FalseVal;
2007 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002008
Chris Lattner04754262010-04-20 05:32:14 +00002009 return 0;
2010}
2011
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002012/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2013/// fold the result. If not, this returns null.
2014Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00002015 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002016 // The type of the GEP pointer operand.
2017 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
2018
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002019 // getelementptr P -> P.
2020 if (NumOps == 1)
2021 return Ops[0];
2022
Duncan Sands85bbff62010-11-22 13:42:49 +00002023 if (isa<UndefValue>(Ops[0])) {
2024 // Compute the (pointer) type returned by the GEP instruction.
2025 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
2026 NumOps-1);
2027 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2028 return UndefValue::get(GEPTy);
2029 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002030
Duncan Sandse60d79f2010-11-21 13:53:09 +00002031 if (NumOps == 2) {
2032 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002033 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2034 if (C->isZero())
2035 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002036 // getelementptr P, N -> P if P points to a type of zero size.
2037 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002038 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00002039 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002040 return Ops[0];
2041 }
2042 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002043
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002044 // Check to see if this is constant foldable.
2045 for (unsigned i = 0; i != NumOps; ++i)
2046 if (!isa<Constant>(Ops[i]))
2047 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002048
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002049 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
2050 (Constant *const*)Ops+1, NumOps-1);
2051}
2052
Duncan Sandsff103412010-11-17 04:30:22 +00002053/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2054static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2055 // If all of the PHI's incoming values are the same then replace the PHI node
2056 // with the common value.
2057 Value *CommonValue = 0;
2058 bool HasUndefInput = false;
2059 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2060 Value *Incoming = PN->getIncomingValue(i);
2061 // If the incoming value is the phi node itself, it can safely be skipped.
2062 if (Incoming == PN) continue;
2063 if (isa<UndefValue>(Incoming)) {
2064 // Remember that we saw an undef value, but otherwise ignore them.
2065 HasUndefInput = true;
2066 continue;
2067 }
2068 if (CommonValue && Incoming != CommonValue)
2069 return 0; // Not the same, bail out.
2070 CommonValue = Incoming;
2071 }
2072
2073 // If CommonValue is null then all of the incoming values were either undef or
2074 // equal to the phi node itself.
2075 if (!CommonValue)
2076 return UndefValue::get(PN->getType());
2077
2078 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2079 // instruction, we cannot return X as the result of the PHI node unless it
2080 // dominates the PHI block.
2081 if (HasUndefInput)
2082 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2083
2084 return CommonValue;
2085}
2086
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002087
Chris Lattnerd06094f2009-11-10 00:55:12 +00002088//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002089
Chris Lattnerd06094f2009-11-10 00:55:12 +00002090/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2091/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002092static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002093 const TargetData *TD, const DominatorTree *DT,
2094 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002095 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002096 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002097 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002098 TD, DT, MaxRecurse);
2099 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002100 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002101 TD, DT, MaxRecurse);
2102 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands593faa52011-01-28 16:51:11 +00002103 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2104 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002105 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002106 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2107 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2108 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002109 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002110 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002111 TD, DT, MaxRecurse);
2112 case Instruction::LShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002113 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002114 case Instruction::AShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002115 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002116 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002117 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002118 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002119 default:
2120 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2121 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2122 Constant *COps[] = {CLHS, CRHS};
2123 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
2124 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002125
Duncan Sands566edb02010-12-21 08:49:00 +00002126 // If the operation is associative, try some generic simplifications.
2127 if (Instruction::isAssociative(Opcode))
2128 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2129 MaxRecurse))
2130 return V;
2131
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002132 // If the operation is with the result of a select instruction, check whether
2133 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002134 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00002135 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002136 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002137 return V;
2138
2139 // If the operation is with the result of a phi instruction, check whether
2140 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002141 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2142 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002143 return V;
2144
Chris Lattnerd06094f2009-11-10 00:55:12 +00002145 return 0;
2146 }
2147}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002148
Duncan Sands12a86f52010-11-14 11:23:23 +00002149Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002150 const TargetData *TD, const DominatorTree *DT) {
2151 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002152}
2153
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002154/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2155/// fold the result.
2156static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002157 const TargetData *TD, const DominatorTree *DT,
2158 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002159 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00002160 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2161 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002162}
2163
2164Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002165 const TargetData *TD, const DominatorTree *DT) {
2166 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002167}
Chris Lattnere3453782009-11-10 01:08:51 +00002168
2169/// SimplifyInstruction - See if we can compute a simplified version of this
2170/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002171Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2172 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002173 Value *Result;
2174
Chris Lattnere3453782009-11-10 01:08:51 +00002175 switch (I->getOpcode()) {
2176 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002177 Result = ConstantFoldInstruction(I, TD);
2178 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002179 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002180 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2181 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2182 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2183 TD, DT);
2184 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002185 case Instruction::Sub:
2186 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2187 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2188 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2189 TD, DT);
2190 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002191 case Instruction::Mul:
2192 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2193 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002194 case Instruction::SDiv:
2195 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2196 break;
2197 case Instruction::UDiv:
2198 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2199 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002200 case Instruction::FDiv:
2201 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2202 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002203 case Instruction::SRem:
2204 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2205 break;
2206 case Instruction::URem:
2207 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2208 break;
2209 case Instruction::FRem:
2210 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2211 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002212 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002213 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2214 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2215 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2216 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002217 break;
2218 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002219 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2220 cast<BinaryOperator>(I)->isExact(),
2221 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002222 break;
2223 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002224 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2225 cast<BinaryOperator>(I)->isExact(),
2226 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002227 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002228 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002229 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2230 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002231 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002232 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2233 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002234 case Instruction::Xor:
2235 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2236 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002237 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002238 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2239 I->getOperand(0), I->getOperand(1), TD, DT);
2240 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002241 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002242 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2243 I->getOperand(0), I->getOperand(1), TD, DT);
2244 break;
Chris Lattner04754262010-04-20 05:32:14 +00002245 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002246 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2247 I->getOperand(2), TD, DT);
2248 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002249 case Instruction::GetElementPtr: {
2250 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00002251 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
2252 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002253 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002254 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002255 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2256 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002257 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002258
2259 /// If called on unreachable code, the above logic may report that the
2260 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002261 /// detecting that case here, returning a safe value instead.
2262 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002263}
2264
Chris Lattner40d8c282009-11-10 22:26:15 +00002265/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2266/// delete the From instruction. In addition to a basic RAUW, this does a
2267/// recursive simplification of the newly formed instructions. This catches
2268/// things where one simplification exposes other opportunities. This only
2269/// simplifies and deletes scalar operations, it does not change the CFG.
2270///
2271void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002272 const TargetData *TD,
2273 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002274 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002275
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002276 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2277 // we can know if it gets deleted out from under us or replaced in a
2278 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002279 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002280 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002281
Chris Lattner40d8c282009-11-10 22:26:15 +00002282 while (!From->use_empty()) {
2283 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002284 Use &TheUse = From->use_begin().getUse();
2285 Instruction *User = cast<Instruction>(TheUse.getUser());
2286 TheUse = To;
2287
2288 // Check to see if the instruction can be folded due to the operand
2289 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2290 // the 'or' with -1.
2291 Value *SimplifiedVal;
2292 {
2293 // Sanity check to make sure 'User' doesn't dangle across
2294 // SimplifyInstruction.
2295 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002296
Duncan Sandseff05812010-11-14 18:36:10 +00002297 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002298 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002299 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002300
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002301 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00002302 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002303 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2304 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002305
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002306 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002307
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002308 // If the recursive simplification ended up revisiting and deleting
2309 // 'From' then we're done.
2310 if (From == 0)
2311 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002312 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002313
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002314 // If 'From' has value handles referring to it, do a real RAUW to update them.
2315 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002316
Chris Lattner40d8c282009-11-10 22:26:15 +00002317 From->eraseFromParent();
2318}