blob: 7bb8f6999281ccd3bd72ba75a3c0f97427702836 [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sands4cd2ad12010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsee9a2e32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
21#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000022#include "llvm/Analysis/InstructionSimplify.h"
23#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000024#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000025#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000026#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000027#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000028#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000029using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000030using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000031
Duncan Sands124708d2011-01-01 20:08:02 +000032#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000033
Duncan Sandsa3c44a52010-12-22 09:40:51 +000034STATISTIC(NumExpand, "Number of expansions");
35STATISTIC(NumFactor , "Number of factorizations");
36STATISTIC(NumReassoc, "Number of reassociations");
37
Duncan Sands82fdab32010-12-21 14:00:22 +000038static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
39 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000040static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000041 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000042static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000043 const DominatorTree *, unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000044static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
45 const DominatorTree *, unsigned);
46static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
47 const DominatorTree *, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000048
49/// ValueDominatesPHI - Does the given value dominate the specified phi node?
50static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
51 Instruction *I = dyn_cast<Instruction>(V);
52 if (!I)
53 // Arguments and constants dominate all instructions.
54 return true;
55
56 // If we have a DominatorTree then do a precise test.
57 if (DT)
58 return DT->dominates(I, P);
59
60 // Otherwise, if the instruction is in the entry block, and is not an invoke,
61 // then it obviously dominates all phi nodes.
62 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
63 !isa<InvokeInst>(I))
64 return true;
65
66 return false;
67}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000068
Duncan Sands3421d902010-12-21 13:32:22 +000069/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
70/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
71/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
72/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
73/// Returns the simplified value, or null if no simplification was performed.
74static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +000075 unsigned OpcToExpand, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +000076 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +000077 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000078 // Recursion is always used, so bail out at once if we already hit the limit.
79 if (!MaxRecurse--)
80 return 0;
81
82 // Check whether the expression has the form "(A op' B) op C".
83 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
84 if (Op0->getOpcode() == OpcodeToExpand) {
85 // It does! Try turning it into "(A op C) op' (B op C)".
86 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
87 // Do "A op C" and "B op C" both simplify?
88 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
89 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
90 // They do! Return "L op' R" if it simplifies or is already available.
91 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +000092 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
93 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +000094 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000095 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +000096 }
Duncan Sands3421d902010-12-21 13:32:22 +000097 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +000098 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
99 MaxRecurse)) {
100 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000101 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000102 }
Duncan Sands3421d902010-12-21 13:32:22 +0000103 }
104 }
105
106 // Check whether the expression has the form "A op (B op' C)".
107 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
108 if (Op1->getOpcode() == OpcodeToExpand) {
109 // It does! Try turning it into "(A op B) op' (A op C)".
110 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
111 // Do "A op B" and "A op C" both simplify?
112 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
113 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
114 // They do! Return "L op' R" if it simplifies or is already available.
115 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000116 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
117 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000118 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000119 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000120 }
Duncan Sands3421d902010-12-21 13:32:22 +0000121 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000122 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
123 MaxRecurse)) {
124 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000125 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000126 }
Duncan Sands3421d902010-12-21 13:32:22 +0000127 }
128 }
129
130 return 0;
131}
132
133/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
134/// using the operation OpCodeToExtract. For example, when Opcode is Add and
135/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
136/// Returns the simplified value, or null if no simplification was performed.
137static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000138 unsigned OpcToExtract, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +0000139 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000140 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000141 // Recursion is always used, so bail out at once if we already hit the limit.
142 if (!MaxRecurse--)
143 return 0;
144
145 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
146 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
147
148 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
149 !Op1 || Op1->getOpcode() != OpcodeToExtract)
150 return 0;
151
152 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000153 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
154 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000155
156 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
157 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
158 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000159 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
160 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000161 // Form "A op' (B op DD)" if it simplifies completely.
162 // Does "B op DD" simplify?
163 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
164 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000165 // If V equals B then "A op' V" is just the LHS. If V equals DD then
166 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000167 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000168 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000169 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000170 }
Duncan Sands3421d902010-12-21 13:32:22 +0000171 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000172 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
173 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000174 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000175 }
Duncan Sands3421d902010-12-21 13:32:22 +0000176 }
177 }
178
179 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
180 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
181 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000182 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
183 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000184 // Form "(A op CC) op' B" if it simplifies completely..
185 // Does "A op CC" simplify?
186 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
187 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000188 // If V equals A then "V op' B" is just the LHS. If V equals CC then
189 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000190 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000191 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000192 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000193 }
Duncan Sands3421d902010-12-21 13:32:22 +0000194 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000195 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
196 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000197 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000198 }
Duncan Sands3421d902010-12-21 13:32:22 +0000199 }
200 }
201
202 return 0;
203}
204
205/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
206/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000207static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000208 const TargetData *TD,
209 const DominatorTree *DT,
210 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000211 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000212 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
213
214 // Recursion is always used, so bail out at once if we already hit the limit.
215 if (!MaxRecurse--)
216 return 0;
217
218 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
219 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
220
221 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
222 if (Op0 && Op0->getOpcode() == Opcode) {
223 Value *A = Op0->getOperand(0);
224 Value *B = Op0->getOperand(1);
225 Value *C = RHS;
226
227 // Does "B op C" simplify?
228 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
229 // It does! Return "A op V" if it simplifies or is already available.
230 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000231 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000232 // Otherwise return "A op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000233 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
234 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000235 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000236 }
Duncan Sands566edb02010-12-21 08:49:00 +0000237 }
238 }
239
240 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
241 if (Op1 && Op1->getOpcode() == Opcode) {
242 Value *A = LHS;
243 Value *B = Op1->getOperand(0);
244 Value *C = Op1->getOperand(1);
245
246 // Does "A op B" simplify?
247 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
248 // It does! Return "V op C" if it simplifies or is already available.
249 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000250 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000251 // Otherwise return "V op C" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000252 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
253 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000254 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000255 }
Duncan Sands566edb02010-12-21 08:49:00 +0000256 }
257 }
258
259 // The remaining transforms require commutativity as well as associativity.
260 if (!Instruction::isCommutative(Opcode))
261 return 0;
262
263 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
264 if (Op0 && Op0->getOpcode() == Opcode) {
265 Value *A = Op0->getOperand(0);
266 Value *B = Op0->getOperand(1);
267 Value *C = RHS;
268
269 // Does "C op A" simplify?
270 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
271 // It does! Return "V op B" if it simplifies or is already available.
272 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000273 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000274 // Otherwise return "V op B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000275 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
276 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000277 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000278 }
Duncan Sands566edb02010-12-21 08:49:00 +0000279 }
280 }
281
282 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
283 if (Op1 && Op1->getOpcode() == Opcode) {
284 Value *A = LHS;
285 Value *B = Op1->getOperand(0);
286 Value *C = Op1->getOperand(1);
287
288 // Does "C op A" simplify?
289 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
290 // It does! Return "B op V" if it simplifies or is already available.
291 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000292 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000293 // Otherwise return "B op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000294 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
295 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000296 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000297 }
Duncan Sands566edb02010-12-21 08:49:00 +0000298 }
299 }
300
301 return 0;
302}
303
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000304/// ThreadBinOpOverSelect - In the case of a binary operation with a select
305/// instruction as an operand, try to simplify the binop by seeing whether
306/// evaluating it on both branches of the select results in the same value.
307/// Returns the common value if so, otherwise returns null.
308static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000309 const TargetData *TD,
310 const DominatorTree *DT,
311 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000312 // Recursion is always used, so bail out at once if we already hit the limit.
313 if (!MaxRecurse--)
314 return 0;
315
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000316 SelectInst *SI;
317 if (isa<SelectInst>(LHS)) {
318 SI = cast<SelectInst>(LHS);
319 } else {
320 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
321 SI = cast<SelectInst>(RHS);
322 }
323
324 // Evaluate the BinOp on the true and false branches of the select.
325 Value *TV;
326 Value *FV;
327 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000328 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
329 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000330 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000331 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
332 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000333 }
334
Duncan Sands7cf85e72011-01-01 16:12:09 +0000335 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000336 // If they both failed to simplify then return null.
337 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000338 return TV;
339
340 // If one branch simplified to undef, return the other one.
341 if (TV && isa<UndefValue>(TV))
342 return FV;
343 if (FV && isa<UndefValue>(FV))
344 return TV;
345
346 // If applying the operation did not change the true and false select values,
347 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000348 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000349 return SI;
350
351 // If one branch simplified and the other did not, and the simplified
352 // value is equal to the unsimplified one, return the simplified value.
353 // For example, select (cond, X, X & Z) & Z -> X & Z.
354 if ((FV && !TV) || (TV && !FV)) {
355 // Check that the simplified value has the form "X op Y" where "op" is the
356 // same as the original operation.
357 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
358 if (Simplified && Simplified->getOpcode() == Opcode) {
359 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
360 // We already know that "op" is the same as for the simplified value. See
361 // if the operands match too. If so, return the simplified value.
362 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
363 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
364 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000365 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
366 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000367 return Simplified;
368 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000369 Simplified->getOperand(1) == UnsimplifiedLHS &&
370 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000371 return Simplified;
372 }
373 }
374
375 return 0;
376}
377
378/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
379/// try to simplify the comparison by seeing whether both branches of the select
380/// result in the same value. Returns the common value if so, otherwise returns
381/// null.
382static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000383 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000384 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000385 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000386 // Recursion is always used, so bail out at once if we already hit the limit.
387 if (!MaxRecurse--)
388 return 0;
389
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000390 // Make sure the select is on the LHS.
391 if (!isa<SelectInst>(LHS)) {
392 std::swap(LHS, RHS);
393 Pred = CmpInst::getSwappedPredicate(Pred);
394 }
395 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
396 SelectInst *SI = cast<SelectInst>(LHS);
397
Duncan Sands50ca4d32011-02-03 09:37:39 +0000398 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000399 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000400 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000401 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000402 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000403 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000404 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000405 // It does! If they simplified to the same value, then use it as the
406 // result of the original comparison.
Duncan Sands124708d2011-01-01 20:08:02 +0000407 if (TCmp == FCmp)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000408 return TCmp;
Duncan Sands50ca4d32011-02-03 09:37:39 +0000409 Value *Cond = SI->getCondition();
410 // If the false value simplified to false, then the result of the compare
411 // is equal to "Cond && TCmp". This also catches the case when the false
412 // value simplified to false and the true value to true, returning "Cond".
413 if (match(FCmp, m_Zero()))
414 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
415 return V;
416 // If the true value simplified to true, then the result of the compare
417 // is equal to "Cond || FCmp".
418 if (match(TCmp, m_One()))
419 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
420 return V;
421 // Finally, if the false value simplified to true and the true value to
422 // false, then the result of the compare is equal to "!Cond".
423 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
424 if (Value *V =
425 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
426 TD, DT, MaxRecurse))
427 return V;
428 }
429 }
430
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000431 return 0;
432}
433
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000434/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
435/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
436/// it on the incoming phi values yields the same result for every value. If so
437/// returns the common value, otherwise returns null.
438static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000439 const TargetData *TD, const DominatorTree *DT,
440 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000441 // Recursion is always used, so bail out at once if we already hit the limit.
442 if (!MaxRecurse--)
443 return 0;
444
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000445 PHINode *PI;
446 if (isa<PHINode>(LHS)) {
447 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000448 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
449 if (!ValueDominatesPHI(RHS, PI, DT))
450 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000451 } else {
452 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
453 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000454 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
455 if (!ValueDominatesPHI(LHS, PI, DT))
456 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000457 }
458
459 // Evaluate the BinOp on the incoming phi values.
460 Value *CommonValue = 0;
461 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000462 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000463 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000464 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000465 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000466 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
467 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000468 // If the operation failed to simplify, or simplified to a different value
469 // to previously, then give up.
470 if (!V || (CommonValue && V != CommonValue))
471 return 0;
472 CommonValue = V;
473 }
474
475 return CommonValue;
476}
477
478/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
479/// try to simplify the comparison by seeing whether comparing with all of the
480/// incoming phi values yields the same result every time. If so returns the
481/// common result, otherwise returns null.
482static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000483 const TargetData *TD, const DominatorTree *DT,
484 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000485 // Recursion is always used, so bail out at once if we already hit the limit.
486 if (!MaxRecurse--)
487 return 0;
488
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000489 // Make sure the phi is on the LHS.
490 if (!isa<PHINode>(LHS)) {
491 std::swap(LHS, RHS);
492 Pred = CmpInst::getSwappedPredicate(Pred);
493 }
494 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
495 PHINode *PI = cast<PHINode>(LHS);
496
Duncan Sands18450092010-11-16 12:16:38 +0000497 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
498 if (!ValueDominatesPHI(RHS, PI, DT))
499 return 0;
500
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000501 // Evaluate the BinOp on the incoming phi values.
502 Value *CommonValue = 0;
503 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000504 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000505 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000506 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000507 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000508 // If the operation failed to simplify, or simplified to a different value
509 // to previously, then give up.
510 if (!V || (CommonValue && V != CommonValue))
511 return 0;
512 CommonValue = V;
513 }
514
515 return CommonValue;
516}
517
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000518/// SimplifyAddInst - Given operands for an Add, see if we can
519/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000520static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
521 const TargetData *TD, const DominatorTree *DT,
522 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000523 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
524 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
525 Constant *Ops[] = { CLHS, CRHS };
526 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
527 Ops, 2, TD);
528 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000529
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000530 // Canonicalize the constant to the RHS.
531 std::swap(Op0, Op1);
532 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000533
Duncan Sandsfea3b212010-12-15 14:07:39 +0000534 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000535 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000536 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000537
Duncan Sandsfea3b212010-12-15 14:07:39 +0000538 // X + 0 -> X
539 if (match(Op1, m_Zero()))
540 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000541
Duncan Sandsfea3b212010-12-15 14:07:39 +0000542 // X + (Y - X) -> Y
543 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000544 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000545 Value *Y = 0;
546 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
547 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000548 return Y;
549
550 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000551 if (match(Op0, m_Not(m_Specific(Op1))) ||
552 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000553 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000554
Duncan Sands82fdab32010-12-21 14:00:22 +0000555 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000556 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000557 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
558 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000559
Duncan Sands566edb02010-12-21 08:49:00 +0000560 // Try some generic simplifications for associative operations.
561 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
562 MaxRecurse))
563 return V;
564
Duncan Sands3421d902010-12-21 13:32:22 +0000565 // Mul distributes over Add. Try some generic simplifications based on this.
566 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
567 TD, DT, MaxRecurse))
568 return V;
569
Duncan Sands87689cf2010-11-19 09:20:39 +0000570 // Threading Add over selects and phi nodes is pointless, so don't bother.
571 // Threading over the select in "A + select(cond, B, C)" means evaluating
572 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573 // only if B and C are equal. If B and C are equal then (since we assume
574 // that operands have already been simplified) "select(cond, B, C)" should
575 // have been simplified to the common value of B and C already. Analysing
576 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
577 // for threading over phi nodes.
578
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000579 return 0;
580}
581
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000582Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
583 const TargetData *TD, const DominatorTree *DT) {
584 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
585}
586
Duncan Sandsfea3b212010-12-15 14:07:39 +0000587/// SimplifySubInst - Given operands for a Sub, see if we can
588/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000589static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000590 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000591 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000592 if (Constant *CLHS = dyn_cast<Constant>(Op0))
593 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
594 Constant *Ops[] = { CLHS, CRHS };
595 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
596 Ops, 2, TD);
597 }
598
599 // X - undef -> undef
600 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000601 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000602 return UndefValue::get(Op0->getType());
603
604 // X - 0 -> X
605 if (match(Op1, m_Zero()))
606 return Op0;
607
608 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000609 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000610 return Constant::getNullValue(Op0->getType());
611
Duncan Sandsfe02c692011-01-18 09:24:58 +0000612 // (X*2) - X -> X
613 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000614 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000615 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
616 match(Op0, m_Shl(m_Specific(Op1), m_One())))
617 return Op1;
618
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000619 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
620 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
621 Value *Y = 0, *Z = Op1;
622 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
623 // See if "V === Y - Z" simplifies.
624 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
625 // It does! Now see if "X + V" simplifies.
626 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
627 MaxRecurse-1)) {
628 // It does, we successfully reassociated!
629 ++NumReassoc;
630 return W;
631 }
632 // See if "V === X - Z" simplifies.
633 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
634 // It does! Now see if "Y + V" simplifies.
635 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
636 MaxRecurse-1)) {
637 // It does, we successfully reassociated!
638 ++NumReassoc;
639 return W;
640 }
641 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000642
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000643 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
644 // For example, X - (X + 1) -> -1
645 X = Op0;
646 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
647 // See if "V === X - Y" simplifies.
648 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
649 // It does! Now see if "V - Z" simplifies.
650 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
651 MaxRecurse-1)) {
652 // It does, we successfully reassociated!
653 ++NumReassoc;
654 return W;
655 }
656 // See if "V === X - Z" simplifies.
657 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
658 // It does! Now see if "V - Y" simplifies.
659 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
660 MaxRecurse-1)) {
661 // It does, we successfully reassociated!
662 ++NumReassoc;
663 return W;
664 }
665 }
666
667 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
668 // For example, X - (X - Y) -> Y.
669 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000670 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
671 // See if "V === Z - X" simplifies.
672 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000673 // It does! Now see if "V + Y" simplifies.
Duncan Sandsc087e202011-01-14 15:26:10 +0000674 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
675 MaxRecurse-1)) {
676 // It does, we successfully reassociated!
677 ++NumReassoc;
678 return W;
679 }
680
Duncan Sands3421d902010-12-21 13:32:22 +0000681 // Mul distributes over Sub. Try some generic simplifications based on this.
682 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
683 TD, DT, MaxRecurse))
684 return V;
685
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000686 // i1 sub -> xor.
687 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
688 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
689 return V;
690
Duncan Sandsfea3b212010-12-15 14:07:39 +0000691 // Threading Sub over selects and phi nodes is pointless, so don't bother.
692 // Threading over the select in "A - select(cond, B, C)" means evaluating
693 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
694 // only if B and C are equal. If B and C are equal then (since we assume
695 // that operands have already been simplified) "select(cond, B, C)" should
696 // have been simplified to the common value of B and C already. Analysing
697 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
698 // for threading over phi nodes.
699
700 return 0;
701}
702
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000703Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
704 const TargetData *TD, const DominatorTree *DT) {
705 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
706}
707
Duncan Sands82fdab32010-12-21 14:00:22 +0000708/// SimplifyMulInst - Given operands for a Mul, see if we can
709/// fold the result. If not, this returns null.
710static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
711 const DominatorTree *DT, unsigned MaxRecurse) {
712 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
713 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
714 Constant *Ops[] = { CLHS, CRHS };
715 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
716 Ops, 2, TD);
717 }
718
719 // Canonicalize the constant to the RHS.
720 std::swap(Op0, Op1);
721 }
722
723 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000724 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000725 return Constant::getNullValue(Op0->getType());
726
727 // X * 0 -> 0
728 if (match(Op1, m_Zero()))
729 return Op1;
730
731 // X * 1 -> X
732 if (match(Op1, m_One()))
733 return Op0;
734
Duncan Sands1895e982011-01-30 18:03:50 +0000735 // (X / Y) * Y -> X if the division is exact.
736 Value *X = 0, *Y = 0;
737 if ((match(Op0, m_SDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
Chris Lattnerc6ee9182011-02-06 22:05:31 +0000738 (match(Op0, m_UDiv(m_Value(X), m_Value(Y))) && Y == Op1) ||
739 (match(Op1, m_SDiv(m_Value(X), m_Value(Y))) && Y == Op0) || // Y * (X / Y)
740 (match(Op1, m_UDiv(m_Value(X), m_Value(Y))) && Y == Op0)) {
741 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 Sandscf80bc12011-01-14 14:44:12 +0000904/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +0000905/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +0000906static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
907 const TargetData *TD, const DominatorTree *DT,
908 unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +0000909 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
910 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
911 Constant *Ops[] = { C0, C1 };
Duncan Sandscf80bc12011-01-14 14:44:12 +0000912 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, 2, TD);
Duncan Sandsc43cee32011-01-14 00:37:45 +0000913 }
914 }
915
Duncan Sandscf80bc12011-01-14 14:44:12 +0000916 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +0000917 if (match(Op0, m_Zero()))
918 return Op0;
919
Duncan Sandscf80bc12011-01-14 14:44:12 +0000920 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +0000921 if (match(Op1, m_Zero()))
922 return Op0;
923
Duncan Sandscf80bc12011-01-14 14:44:12 +0000924 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000925 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +0000926 return Op1;
927
928 // Shifting by the bitwidth or more is undefined.
929 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
930 if (CI->getValue().getLimitedValue() >=
931 Op0->getType()->getScalarSizeInBits())
932 return UndefValue::get(Op0->getType());
933
Duncan Sandscf80bc12011-01-14 14:44:12 +0000934 // If the operation is with the result of a select instruction, check whether
935 // operating on either branch of the select always yields the same value.
936 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
937 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
938 return V;
939
940 // If the operation is with the result of a phi instruction, check whether
941 // operating on all incoming values of the phi always yields the same value.
942 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
943 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
944 return V;
945
946 return 0;
947}
948
949/// SimplifyShlInst - Given operands for an Shl, see if we can
950/// fold the result. If not, this returns null.
951static Value *SimplifyShlInst(Value *Op0, Value *Op1, const TargetData *TD,
952 const DominatorTree *DT, unsigned MaxRecurse) {
953 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
954 return V;
955
956 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000957 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +0000958 return Constant::getNullValue(Op0->getType());
959
Duncan Sandsc43cee32011-01-14 00:37:45 +0000960 return 0;
961}
962
963Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, const TargetData *TD,
964 const DominatorTree *DT) {
965 return ::SimplifyShlInst(Op0, Op1, TD, DT, RecursionLimit);
966}
967
968/// SimplifyLShrInst - Given operands for an LShr, see if we can
969/// fold the result. If not, this returns null.
970static Value *SimplifyLShrInst(Value *Op0, Value *Op1, const TargetData *TD,
971 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +0000972 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
973 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +0000974
975 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000976 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +0000977 return Constant::getNullValue(Op0->getType());
978
Duncan Sandsc43cee32011-01-14 00:37:45 +0000979 return 0;
980}
981
982Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, const TargetData *TD,
983 const DominatorTree *DT) {
984 return ::SimplifyLShrInst(Op0, Op1, TD, DT, RecursionLimit);
985}
986
987/// SimplifyAShrInst - Given operands for an AShr, see if we can
988/// fold the result. If not, this returns null.
989static Value *SimplifyAShrInst(Value *Op0, Value *Op1, const TargetData *TD,
990 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +0000991 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
992 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +0000993
994 // all ones >>a X -> all ones
995 if (match(Op0, m_AllOnes()))
996 return Op0;
997
998 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000999 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001000 return Constant::getAllOnesValue(Op0->getType());
1001
Duncan Sandsc43cee32011-01-14 00:37:45 +00001002 return 0;
1003}
1004
1005Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, const TargetData *TD,
1006 const DominatorTree *DT) {
1007 return ::SimplifyAShrInst(Op0, Op1, TD, DT, RecursionLimit);
1008}
1009
Chris Lattnerd06094f2009-11-10 00:55:12 +00001010/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001011/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001012static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001013 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001014 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1015 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1016 Constant *Ops[] = { CLHS, CRHS };
1017 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1018 Ops, 2, TD);
1019 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001020
Chris Lattnerd06094f2009-11-10 00:55:12 +00001021 // Canonicalize the constant to the RHS.
1022 std::swap(Op0, Op1);
1023 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001024
Chris Lattnerd06094f2009-11-10 00:55:12 +00001025 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001026 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001027 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001028
Chris Lattnerd06094f2009-11-10 00:55:12 +00001029 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001030 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001031 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001032
Duncan Sands2b749872010-11-17 18:52:15 +00001033 // X & 0 = 0
1034 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001035 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001036
Duncan Sands2b749872010-11-17 18:52:15 +00001037 // X & -1 = X
1038 if (match(Op1, m_AllOnes()))
1039 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001040
Chris Lattnerd06094f2009-11-10 00:55:12 +00001041 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +00001042 Value *A = 0, *B = 0;
Duncan Sands124708d2011-01-01 20:08:02 +00001043 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
1044 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001045 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001046
Chris Lattnerd06094f2009-11-10 00:55:12 +00001047 // (A | ?) & A = A
1048 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001049 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001050 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001051
Chris Lattnerd06094f2009-11-10 00:55:12 +00001052 // A & (A | ?) = A
1053 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001054 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001055 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001056
Duncan Sands566edb02010-12-21 08:49:00 +00001057 // Try some generic simplifications for associative operations.
1058 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1059 MaxRecurse))
1060 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001061
Duncan Sands3421d902010-12-21 13:32:22 +00001062 // And distributes over Or. Try some generic simplifications based on this.
1063 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1064 TD, DT, MaxRecurse))
1065 return V;
1066
1067 // And distributes over Xor. Try some generic simplifications based on this.
1068 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1069 TD, DT, MaxRecurse))
1070 return V;
1071
1072 // Or distributes over And. Try some generic simplifications based on this.
1073 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1074 TD, DT, MaxRecurse))
1075 return V;
1076
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001077 // If the operation is with the result of a select instruction, check whether
1078 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001079 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001080 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001081 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001082 return V;
1083
1084 // If the operation is with the result of a phi instruction, check whether
1085 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001086 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001087 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001088 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001089 return V;
1090
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001091 return 0;
1092}
1093
Duncan Sands18450092010-11-16 12:16:38 +00001094Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1095 const DominatorTree *DT) {
1096 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001097}
1098
Chris Lattnerd06094f2009-11-10 00:55:12 +00001099/// SimplifyOrInst - Given operands for an Or, see if we can
1100/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001101static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001102 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001103 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1104 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1105 Constant *Ops[] = { CLHS, CRHS };
1106 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1107 Ops, 2, TD);
1108 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001109
Chris Lattnerd06094f2009-11-10 00:55:12 +00001110 // Canonicalize the constant to the RHS.
1111 std::swap(Op0, Op1);
1112 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001113
Chris Lattnerd06094f2009-11-10 00:55:12 +00001114 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001115 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001116 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001117
Chris Lattnerd06094f2009-11-10 00:55:12 +00001118 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001119 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001120 return Op0;
1121
Duncan Sands2b749872010-11-17 18:52:15 +00001122 // X | 0 = X
1123 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001124 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001125
Duncan Sands2b749872010-11-17 18:52:15 +00001126 // X | -1 = -1
1127 if (match(Op1, m_AllOnes()))
1128 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001129
Chris Lattnerd06094f2009-11-10 00:55:12 +00001130 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +00001131 Value *A = 0, *B = 0;
Duncan Sands124708d2011-01-01 20:08:02 +00001132 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
1133 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001134 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001135
Chris Lattnerd06094f2009-11-10 00:55:12 +00001136 // (A & ?) | A = A
1137 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001138 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001139 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001140
Chris Lattnerd06094f2009-11-10 00:55:12 +00001141 // A | (A & ?) = A
1142 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001143 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001144 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001145
Duncan Sands566edb02010-12-21 08:49:00 +00001146 // Try some generic simplifications for associative operations.
1147 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1148 MaxRecurse))
1149 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001150
Duncan Sands3421d902010-12-21 13:32:22 +00001151 // Or distributes over And. Try some generic simplifications based on this.
1152 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1153 TD, DT, MaxRecurse))
1154 return V;
1155
1156 // And distributes over Or. Try some generic simplifications based on this.
1157 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1158 TD, DT, MaxRecurse))
1159 return V;
1160
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001161 // If the operation is with the result of a select instruction, check whether
1162 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001163 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001164 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001165 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001166 return V;
1167
1168 // If the operation is with the result of a phi instruction, check whether
1169 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001170 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001171 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001172 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001173 return V;
1174
Chris Lattnerd06094f2009-11-10 00:55:12 +00001175 return 0;
1176}
1177
Duncan Sands18450092010-11-16 12:16:38 +00001178Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1179 const DominatorTree *DT) {
1180 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001181}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001182
Duncan Sands2b749872010-11-17 18:52:15 +00001183/// SimplifyXorInst - Given operands for a Xor, see if we can
1184/// fold the result. If not, this returns null.
1185static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1186 const DominatorTree *DT, unsigned MaxRecurse) {
1187 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1188 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1189 Constant *Ops[] = { CLHS, CRHS };
1190 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1191 Ops, 2, TD);
1192 }
1193
1194 // Canonicalize the constant to the RHS.
1195 std::swap(Op0, Op1);
1196 }
1197
1198 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001199 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001200 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001201
1202 // A ^ 0 = A
1203 if (match(Op1, m_Zero()))
1204 return Op0;
1205
1206 // A ^ A = 0
Duncan Sands124708d2011-01-01 20:08:02 +00001207 if (Op0 == Op1)
Duncan Sands2b749872010-11-17 18:52:15 +00001208 return Constant::getNullValue(Op0->getType());
1209
1210 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +00001211 Value *A = 0;
Duncan Sands124708d2011-01-01 20:08:02 +00001212 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
1213 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Duncan Sands2b749872010-11-17 18:52:15 +00001214 return Constant::getAllOnesValue(Op0->getType());
1215
Duncan Sands566edb02010-12-21 08:49:00 +00001216 // Try some generic simplifications for associative operations.
1217 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1218 MaxRecurse))
1219 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001220
Duncan Sands3421d902010-12-21 13:32:22 +00001221 // And distributes over Xor. Try some generic simplifications based on this.
1222 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1223 TD, DT, MaxRecurse))
1224 return V;
1225
Duncan Sands87689cf2010-11-19 09:20:39 +00001226 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1227 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1228 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1229 // only if B and C are equal. If B and C are equal then (since we assume
1230 // that operands have already been simplified) "select(cond, B, C)" should
1231 // have been simplified to the common value of B and C already. Analysing
1232 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1233 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001234
1235 return 0;
1236}
1237
1238Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1239 const DominatorTree *DT) {
1240 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1241}
1242
Chris Lattner210c5d42009-11-09 23:55:12 +00001243static const Type *GetCompareTy(Value *Op) {
1244 return CmpInst::makeCmpResultType(Op->getType());
1245}
1246
Chris Lattner9dbb4292009-11-09 23:28:39 +00001247/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1248/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001249static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001250 const TargetData *TD, const DominatorTree *DT,
1251 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001252 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001253 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001254
Chris Lattnerd06094f2009-11-10 00:55:12 +00001255 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001256 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1257 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001258
1259 // If we have a constant, make sure it is on the RHS.
1260 std::swap(LHS, RHS);
1261 Pred = CmpInst::getSwappedPredicate(Pred);
1262 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001263
Duncan Sands6dc91252011-01-13 08:56:29 +00001264 const Type *ITy = GetCompareTy(LHS); // The return type.
1265 const Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001266
Chris Lattner210c5d42009-11-09 23:55:12 +00001267 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001268 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1269 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001270 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001271 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001272
Duncan Sands6dc91252011-01-13 08:56:29 +00001273 // Special case logic when the operands have i1 type.
1274 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1275 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1276 switch (Pred) {
1277 default: break;
1278 case ICmpInst::ICMP_EQ:
1279 // X == 1 -> X
1280 if (match(RHS, m_One()))
1281 return LHS;
1282 break;
1283 case ICmpInst::ICMP_NE:
1284 // X != 0 -> X
1285 if (match(RHS, m_Zero()))
1286 return LHS;
1287 break;
1288 case ICmpInst::ICMP_UGT:
1289 // X >u 0 -> X
1290 if (match(RHS, m_Zero()))
1291 return LHS;
1292 break;
1293 case ICmpInst::ICMP_UGE:
1294 // X >=u 1 -> X
1295 if (match(RHS, m_One()))
1296 return LHS;
1297 break;
1298 case ICmpInst::ICMP_SLT:
1299 // X <s 0 -> X
1300 if (match(RHS, m_Zero()))
1301 return LHS;
1302 break;
1303 case ICmpInst::ICMP_SLE:
1304 // X <=s -1 -> X
1305 if (match(RHS, m_One()))
1306 return LHS;
1307 break;
1308 }
1309 }
1310
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001311 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1312 // different addresses, and what's more the address of a stack variable is
1313 // never null or equal to the address of a global. Note that generalizing
1314 // to the case where LHS is a global variable address or null is pointless,
1315 // since if both LHS and RHS are constants then we already constant folded
1316 // the compare, and if only one of them is then we moved it to RHS already.
1317 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1318 isa<ConstantPointerNull>(RHS)))
1319 // We already know that LHS != LHS.
1320 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1321
1322 // If we are comparing with zero then try hard since this is a common case.
1323 if (match(RHS, m_Zero())) {
1324 bool LHSKnownNonNegative, LHSKnownNegative;
1325 switch (Pred) {
1326 default:
1327 assert(false && "Unknown ICmp predicate!");
1328 case ICmpInst::ICMP_ULT:
1329 return ConstantInt::getFalse(LHS->getContext());
1330 case ICmpInst::ICMP_UGE:
1331 return ConstantInt::getTrue(LHS->getContext());
1332 case ICmpInst::ICMP_EQ:
1333 case ICmpInst::ICMP_ULE:
1334 if (isKnownNonZero(LHS, TD))
1335 return ConstantInt::getFalse(LHS->getContext());
1336 break;
1337 case ICmpInst::ICMP_NE:
1338 case ICmpInst::ICMP_UGT:
1339 if (isKnownNonZero(LHS, TD))
1340 return ConstantInt::getTrue(LHS->getContext());
1341 break;
1342 case ICmpInst::ICMP_SLT:
1343 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1344 if (LHSKnownNegative)
1345 return ConstantInt::getTrue(LHS->getContext());
1346 if (LHSKnownNonNegative)
1347 return ConstantInt::getFalse(LHS->getContext());
1348 break;
1349 case ICmpInst::ICMP_SLE:
1350 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1351 if (LHSKnownNegative)
1352 return ConstantInt::getTrue(LHS->getContext());
1353 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1354 return ConstantInt::getFalse(LHS->getContext());
1355 break;
1356 case ICmpInst::ICMP_SGE:
1357 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1358 if (LHSKnownNegative)
1359 return ConstantInt::getFalse(LHS->getContext());
1360 if (LHSKnownNonNegative)
1361 return ConstantInt::getTrue(LHS->getContext());
1362 break;
1363 case ICmpInst::ICMP_SGT:
1364 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1365 if (LHSKnownNegative)
1366 return ConstantInt::getFalse(LHS->getContext());
1367 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1368 return ConstantInt::getTrue(LHS->getContext());
1369 break;
1370 }
1371 }
1372
1373 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001374 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1375 switch (Pred) {
1376 default: break;
1377 case ICmpInst::ICMP_UGT:
1378 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
1379 return ConstantInt::getFalse(CI->getContext());
1380 break;
1381 case ICmpInst::ICMP_UGE:
1382 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
1383 return ConstantInt::getTrue(CI->getContext());
1384 break;
1385 case ICmpInst::ICMP_ULT:
1386 if (CI->isMinValue(false)) // A <u MIN -> FALSE
1387 return ConstantInt::getFalse(CI->getContext());
1388 break;
1389 case ICmpInst::ICMP_ULE:
1390 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
1391 return ConstantInt::getTrue(CI->getContext());
1392 break;
1393 case ICmpInst::ICMP_SGT:
1394 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
1395 return ConstantInt::getFalse(CI->getContext());
1396 break;
1397 case ICmpInst::ICMP_SGE:
1398 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
1399 return ConstantInt::getTrue(CI->getContext());
1400 break;
1401 case ICmpInst::ICMP_SLT:
1402 if (CI->isMinValue(true)) // A <s MIN -> FALSE
1403 return ConstantInt::getFalse(CI->getContext());
1404 break;
1405 case ICmpInst::ICMP_SLE:
1406 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
1407 return ConstantInt::getTrue(CI->getContext());
1408 break;
1409 }
1410 }
1411
Duncan Sands9d32f602011-01-20 13:21:55 +00001412 // Compare of cast, for example (zext X) != 0 -> X != 0
1413 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1414 Instruction *LI = cast<CastInst>(LHS);
1415 Value *SrcOp = LI->getOperand(0);
1416 const Type *SrcTy = SrcOp->getType();
1417 const Type *DstTy = LI->getType();
1418
1419 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1420 // if the integer type is the same size as the pointer type.
1421 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1422 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1423 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1424 // Transfer the cast to the constant.
1425 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1426 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1427 TD, DT, MaxRecurse-1))
1428 return V;
1429 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1430 if (RI->getOperand(0)->getType() == SrcTy)
1431 // Compare without the cast.
1432 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1433 TD, DT, MaxRecurse-1))
1434 return V;
1435 }
1436 }
1437
1438 if (isa<ZExtInst>(LHS)) {
1439 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1440 // same type.
1441 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1442 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1443 // Compare X and Y. Note that signed predicates become unsigned.
1444 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1445 SrcOp, RI->getOperand(0), TD, DT,
1446 MaxRecurse-1))
1447 return V;
1448 }
1449 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1450 // too. If not, then try to deduce the result of the comparison.
1451 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1452 // Compute the constant that would happen if we truncated to SrcTy then
1453 // reextended to DstTy.
1454 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1455 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1456
1457 // If the re-extended constant didn't change then this is effectively
1458 // also a case of comparing two zero-extended values.
1459 if (RExt == CI && MaxRecurse)
1460 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1461 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1462 return V;
1463
1464 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1465 // there. Use this to work out the result of the comparison.
1466 if (RExt != CI) {
1467 switch (Pred) {
1468 default:
1469 assert(false && "Unknown ICmp predicate!");
1470 // LHS <u RHS.
1471 case ICmpInst::ICMP_EQ:
1472 case ICmpInst::ICMP_UGT:
1473 case ICmpInst::ICMP_UGE:
1474 return ConstantInt::getFalse(CI->getContext());
1475
1476 case ICmpInst::ICMP_NE:
1477 case ICmpInst::ICMP_ULT:
1478 case ICmpInst::ICMP_ULE:
1479 return ConstantInt::getTrue(CI->getContext());
1480
1481 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1482 // is non-negative then LHS <s RHS.
1483 case ICmpInst::ICMP_SGT:
1484 case ICmpInst::ICMP_SGE:
1485 return CI->getValue().isNegative() ?
1486 ConstantInt::getTrue(CI->getContext()) :
1487 ConstantInt::getFalse(CI->getContext());
1488
1489 case ICmpInst::ICMP_SLT:
1490 case ICmpInst::ICMP_SLE:
1491 return CI->getValue().isNegative() ?
1492 ConstantInt::getFalse(CI->getContext()) :
1493 ConstantInt::getTrue(CI->getContext());
1494 }
1495 }
1496 }
1497 }
1498
1499 if (isa<SExtInst>(LHS)) {
1500 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1501 // same type.
1502 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1503 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1504 // Compare X and Y. Note that the predicate does not change.
1505 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1506 TD, DT, MaxRecurse-1))
1507 return V;
1508 }
1509 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1510 // too. If not, then try to deduce the result of the comparison.
1511 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1512 // Compute the constant that would happen if we truncated to SrcTy then
1513 // reextended to DstTy.
1514 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1515 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1516
1517 // If the re-extended constant didn't change then this is effectively
1518 // also a case of comparing two sign-extended values.
1519 if (RExt == CI && MaxRecurse)
1520 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1521 MaxRecurse-1))
1522 return V;
1523
1524 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1525 // bits there. Use this to work out the result of the comparison.
1526 if (RExt != CI) {
1527 switch (Pred) {
1528 default:
1529 assert(false && "Unknown ICmp predicate!");
1530 case ICmpInst::ICMP_EQ:
1531 return ConstantInt::getFalse(CI->getContext());
1532 case ICmpInst::ICMP_NE:
1533 return ConstantInt::getTrue(CI->getContext());
1534
1535 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1536 // LHS >s RHS.
1537 case ICmpInst::ICMP_SGT:
1538 case ICmpInst::ICMP_SGE:
1539 return CI->getValue().isNegative() ?
1540 ConstantInt::getTrue(CI->getContext()) :
1541 ConstantInt::getFalse(CI->getContext());
1542 case ICmpInst::ICMP_SLT:
1543 case ICmpInst::ICMP_SLE:
1544 return CI->getValue().isNegative() ?
1545 ConstantInt::getFalse(CI->getContext()) :
1546 ConstantInt::getTrue(CI->getContext());
1547
1548 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1549 // LHS >u RHS.
1550 case ICmpInst::ICMP_UGT:
1551 case ICmpInst::ICMP_UGE:
1552 // Comparison is true iff the LHS <s 0.
1553 if (MaxRecurse)
1554 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1555 Constant::getNullValue(SrcTy),
1556 TD, DT, MaxRecurse-1))
1557 return V;
1558 break;
1559 case ICmpInst::ICMP_ULT:
1560 case ICmpInst::ICMP_ULE:
1561 // Comparison is true iff the LHS >=s 0.
1562 if (MaxRecurse)
1563 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1564 Constant::getNullValue(SrcTy),
1565 TD, DT, MaxRecurse-1))
1566 return V;
1567 break;
1568 }
1569 }
1570 }
1571 }
1572 }
1573
Duncan Sands1ac7c992010-11-07 16:12:23 +00001574 // If the comparison is with the result of a select instruction, check whether
1575 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001576 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1577 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001578 return V;
1579
1580 // If the comparison is with the result of a phi instruction, check whether
1581 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001582 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1583 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001584 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00001585
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001586 return 0;
1587}
1588
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001589Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001590 const TargetData *TD, const DominatorTree *DT) {
1591 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001592}
1593
Chris Lattner9dbb4292009-11-09 23:28:39 +00001594/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1595/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001596static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001597 const TargetData *TD, const DominatorTree *DT,
1598 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001599 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1600 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1601
Chris Lattnerd06094f2009-11-10 00:55:12 +00001602 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001603 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1604 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00001605
Chris Lattnerd06094f2009-11-10 00:55:12 +00001606 // If we have a constant, make sure it is on the RHS.
1607 std::swap(LHS, RHS);
1608 Pred = CmpInst::getSwappedPredicate(Pred);
1609 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001610
Chris Lattner210c5d42009-11-09 23:55:12 +00001611 // Fold trivial predicates.
1612 if (Pred == FCmpInst::FCMP_FALSE)
1613 return ConstantInt::get(GetCompareTy(LHS), 0);
1614 if (Pred == FCmpInst::FCMP_TRUE)
1615 return ConstantInt::get(GetCompareTy(LHS), 1);
1616
Chris Lattner210c5d42009-11-09 23:55:12 +00001617 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1618 return UndefValue::get(GetCompareTy(LHS));
1619
1620 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00001621 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001622 if (CmpInst::isTrueWhenEqual(Pred))
1623 return ConstantInt::get(GetCompareTy(LHS), 1);
1624 if (CmpInst::isFalseWhenEqual(Pred))
1625 return ConstantInt::get(GetCompareTy(LHS), 0);
1626 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001627
Chris Lattner210c5d42009-11-09 23:55:12 +00001628 // Handle fcmp with constant RHS
1629 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1630 // If the constant is a nan, see if we can fold the comparison based on it.
1631 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1632 if (CFP->getValueAPF().isNaN()) {
1633 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1634 return ConstantInt::getFalse(CFP->getContext());
1635 assert(FCmpInst::isUnordered(Pred) &&
1636 "Comparison must be either ordered or unordered!");
1637 // True if unordered.
1638 return ConstantInt::getTrue(CFP->getContext());
1639 }
Dan Gohman6b617a72010-02-22 04:06:03 +00001640 // Check whether the constant is an infinity.
1641 if (CFP->getValueAPF().isInfinity()) {
1642 if (CFP->getValueAPF().isNegative()) {
1643 switch (Pred) {
1644 case FCmpInst::FCMP_OLT:
1645 // No value is ordered and less than negative infinity.
1646 return ConstantInt::getFalse(CFP->getContext());
1647 case FCmpInst::FCMP_UGE:
1648 // All values are unordered with or at least negative infinity.
1649 return ConstantInt::getTrue(CFP->getContext());
1650 default:
1651 break;
1652 }
1653 } else {
1654 switch (Pred) {
1655 case FCmpInst::FCMP_OGT:
1656 // No value is ordered and greater than infinity.
1657 return ConstantInt::getFalse(CFP->getContext());
1658 case FCmpInst::FCMP_ULE:
1659 // All values are unordered with and at most infinity.
1660 return ConstantInt::getTrue(CFP->getContext());
1661 default:
1662 break;
1663 }
1664 }
1665 }
Chris Lattner210c5d42009-11-09 23:55:12 +00001666 }
1667 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001668
Duncan Sands92826de2010-11-07 16:46:25 +00001669 // If the comparison is with the result of a select instruction, check whether
1670 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001671 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1672 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001673 return V;
1674
1675 // If the comparison is with the result of a phi instruction, check whether
1676 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001677 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1678 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001679 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00001680
Chris Lattner9dbb4292009-11-09 23:28:39 +00001681 return 0;
1682}
1683
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001684Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001685 const TargetData *TD, const DominatorTree *DT) {
1686 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001687}
1688
Chris Lattner04754262010-04-20 05:32:14 +00001689/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1690/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00001691Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1692 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00001693 // select true, X, Y -> X
1694 // select false, X, Y -> Y
1695 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1696 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001697
Chris Lattner04754262010-04-20 05:32:14 +00001698 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00001699 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00001700 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001701
Chris Lattner04754262010-04-20 05:32:14 +00001702 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1703 return FalseVal;
1704 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1705 return TrueVal;
1706 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1707 if (isa<Constant>(TrueVal))
1708 return TrueVal;
1709 return FalseVal;
1710 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001711
Chris Lattner04754262010-04-20 05:32:14 +00001712 return 0;
1713}
1714
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001715/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1716/// fold the result. If not, this returns null.
1717Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00001718 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001719 // The type of the GEP pointer operand.
1720 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1721
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001722 // getelementptr P -> P.
1723 if (NumOps == 1)
1724 return Ops[0];
1725
Duncan Sands85bbff62010-11-22 13:42:49 +00001726 if (isa<UndefValue>(Ops[0])) {
1727 // Compute the (pointer) type returned by the GEP instruction.
1728 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1729 NumOps-1);
1730 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1731 return UndefValue::get(GEPTy);
1732 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001733
Duncan Sandse60d79f2010-11-21 13:53:09 +00001734 if (NumOps == 2) {
1735 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001736 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1737 if (C->isZero())
1738 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00001739 // getelementptr P, N -> P if P points to a type of zero size.
1740 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001741 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00001742 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00001743 return Ops[0];
1744 }
1745 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001746
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001747 // Check to see if this is constant foldable.
1748 for (unsigned i = 0; i != NumOps; ++i)
1749 if (!isa<Constant>(Ops[i]))
1750 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001751
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001752 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1753 (Constant *const*)Ops+1, NumOps-1);
1754}
1755
Duncan Sandsff103412010-11-17 04:30:22 +00001756/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1757static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1758 // If all of the PHI's incoming values are the same then replace the PHI node
1759 // with the common value.
1760 Value *CommonValue = 0;
1761 bool HasUndefInput = false;
1762 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1763 Value *Incoming = PN->getIncomingValue(i);
1764 // If the incoming value is the phi node itself, it can safely be skipped.
1765 if (Incoming == PN) continue;
1766 if (isa<UndefValue>(Incoming)) {
1767 // Remember that we saw an undef value, but otherwise ignore them.
1768 HasUndefInput = true;
1769 continue;
1770 }
1771 if (CommonValue && Incoming != CommonValue)
1772 return 0; // Not the same, bail out.
1773 CommonValue = Incoming;
1774 }
1775
1776 // If CommonValue is null then all of the incoming values were either undef or
1777 // equal to the phi node itself.
1778 if (!CommonValue)
1779 return UndefValue::get(PN->getType());
1780
1781 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1782 // instruction, we cannot return X as the result of the PHI node unless it
1783 // dominates the PHI block.
1784 if (HasUndefInput)
1785 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1786
1787 return CommonValue;
1788}
1789
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001790
Chris Lattnerd06094f2009-11-10 00:55:12 +00001791//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00001792
Chris Lattnerd06094f2009-11-10 00:55:12 +00001793/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1794/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001795static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001796 const TargetData *TD, const DominatorTree *DT,
1797 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001798 switch (Opcode) {
Duncan Sandsee9a2e32010-12-20 14:47:04 +00001799 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1800 /* isNUW */ false, TD, DT,
1801 MaxRecurse);
1802 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1803 /* isNUW */ false, TD, DT,
1804 MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00001805 case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands593faa52011-01-28 16:51:11 +00001806 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
1807 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001808 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001809 case Instruction::Shl: return SimplifyShlInst(LHS, RHS, TD, DT, MaxRecurse);
1810 case Instruction::LShr: return SimplifyLShrInst(LHS, RHS, TD, DT, MaxRecurse);
1811 case Instruction::AShr: return SimplifyAShrInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00001812 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1813 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1814 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001815 default:
1816 if (Constant *CLHS = dyn_cast<Constant>(LHS))
1817 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1818 Constant *COps[] = {CLHS, CRHS};
1819 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1820 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001821
Duncan Sands566edb02010-12-21 08:49:00 +00001822 // If the operation is associative, try some generic simplifications.
1823 if (Instruction::isAssociative(Opcode))
1824 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1825 MaxRecurse))
1826 return V;
1827
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001828 // If the operation is with the result of a select instruction, check whether
1829 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001830 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00001831 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001832 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001833 return V;
1834
1835 // If the operation is with the result of a phi instruction, check whether
1836 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001837 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1838 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001839 return V;
1840
Chris Lattnerd06094f2009-11-10 00:55:12 +00001841 return 0;
1842 }
1843}
Chris Lattner9dbb4292009-11-09 23:28:39 +00001844
Duncan Sands12a86f52010-11-14 11:23:23 +00001845Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001846 const TargetData *TD, const DominatorTree *DT) {
1847 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00001848}
1849
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001850/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1851/// fold the result.
1852static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001853 const TargetData *TD, const DominatorTree *DT,
1854 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001855 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00001856 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1857 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001858}
1859
1860Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001861 const TargetData *TD, const DominatorTree *DT) {
1862 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001863}
Chris Lattnere3453782009-11-10 01:08:51 +00001864
1865/// SimplifyInstruction - See if we can compute a simplified version of this
1866/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00001867Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1868 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00001869 Value *Result;
1870
Chris Lattnere3453782009-11-10 01:08:51 +00001871 switch (I->getOpcode()) {
1872 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001873 Result = ConstantFoldInstruction(I, TD);
1874 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001875 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001876 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1877 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1878 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1879 TD, DT);
1880 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001881 case Instruction::Sub:
1882 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1883 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1884 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1885 TD, DT);
1886 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00001887 case Instruction::Mul:
1888 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1889 break;
Duncan Sands593faa52011-01-28 16:51:11 +00001890 case Instruction::SDiv:
1891 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
1892 break;
1893 case Instruction::UDiv:
1894 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
1895 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001896 case Instruction::FDiv:
1897 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
1898 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001899 case Instruction::Shl:
1900 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1), TD, DT);
1901 break;
1902 case Instruction::LShr:
1903 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1904 break;
1905 case Instruction::AShr:
1906 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1907 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001908 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001909 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1910 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001911 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001912 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1913 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001914 case Instruction::Xor:
1915 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1916 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001917 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001918 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1919 I->getOperand(0), I->getOperand(1), TD, DT);
1920 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001921 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001922 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1923 I->getOperand(0), I->getOperand(1), TD, DT);
1924 break;
Chris Lattner04754262010-04-20 05:32:14 +00001925 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001926 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1927 I->getOperand(2), TD, DT);
1928 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001929 case Instruction::GetElementPtr: {
1930 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001931 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1932 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001933 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001934 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001935 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1936 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001937 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001938
1939 /// If called on unreachable code, the above logic may report that the
1940 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001941 /// detecting that case here, returning a safe value instead.
1942 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001943}
1944
Chris Lattner40d8c282009-11-10 22:26:15 +00001945/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1946/// delete the From instruction. In addition to a basic RAUW, this does a
1947/// recursive simplification of the newly formed instructions. This catches
1948/// things where one simplification exposes other opportunities. This only
1949/// simplifies and deletes scalar operations, it does not change the CFG.
1950///
1951void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001952 const TargetData *TD,
1953 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001954 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001955
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001956 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1957 // we can know if it gets deleted out from under us or replaced in a
1958 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001959 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001960 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001961
Chris Lattner40d8c282009-11-10 22:26:15 +00001962 while (!From->use_empty()) {
1963 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001964 Use &TheUse = From->use_begin().getUse();
1965 Instruction *User = cast<Instruction>(TheUse.getUser());
1966 TheUse = To;
1967
1968 // Check to see if the instruction can be folded due to the operand
1969 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1970 // the 'or' with -1.
1971 Value *SimplifiedVal;
1972 {
1973 // Sanity check to make sure 'User' doesn't dangle across
1974 // SimplifyInstruction.
1975 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001976
Duncan Sandseff05812010-11-14 18:36:10 +00001977 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001978 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001979 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001980
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001981 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001982 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001983 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1984 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001985
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001986 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001987
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001988 // If the recursive simplification ended up revisiting and deleting
1989 // 'From' then we're done.
1990 if (From == 0)
1991 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001992 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001993
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001994 // If 'From' has value handles referring to it, do a real RAUW to update them.
1995 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001996
Chris Lattner40d8c282009-11-10 22:26:15 +00001997 From->eraseFromParent();
1998}