blob: 7656220ba1fb32748e082d4e267585672648d71e [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sands4cd2ad12010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsee9a2e32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
Jay Foad562b84b2011-04-11 09:35:34 +000021#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000022#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000023#include "llvm/Analysis/InstructionSimplify.h"
24#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000025#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000026#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000027#include "llvm/Support/ConstantRange.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000028#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000029#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000030#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000031using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000032using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000033
Chris Lattner81a0dc92011-02-09 17:15:04 +000034enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000035
Duncan Sandsa3c44a52010-12-22 09:40:51 +000036STATISTIC(NumExpand, "Number of expansions");
37STATISTIC(NumFactor , "Number of factorizations");
38STATISTIC(NumReassoc, "Number of reassociations");
39
Duncan Sands82fdab32010-12-21 14:00:22 +000040static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000041 const TargetLibraryInfo *, const DominatorTree *,
42 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000043static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000044 const TargetLibraryInfo *, const DominatorTree *,
45 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000046static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000047 const TargetLibraryInfo *, const DominatorTree *,
48 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000049static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000050 const TargetLibraryInfo *, const DominatorTree *,
51 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000052static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000053 const TargetLibraryInfo *, const DominatorTree *,
54 unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000055
Duncan Sandsf56138d2011-07-26 15:03:53 +000056/// getFalse - For a boolean type, or a vector of boolean type, return false, or
57/// a vector with every element false, as appropriate for the type.
58static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000059 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000060 "Expected i1 type or a vector of i1!");
61 return Constant::getNullValue(Ty);
62}
63
64/// getTrue - For a boolean type, or a vector of boolean type, return true, or
65/// a vector with every element true, as appropriate for the type.
66static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000067 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000068 "Expected i1 type or a vector of i1!");
69 return Constant::getAllOnesValue(Ty);
70}
71
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000072/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
73static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
74 Value *RHS) {
75 CmpInst *Cmp = dyn_cast<CmpInst>(V);
76 if (!Cmp)
77 return false;
78 CmpInst::Predicate CPred = Cmp->getPredicate();
79 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
80 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
81 return true;
82 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
83 CRHS == LHS;
84}
85
Duncan Sands18450092010-11-16 12:16:38 +000086/// ValueDominatesPHI - Does the given value dominate the specified phi node?
87static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
88 Instruction *I = dyn_cast<Instruction>(V);
89 if (!I)
90 // Arguments and constants dominate all instructions.
91 return true;
92
93 // If we have a DominatorTree then do a precise test.
94 if (DT)
95 return DT->dominates(I, P);
96
97 // Otherwise, if the instruction is in the entry block, and is not an invoke,
98 // then it obviously dominates all phi nodes.
99 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
100 !isa<InvokeInst>(I))
101 return true;
102
103 return false;
104}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000105
Duncan Sands3421d902010-12-21 13:32:22 +0000106/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
107/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
108/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
109/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
110/// Returns the simplified value, or null if no simplification was performed.
111static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000112 unsigned OpcToExpand, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000113 const TargetLibraryInfo *TLI, const DominatorTree *DT,
114 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000115 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000116 // Recursion is always used, so bail out at once if we already hit the limit.
117 if (!MaxRecurse--)
118 return 0;
119
120 // Check whether the expression has the form "(A op' B) op C".
121 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
122 if (Op0->getOpcode() == OpcodeToExpand) {
123 // It does! Try turning it into "(A op C) op' (B op C)".
124 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
125 // Do "A op C" and "B op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000126 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
127 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000128 // They do! Return "L op' R" if it simplifies or is already available.
129 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000130 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
131 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000132 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000133 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000134 }
Duncan Sands3421d902010-12-21 13:32:22 +0000135 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000136 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000137 MaxRecurse)) {
138 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000139 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000140 }
Duncan Sands3421d902010-12-21 13:32:22 +0000141 }
142 }
143
144 // Check whether the expression has the form "A op (B op' C)".
145 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
146 if (Op1->getOpcode() == OpcodeToExpand) {
147 // It does! Try turning it into "(A op B) op' (A op C)".
148 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
149 // Do "A op B" and "A op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000150 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
151 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000152 // They do! Return "L op' R" if it simplifies or is already available.
153 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000154 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
155 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000156 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000157 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000158 }
Duncan Sands3421d902010-12-21 13:32:22 +0000159 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000160 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000161 MaxRecurse)) {
162 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000163 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000164 }
Duncan Sands3421d902010-12-21 13:32:22 +0000165 }
166 }
167
168 return 0;
169}
170
171/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
172/// using the operation OpCodeToExtract. For example, when Opcode is Add and
173/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
174/// Returns the simplified value, or null if no simplification was performed.
175static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000176 unsigned OpcToExtract, const TargetData *TD,
177 const TargetLibraryInfo *TLI,
178 const DominatorTree *DT,
179 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000180 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000181 // Recursion is always used, so bail out at once if we already hit the limit.
182 if (!MaxRecurse--)
183 return 0;
184
185 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
186 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
187
188 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
189 !Op1 || Op1->getOpcode() != OpcodeToExtract)
190 return 0;
191
192 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000193 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
194 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000195
196 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
197 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
198 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000199 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
200 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000201 // Form "A op' (B op DD)" if it simplifies completely.
202 // Does "B op DD" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000203 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000204 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000205 // If V equals B then "A op' V" is just the LHS. If V equals DD then
206 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000207 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000208 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000209 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000210 }
Duncan Sands3421d902010-12-21 13:32:22 +0000211 // Otherwise return "A op' V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000212 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
213 MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000214 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000215 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000216 }
Duncan Sands3421d902010-12-21 13:32:22 +0000217 }
218 }
219
220 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
221 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
222 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000223 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
224 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000225 // Form "(A op CC) op' B" if it simplifies completely..
226 // Does "A op CC" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000227 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000228 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000229 // If V equals A then "V op' B" is just the LHS. If V equals CC then
230 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000231 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000232 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000233 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000234 }
Duncan Sands3421d902010-12-21 13:32:22 +0000235 // Otherwise return "V op' B" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000236 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
237 MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000238 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000239 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000240 }
Duncan Sands3421d902010-12-21 13:32:22 +0000241 }
242 }
243
244 return 0;
245}
246
247/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
248/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000249static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000250 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000251 const TargetLibraryInfo *TLI,
Duncan Sands566edb02010-12-21 08:49:00 +0000252 const DominatorTree *DT,
253 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000254 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000255 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
256
257 // Recursion is always used, so bail out at once if we already hit the limit.
258 if (!MaxRecurse--)
259 return 0;
260
261 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
262 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
263
264 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
265 if (Op0 && Op0->getOpcode() == Opcode) {
266 Value *A = Op0->getOperand(0);
267 Value *B = Op0->getOperand(1);
268 Value *C = RHS;
269
270 // Does "B op C" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000271 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000272 // It does! Return "A op V" if it simplifies or is already available.
273 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000274 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000275 // Otherwise return "A op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000276 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000277 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000278 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000279 }
Duncan Sands566edb02010-12-21 08:49:00 +0000280 }
281 }
282
283 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
284 if (Op1 && Op1->getOpcode() == Opcode) {
285 Value *A = LHS;
286 Value *B = Op1->getOperand(0);
287 Value *C = Op1->getOperand(1);
288
289 // Does "A op B" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000290 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000291 // It does! Return "V op C" if it simplifies or is already available.
292 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000293 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000294 // Otherwise return "V op C" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000295 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000296 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000297 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000298 }
Duncan Sands566edb02010-12-21 08:49:00 +0000299 }
300 }
301
302 // The remaining transforms require commutativity as well as associativity.
303 if (!Instruction::isCommutative(Opcode))
304 return 0;
305
306 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
307 if (Op0 && Op0->getOpcode() == Opcode) {
308 Value *A = Op0->getOperand(0);
309 Value *B = Op0->getOperand(1);
310 Value *C = RHS;
311
312 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000313 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000314 // It does! Return "V op B" if it simplifies or is already available.
315 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000316 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000317 // Otherwise return "V op B" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000318 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000319 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000320 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000321 }
Duncan Sands566edb02010-12-21 08:49:00 +0000322 }
323 }
324
325 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
326 if (Op1 && Op1->getOpcode() == Opcode) {
327 Value *A = LHS;
328 Value *B = Op1->getOperand(0);
329 Value *C = Op1->getOperand(1);
330
331 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000332 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000333 // It does! Return "B op V" if it simplifies or is already available.
334 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000335 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000336 // Otherwise return "B op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000337 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000338 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000339 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000340 }
Duncan Sands566edb02010-12-21 08:49:00 +0000341 }
342 }
343
344 return 0;
345}
346
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000347/// ThreadBinOpOverSelect - In the case of a binary operation with a select
348/// instruction as an operand, try to simplify the binop by seeing whether
349/// evaluating it on both branches of the select results in the same value.
350/// Returns the common value if so, otherwise returns null.
351static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000352 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000353 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000354 const DominatorTree *DT,
355 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000356 // Recursion is always used, so bail out at once if we already hit the limit.
357 if (!MaxRecurse--)
358 return 0;
359
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000360 SelectInst *SI;
361 if (isa<SelectInst>(LHS)) {
362 SI = cast<SelectInst>(LHS);
363 } else {
364 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
365 SI = cast<SelectInst>(RHS);
366 }
367
368 // Evaluate the BinOp on the true and false branches of the select.
369 Value *TV;
370 Value *FV;
371 if (SI == LHS) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000372 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
373 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000374 } else {
Chad Rosier618c1db2011-12-01 03:08:23 +0000375 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
376 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000377 }
378
Duncan Sands7cf85e72011-01-01 16:12:09 +0000379 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000380 // If they both failed to simplify then return null.
381 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000382 return TV;
383
384 // If one branch simplified to undef, return the other one.
385 if (TV && isa<UndefValue>(TV))
386 return FV;
387 if (FV && isa<UndefValue>(FV))
388 return TV;
389
390 // If applying the operation did not change the true and false select values,
391 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000392 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000393 return SI;
394
395 // If one branch simplified and the other did not, and the simplified
396 // value is equal to the unsimplified one, return the simplified value.
397 // For example, select (cond, X, X & Z) & Z -> X & Z.
398 if ((FV && !TV) || (TV && !FV)) {
399 // Check that the simplified value has the form "X op Y" where "op" is the
400 // same as the original operation.
401 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
402 if (Simplified && Simplified->getOpcode() == Opcode) {
403 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
404 // We already know that "op" is the same as for the simplified value. See
405 // if the operands match too. If so, return the simplified value.
406 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
407 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
408 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000409 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
410 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000411 return Simplified;
412 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000413 Simplified->getOperand(1) == UnsimplifiedLHS &&
414 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000415 return Simplified;
416 }
417 }
418
419 return 0;
420}
421
422/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
423/// try to simplify the comparison by seeing whether both branches of the select
424/// result in the same value. Returns the common value if so, otherwise returns
425/// null.
426static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000427 Value *RHS, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000428 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000429 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000430 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000431 // Recursion is always used, so bail out at once if we already hit the limit.
432 if (!MaxRecurse--)
433 return 0;
434
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000435 // Make sure the select is on the LHS.
436 if (!isa<SelectInst>(LHS)) {
437 std::swap(LHS, RHS);
438 Pred = CmpInst::getSwappedPredicate(Pred);
439 }
440 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
441 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000442 Value *Cond = SI->getCondition();
443 Value *TV = SI->getTrueValue();
444 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000445
Duncan Sands50ca4d32011-02-03 09:37:39 +0000446 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000447 // Does "cmp TV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000448 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000449 if (TCmp == Cond) {
450 // It not only simplified, it simplified to the select condition. Replace
451 // it with 'true'.
452 TCmp = getTrue(Cond->getType());
453 } else if (!TCmp) {
454 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
455 // condition then we can replace it with 'true'. Otherwise give up.
456 if (!isSameCompare(Cond, Pred, TV, RHS))
457 return 0;
458 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000459 }
460
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000461 // Does "cmp FV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000462 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000463 if (FCmp == Cond) {
464 // It not only simplified, it simplified to the select condition. Replace
465 // it with 'false'.
466 FCmp = getFalse(Cond->getType());
467 } else if (!FCmp) {
468 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
469 // condition then we can replace it with 'false'. Otherwise give up.
470 if (!isSameCompare(Cond, Pred, FV, RHS))
471 return 0;
472 FCmp = getFalse(Cond->getType());
473 }
474
475 // If both sides simplified to the same value, then use it as the result of
476 // the original comparison.
477 if (TCmp == FCmp)
478 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000479
480 // The remaining cases only make sense if the select condition has the same
481 // type as the result of the comparison, so bail out if this is not so.
482 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
483 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000484 // If the false value simplified to false, then the result of the compare
485 // is equal to "Cond && TCmp". This also catches the case when the false
486 // value simplified to false and the true value to true, returning "Cond".
487 if (match(FCmp, m_Zero()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000488 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000489 return V;
490 // If the true value simplified to true, then the result of the compare
491 // is equal to "Cond || FCmp".
492 if (match(TCmp, m_One()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000493 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000494 return V;
495 // Finally, if the false value simplified to true and the true value to
496 // false, then the result of the compare is equal to "!Cond".
497 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
498 if (Value *V =
499 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +0000500 TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000501 return V;
502
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000503 return 0;
504}
505
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000506/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
507/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
508/// it on the incoming phi values yields the same result for every value. If so
509/// returns the common value, otherwise returns null.
510static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000511 const TargetData *TD,
512 const TargetLibraryInfo *TLI,
513 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000514 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000515 // Recursion is always used, so bail out at once if we already hit the limit.
516 if (!MaxRecurse--)
517 return 0;
518
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000519 PHINode *PI;
520 if (isa<PHINode>(LHS)) {
521 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000522 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
523 if (!ValueDominatesPHI(RHS, PI, DT))
524 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000525 } else {
526 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
527 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000528 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
529 if (!ValueDominatesPHI(LHS, PI, DT))
530 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000531 }
532
533 // Evaluate the BinOp on the incoming phi values.
534 Value *CommonValue = 0;
535 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000536 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000537 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000538 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000539 Value *V = PI == LHS ?
Chad Rosier618c1db2011-12-01 03:08:23 +0000540 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
541 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000542 // If the operation failed to simplify, or simplified to a different value
543 // to previously, then give up.
544 if (!V || (CommonValue && V != CommonValue))
545 return 0;
546 CommonValue = V;
547 }
548
549 return CommonValue;
550}
551
552/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
553/// try to simplify the comparison by seeing whether comparing with all of the
554/// incoming phi values yields the same result every time. If so returns the
555/// common result, otherwise returns null.
556static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000557 const TargetData *TD,
558 const TargetLibraryInfo *TLI,
559 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000560 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000561 // Recursion is always used, so bail out at once if we already hit the limit.
562 if (!MaxRecurse--)
563 return 0;
564
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000565 // Make sure the phi is on the LHS.
566 if (!isa<PHINode>(LHS)) {
567 std::swap(LHS, RHS);
568 Pred = CmpInst::getSwappedPredicate(Pred);
569 }
570 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
571 PHINode *PI = cast<PHINode>(LHS);
572
Duncan Sands18450092010-11-16 12:16:38 +0000573 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
574 if (!ValueDominatesPHI(RHS, PI, DT))
575 return 0;
576
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000577 // Evaluate the BinOp on the incoming phi values.
578 Value *CommonValue = 0;
579 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000580 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000581 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000582 if (Incoming == PI) continue;
Chad Rosier618c1db2011-12-01 03:08:23 +0000583 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000584 // If the operation failed to simplify, or simplified to a different value
585 // to previously, then give up.
586 if (!V || (CommonValue && V != CommonValue))
587 return 0;
588 CommonValue = V;
589 }
590
591 return CommonValue;
592}
593
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000594/// SimplifyAddInst - Given operands for an Add, see if we can
595/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000596static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000597 const TargetData *TD,
598 const TargetLibraryInfo *TLI,
599 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000600 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000601 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
602 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
603 Constant *Ops[] = { CLHS, CRHS };
604 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000605 Ops, TD, TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000606 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000607
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000608 // Canonicalize the constant to the RHS.
609 std::swap(Op0, Op1);
610 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000611
Duncan Sandsfea3b212010-12-15 14:07:39 +0000612 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000613 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000614 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000615
Duncan Sandsfea3b212010-12-15 14:07:39 +0000616 // X + 0 -> X
617 if (match(Op1, m_Zero()))
618 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000619
Duncan Sandsfea3b212010-12-15 14:07:39 +0000620 // X + (Y - X) -> Y
621 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000622 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000623 Value *Y = 0;
624 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
625 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000626 return Y;
627
628 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000629 if (match(Op0, m_Not(m_Specific(Op1))) ||
630 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000631 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000632
Duncan Sands82fdab32010-12-21 14:00:22 +0000633 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000634 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000635 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000636 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000637
Duncan Sands566edb02010-12-21 08:49:00 +0000638 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000639 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +0000640 MaxRecurse))
641 return V;
642
Duncan Sands3421d902010-12-21 13:32:22 +0000643 // Mul distributes over Add. Try some generic simplifications based on this.
644 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000645 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000646 return V;
647
Duncan Sands87689cf2010-11-19 09:20:39 +0000648 // Threading Add over selects and phi nodes is pointless, so don't bother.
649 // Threading over the select in "A + select(cond, B, C)" means evaluating
650 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
651 // only if B and C are equal. If B and C are equal then (since we assume
652 // that operands have already been simplified) "select(cond, B, C)" should
653 // have been simplified to the common value of B and C already. Analysing
654 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
655 // for threading over phi nodes.
656
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000657 return 0;
658}
659
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000660Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000661 const TargetData *TD, const TargetLibraryInfo *TLI,
662 const DominatorTree *DT) {
663 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000664}
665
Duncan Sandsfea3b212010-12-15 14:07:39 +0000666/// SimplifySubInst - Given operands for a Sub, see if we can
667/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000668static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000669 const TargetData *TD,
670 const TargetLibraryInfo *TLI,
671 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000672 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000673 if (Constant *CLHS = dyn_cast<Constant>(Op0))
674 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
675 Constant *Ops[] = { CLHS, CRHS };
676 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000677 Ops, TD, TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000678 }
679
680 // X - undef -> undef
681 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000682 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000683 return UndefValue::get(Op0->getType());
684
685 // X - 0 -> X
686 if (match(Op1, m_Zero()))
687 return Op0;
688
689 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000690 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000691 return Constant::getNullValue(Op0->getType());
692
Duncan Sandsfe02c692011-01-18 09:24:58 +0000693 // (X*2) - X -> X
694 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000695 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000696 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
697 match(Op0, m_Shl(m_Specific(Op1), m_One())))
698 return Op1;
699
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000700 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
701 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
702 Value *Y = 0, *Z = Op1;
703 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
704 // See if "V === Y - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000705 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000706 // It does! Now see if "X + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000707 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000708 MaxRecurse-1)) {
709 // It does, we successfully reassociated!
710 ++NumReassoc;
711 return W;
712 }
713 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000714 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000715 // It does! Now see if "Y + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000716 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000717 MaxRecurse-1)) {
718 // It does, we successfully reassociated!
719 ++NumReassoc;
720 return W;
721 }
722 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000723
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000724 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
725 // For example, X - (X + 1) -> -1
726 X = Op0;
727 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
728 // See if "V === X - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000729 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000730 // It does! Now see if "V - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000731 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000732 MaxRecurse-1)) {
733 // It does, we successfully reassociated!
734 ++NumReassoc;
735 return W;
736 }
737 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000738 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000739 // It does! Now see if "V - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000740 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000741 MaxRecurse-1)) {
742 // It does, we successfully reassociated!
743 ++NumReassoc;
744 return W;
745 }
746 }
747
748 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
749 // For example, X - (X - Y) -> Y.
750 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000751 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
752 // See if "V === Z - X" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000753 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000754 // It does! Now see if "V + Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000755 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
Duncan Sandsc087e202011-01-14 15:26:10 +0000756 MaxRecurse-1)) {
757 // It does, we successfully reassociated!
758 ++NumReassoc;
759 return W;
760 }
761
Duncan Sands3421d902010-12-21 13:32:22 +0000762 // Mul distributes over Sub. Try some generic simplifications based on this.
763 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000764 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000765 return V;
766
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000767 // i1 sub -> xor.
768 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000769 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000770 return V;
771
Duncan Sandsfea3b212010-12-15 14:07:39 +0000772 // Threading Sub over selects and phi nodes is pointless, so don't bother.
773 // Threading over the select in "A - select(cond, B, C)" means evaluating
774 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
775 // only if B and C are equal. If B and C are equal then (since we assume
776 // that operands have already been simplified) "select(cond, B, C)" should
777 // have been simplified to the common value of B and C already. Analysing
778 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
779 // for threading over phi nodes.
780
781 return 0;
782}
783
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000784Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000785 const TargetData *TD,
786 const TargetLibraryInfo *TLI,
787 const DominatorTree *DT) {
788 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000789}
790
Duncan Sands82fdab32010-12-21 14:00:22 +0000791/// SimplifyMulInst - Given operands for a Mul, see if we can
792/// fold the result. If not, this returns null.
793static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000794 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000795 const DominatorTree *DT, unsigned MaxRecurse) {
796 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
797 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
798 Constant *Ops[] = { CLHS, CRHS };
799 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000800 Ops, TD, TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000801 }
802
803 // Canonicalize the constant to the RHS.
804 std::swap(Op0, Op1);
805 }
806
807 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000808 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000809 return Constant::getNullValue(Op0->getType());
810
811 // X * 0 -> 0
812 if (match(Op1, m_Zero()))
813 return Op1;
814
815 // X * 1 -> X
816 if (match(Op1, m_One()))
817 return Op0;
818
Duncan Sands1895e982011-01-30 18:03:50 +0000819 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000820 Value *X = 0;
821 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
822 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
823 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000824
Nick Lewycky54138802011-01-29 19:55:23 +0000825 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000826 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000827 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000828 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000829
830 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000831 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000832 MaxRecurse))
833 return V;
834
835 // Mul distributes over Add. Try some generic simplifications based on this.
836 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Chad Rosier618c1db2011-12-01 03:08:23 +0000837 TD, TLI, DT, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +0000838 return V;
839
840 // If the operation is with the result of a select instruction, check whether
841 // operating on either branch of the select always yields the same value.
842 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000843 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000844 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))
Chad Rosier618c1db2011-12-01 03:08:23 +0000850 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000851 MaxRecurse))
852 return V;
853
854 return 0;
855}
856
857Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000858 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000859 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000860 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +0000861}
862
Duncan Sands593faa52011-01-28 16:51:11 +0000863/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
864/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000865static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +0000866 const TargetData *TD, const TargetLibraryInfo *TLI,
867 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +0000868 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
869 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
870 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +0000871 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sands593faa52011-01-28 16:51:11 +0000872 }
873 }
874
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000875 bool isSigned = Opcode == Instruction::SDiv;
876
Duncan Sands593faa52011-01-28 16:51:11 +0000877 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000878 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000879 return Op1;
880
881 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000882 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000883 return Constant::getNullValue(Op0->getType());
884
885 // 0 / X -> 0, we don't need to preserve faults!
886 if (match(Op0, m_Zero()))
887 return Op0;
888
889 // X / 1 -> X
890 if (match(Op1, m_One()))
891 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000892
893 if (Op0->getType()->isIntegerTy(1))
894 // It can't be division by zero, hence it must be division by one.
895 return Op0;
896
897 // X / X -> 1
898 if (Op0 == Op1)
899 return ConstantInt::get(Op0->getType(), 1);
900
901 // (X * Y) / Y -> X if the multiplication does not overflow.
902 Value *X = 0, *Y = 0;
903 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
904 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +0000905 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +0000906 // If the Mul knows it does not overflow, then we are good to go.
907 if ((isSigned && Mul->hasNoSignedWrap()) ||
908 (!isSigned && Mul->hasNoUnsignedWrap()))
909 return X;
Duncan Sands593faa52011-01-28 16:51:11 +0000910 // If X has the form X = A / Y then X * Y cannot overflow.
911 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
912 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
913 return X;
914 }
915
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000916 // (X rem Y) / Y -> 0
917 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
918 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
919 return Constant::getNullValue(Op0->getType());
920
921 // If the operation is with the result of a select instruction, check whether
922 // operating on either branch of the select always yields the same value.
923 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000924 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
925 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000926 return V;
927
928 // If the operation is with the result of a phi instruction, check whether
929 // operating on all incoming values of the phi always yields the same value.
930 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000931 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
932 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000933 return V;
934
Duncan Sands593faa52011-01-28 16:51:11 +0000935 return 0;
936}
937
938/// SimplifySDivInst - Given operands for an SDiv, see if we can
939/// fold the result. If not, this returns null.
940static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000941 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +0000942 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000943 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
944 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +0000945 return V;
946
Duncan Sands593faa52011-01-28 16:51:11 +0000947 return 0;
948}
949
950Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000951 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000952 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000953 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +0000954}
955
956/// SimplifyUDivInst - Given operands for a UDiv, see if we can
957/// fold the result. If not, this returns null.
958static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000959 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +0000960 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000961 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
962 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +0000963 return V;
964
Duncan Sands593faa52011-01-28 16:51:11 +0000965 return 0;
966}
967
968Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000969 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000970 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000971 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +0000972}
973
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000974static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +0000975 const TargetLibraryInfo *,
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000976 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000977 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000978 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000979 return Op0;
980
981 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000982 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000983 return Op1;
984
985 return 0;
986}
987
988Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000989 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000990 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000991 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000992}
993
Duncan Sandsf24ed772011-05-02 16:27:02 +0000994/// SimplifyRem - Given operands for an SRem or URem, see if we can
995/// fold the result. If not, this returns null.
996static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +0000997 const TargetData *TD, const TargetLibraryInfo *TLI,
998 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +0000999 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1000 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1001 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001002 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001003 }
1004 }
1005
Duncan Sandsf24ed772011-05-02 16:27:02 +00001006 // X % undef -> undef
1007 if (match(Op1, m_Undef()))
1008 return Op1;
1009
1010 // undef % X -> 0
1011 if (match(Op0, m_Undef()))
1012 return Constant::getNullValue(Op0->getType());
1013
1014 // 0 % X -> 0, we don't need to preserve faults!
1015 if (match(Op0, m_Zero()))
1016 return Op0;
1017
1018 // X % 0 -> undef, we don't need to preserve faults!
1019 if (match(Op1, m_Zero()))
1020 return UndefValue::get(Op0->getType());
1021
1022 // X % 1 -> 0
1023 if (match(Op1, m_One()))
1024 return Constant::getNullValue(Op0->getType());
1025
1026 if (Op0->getType()->isIntegerTy(1))
1027 // It can't be remainder by zero, hence it must be remainder by one.
1028 return Constant::getNullValue(Op0->getType());
1029
1030 // X % X -> 0
1031 if (Op0 == Op1)
1032 return Constant::getNullValue(Op0->getType());
1033
1034 // If the operation is with the result of a select instruction, check whether
1035 // operating on either branch of the select always yields the same value.
1036 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001037 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001038 return V;
1039
1040 // If the operation is with the result of a phi instruction, check whether
1041 // operating on all incoming values of the phi always yields the same value.
1042 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001043 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001044 return V;
1045
1046 return 0;
1047}
1048
1049/// SimplifySRemInst - Given operands for an SRem, see if we can
1050/// fold the result. If not, this returns null.
1051static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001052 const TargetLibraryInfo *TLI,
1053 const DominatorTree *DT,
1054 unsigned MaxRecurse) {
1055 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001056 return V;
1057
1058 return 0;
1059}
1060
1061Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001062 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001063 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001064 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001065}
1066
1067/// SimplifyURemInst - Given operands for a URem, see if we can
1068/// fold the result. If not, this returns null.
1069static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001070 const TargetLibraryInfo *TLI,
1071 const DominatorTree *DT,
1072 unsigned MaxRecurse) {
1073 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001074 return V;
1075
1076 return 0;
1077}
1078
1079Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001080 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001081 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001082 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001083}
1084
1085static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +00001086 const TargetLibraryInfo *,
1087 const DominatorTree *,
1088 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001089 // undef % X -> undef (the undef could be a snan).
1090 if (match(Op0, m_Undef()))
1091 return Op0;
1092
1093 // X % undef -> undef
1094 if (match(Op1, m_Undef()))
1095 return Op1;
1096
1097 return 0;
1098}
1099
1100Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001101 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001102 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001103 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001104}
1105
Duncan Sandscf80bc12011-01-14 14:44:12 +00001106/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001107/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001108static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +00001109 const TargetData *TD, const TargetLibraryInfo *TLI,
1110 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001111 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1112 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1113 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001114 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001115 }
1116 }
1117
Duncan Sandscf80bc12011-01-14 14:44:12 +00001118 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001119 if (match(Op0, m_Zero()))
1120 return Op0;
1121
Duncan Sandscf80bc12011-01-14 14:44:12 +00001122 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001123 if (match(Op1, m_Zero()))
1124 return Op0;
1125
Duncan Sandscf80bc12011-01-14 14:44:12 +00001126 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001127 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001128 return Op1;
1129
1130 // Shifting by the bitwidth or more is undefined.
1131 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1132 if (CI->getValue().getLimitedValue() >=
1133 Op0->getType()->getScalarSizeInBits())
1134 return UndefValue::get(Op0->getType());
1135
Duncan Sandscf80bc12011-01-14 14:44:12 +00001136 // If the operation is with the result of a select instruction, check whether
1137 // operating on either branch of the select always yields the same value.
1138 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001139 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001140 return V;
1141
1142 // If the operation is with the result of a phi instruction, check whether
1143 // operating on all incoming values of the phi always yields the same value.
1144 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001145 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001146 return V;
1147
1148 return 0;
1149}
1150
1151/// SimplifyShlInst - Given operands for an Shl, see if we can
1152/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001153static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001154 const TargetData *TD,
1155 const TargetLibraryInfo *TLI,
1156 const DominatorTree *DT, unsigned MaxRecurse) {
1157 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001158 return V;
1159
1160 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001161 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001162 return Constant::getNullValue(Op0->getType());
1163
Chris Lattner81a0dc92011-02-09 17:15:04 +00001164 // (X >> A) << A -> X
1165 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001166 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001167 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001168 return 0;
1169}
1170
Chris Lattner81a0dc92011-02-09 17:15:04 +00001171Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001172 const TargetData *TD, const TargetLibraryInfo *TLI,
1173 const DominatorTree *DT) {
1174 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001175}
1176
1177/// SimplifyLShrInst - Given operands for an LShr, see if we can
1178/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001179static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001180 const TargetData *TD,
1181 const TargetLibraryInfo *TLI,
1182 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001183 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001184 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001185 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001186
1187 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001188 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001189 return Constant::getNullValue(Op0->getType());
1190
Chris Lattner81a0dc92011-02-09 17:15:04 +00001191 // (X << A) >> A -> X
1192 Value *X;
1193 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1194 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1195 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001196
Duncan Sandsc43cee32011-01-14 00:37:45 +00001197 return 0;
1198}
1199
Chris Lattner81a0dc92011-02-09 17:15:04 +00001200Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001201 const TargetData *TD,
1202 const TargetLibraryInfo *TLI,
1203 const DominatorTree *DT) {
1204 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001205}
1206
1207/// SimplifyAShrInst - Given operands for an AShr, see if we can
1208/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001209static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001210 const TargetData *TD,
1211 const TargetLibraryInfo *TLI,
1212 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001213 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001214 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001215 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001216
1217 // all ones >>a X -> all ones
1218 if (match(Op0, m_AllOnes()))
1219 return Op0;
1220
1221 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001222 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001223 return Constant::getAllOnesValue(Op0->getType());
1224
Chris Lattner81a0dc92011-02-09 17:15:04 +00001225 // (X << A) >> A -> X
1226 Value *X;
1227 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1228 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1229 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001230
Duncan Sandsc43cee32011-01-14 00:37:45 +00001231 return 0;
1232}
1233
Chris Lattner81a0dc92011-02-09 17:15:04 +00001234Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001235 const TargetData *TD,
1236 const TargetLibraryInfo *TLI,
1237 const DominatorTree *DT) {
1238 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001239}
1240
Chris Lattnerd06094f2009-11-10 00:55:12 +00001241/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001242/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001243static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1244 const TargetLibraryInfo *TLI,
1245 const DominatorTree *DT,
1246 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001247 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1248 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1249 Constant *Ops[] = { CLHS, CRHS };
1250 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001251 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001252 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001253
Chris Lattnerd06094f2009-11-10 00:55:12 +00001254 // Canonicalize the constant to the RHS.
1255 std::swap(Op0, Op1);
1256 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001257
Chris Lattnerd06094f2009-11-10 00:55:12 +00001258 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001259 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001260 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001261
Chris Lattnerd06094f2009-11-10 00:55:12 +00001262 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001263 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001264 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001265
Duncan Sands2b749872010-11-17 18:52:15 +00001266 // X & 0 = 0
1267 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001268 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001269
Duncan Sands2b749872010-11-17 18:52:15 +00001270 // X & -1 = X
1271 if (match(Op1, m_AllOnes()))
1272 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001273
Chris Lattnerd06094f2009-11-10 00:55:12 +00001274 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001275 if (match(Op0, m_Not(m_Specific(Op1))) ||
1276 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001277 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001278
Chris Lattnerd06094f2009-11-10 00:55:12 +00001279 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001280 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001281 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001282 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001283 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001284
Chris Lattnerd06094f2009-11-10 00:55:12 +00001285 // A & (A | ?) = A
1286 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001287 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001288 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001289
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001290 // A & (-A) = A if A is a power of two or zero.
1291 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1292 match(Op1, m_Neg(m_Specific(Op0)))) {
1293 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1294 return Op0;
1295 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1296 return Op1;
1297 }
1298
Duncan Sands566edb02010-12-21 08:49:00 +00001299 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001300 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1301 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001302 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001303
Duncan Sands3421d902010-12-21 13:32:22 +00001304 // And distributes over Or. Try some generic simplifications based on this.
1305 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001306 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001307 return V;
1308
1309 // And distributes over Xor. Try some generic simplifications based on this.
1310 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Chad Rosier618c1db2011-12-01 03:08:23 +00001311 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001312 return V;
1313
1314 // Or distributes over And. Try some generic simplifications based on this.
1315 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001316 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001317 return V;
1318
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001319 // If the operation is with the result of a select instruction, check whether
1320 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001321 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001322 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1323 DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001324 return V;
1325
1326 // If the operation is with the result of a phi instruction, check whether
1327 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001328 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001329 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001330 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001331 return V;
1332
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001333 return 0;
1334}
1335
Duncan Sands18450092010-11-16 12:16:38 +00001336Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001337 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001338 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001339 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001340}
1341
Chris Lattnerd06094f2009-11-10 00:55:12 +00001342/// SimplifyOrInst - Given operands for an Or, see if we can
1343/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001344static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1345 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001346 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001347 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1348 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1349 Constant *Ops[] = { CLHS, CRHS };
1350 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001351 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001352 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001353
Chris Lattnerd06094f2009-11-10 00:55:12 +00001354 // Canonicalize the constant to the RHS.
1355 std::swap(Op0, Op1);
1356 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001357
Chris Lattnerd06094f2009-11-10 00:55:12 +00001358 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001359 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001360 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001361
Chris Lattnerd06094f2009-11-10 00:55:12 +00001362 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001363 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001364 return Op0;
1365
Duncan Sands2b749872010-11-17 18:52:15 +00001366 // X | 0 = X
1367 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001368 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001369
Duncan Sands2b749872010-11-17 18:52:15 +00001370 // X | -1 = -1
1371 if (match(Op1, m_AllOnes()))
1372 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001373
Chris Lattnerd06094f2009-11-10 00:55:12 +00001374 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001375 if (match(Op0, m_Not(m_Specific(Op1))) ||
1376 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001377 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001378
Chris Lattnerd06094f2009-11-10 00:55:12 +00001379 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001380 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001381 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001382 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001383 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001384
Chris Lattnerd06094f2009-11-10 00:55:12 +00001385 // A | (A & ?) = A
1386 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001387 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001388 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001389
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001390 // ~(A & ?) | A = -1
1391 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1392 (A == Op1 || B == Op1))
1393 return Constant::getAllOnesValue(Op1->getType());
1394
1395 // A | ~(A & ?) = -1
1396 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1397 (A == Op0 || B == Op0))
1398 return Constant::getAllOnesValue(Op0->getType());
1399
Duncan Sands566edb02010-12-21 08:49:00 +00001400 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001401 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1402 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001403 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001404
Duncan Sands3421d902010-12-21 13:32:22 +00001405 // Or distributes over And. Try some generic simplifications based on this.
Chad Rosier618c1db2011-12-01 03:08:23 +00001406 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1407 TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001408 return V;
1409
1410 // And distributes over Or. Try some generic simplifications based on this.
1411 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001412 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001413 return V;
1414
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001415 // If the operation is with the result of a select instruction, check whether
1416 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001417 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001418 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001419 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001420 return V;
1421
1422 // If the operation is with the result of a phi instruction, check whether
1423 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001424 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001425 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001426 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001427 return V;
1428
Chris Lattnerd06094f2009-11-10 00:55:12 +00001429 return 0;
1430}
1431
Duncan Sands18450092010-11-16 12:16:38 +00001432Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001433 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001434 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001435 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001436}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001437
Duncan Sands2b749872010-11-17 18:52:15 +00001438/// SimplifyXorInst - Given operands for a Xor, see if we can
1439/// fold the result. If not, this returns null.
1440static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001441 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001442 const DominatorTree *DT, unsigned MaxRecurse) {
1443 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1444 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1445 Constant *Ops[] = { CLHS, CRHS };
1446 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001447 Ops, TD, TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001448 }
1449
1450 // Canonicalize the constant to the RHS.
1451 std::swap(Op0, Op1);
1452 }
1453
1454 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001455 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001456 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001457
1458 // A ^ 0 = A
1459 if (match(Op1, m_Zero()))
1460 return Op0;
1461
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001462 // A ^ A = 0
1463 if (Op0 == Op1)
1464 return Constant::getNullValue(Op0->getType());
1465
Duncan Sands2b749872010-11-17 18:52:15 +00001466 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001467 if (match(Op0, m_Not(m_Specific(Op1))) ||
1468 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001469 return Constant::getAllOnesValue(Op0->getType());
1470
Duncan Sands566edb02010-12-21 08:49:00 +00001471 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001472 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1473 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001474 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001475
Duncan Sands3421d902010-12-21 13:32:22 +00001476 // And distributes over Xor. Try some generic simplifications based on this.
1477 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001478 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001479 return V;
1480
Duncan Sands87689cf2010-11-19 09:20:39 +00001481 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1482 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1483 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1484 // only if B and C are equal. If B and C are equal then (since we assume
1485 // that operands have already been simplified) "select(cond, B, C)" should
1486 // have been simplified to the common value of B and C already. Analysing
1487 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1488 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001489
1490 return 0;
1491}
1492
1493Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001494 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001495 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001496 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001497}
1498
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001499static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001500 return CmpInst::makeCmpResultType(Op->getType());
1501}
1502
Duncan Sandse864b5b2011-05-07 16:56:49 +00001503/// ExtractEquivalentCondition - Rummage around inside V looking for something
1504/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1505/// otherwise return null. Helper function for analyzing max/min idioms.
1506static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1507 Value *LHS, Value *RHS) {
1508 SelectInst *SI = dyn_cast<SelectInst>(V);
1509 if (!SI)
1510 return 0;
1511 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1512 if (!Cmp)
1513 return 0;
1514 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1515 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1516 return Cmp;
1517 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1518 LHS == CmpRHS && RHS == CmpLHS)
1519 return Cmp;
1520 return 0;
1521}
1522
Chris Lattner9dbb4292009-11-09 23:28:39 +00001523/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1524/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001525static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00001526 const TargetData *TD,
1527 const TargetLibraryInfo *TLI,
1528 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00001529 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001530 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001531 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001532
Chris Lattnerd06094f2009-11-10 00:55:12 +00001533 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001534 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00001535 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001536
1537 // If we have a constant, make sure it is on the RHS.
1538 std::swap(LHS, RHS);
1539 Pred = CmpInst::getSwappedPredicate(Pred);
1540 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001541
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001542 Type *ITy = GetCompareTy(LHS); // The return type.
1543 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001544
Chris Lattner210c5d42009-11-09 23:55:12 +00001545 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001546 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1547 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001548 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001549 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001550
Duncan Sands6dc91252011-01-13 08:56:29 +00001551 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001552 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001553 switch (Pred) {
1554 default: break;
1555 case ICmpInst::ICMP_EQ:
1556 // X == 1 -> X
1557 if (match(RHS, m_One()))
1558 return LHS;
1559 break;
1560 case ICmpInst::ICMP_NE:
1561 // X != 0 -> X
1562 if (match(RHS, m_Zero()))
1563 return LHS;
1564 break;
1565 case ICmpInst::ICMP_UGT:
1566 // X >u 0 -> X
1567 if (match(RHS, m_Zero()))
1568 return LHS;
1569 break;
1570 case ICmpInst::ICMP_UGE:
1571 // X >=u 1 -> X
1572 if (match(RHS, m_One()))
1573 return LHS;
1574 break;
1575 case ICmpInst::ICMP_SLT:
1576 // X <s 0 -> X
1577 if (match(RHS, m_Zero()))
1578 return LHS;
1579 break;
1580 case ICmpInst::ICMP_SLE:
1581 // X <=s -1 -> X
1582 if (match(RHS, m_One()))
1583 return LHS;
1584 break;
1585 }
1586 }
1587
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001588 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1589 // different addresses, and what's more the address of a stack variable is
1590 // never null or equal to the address of a global. Note that generalizing
1591 // to the case where LHS is a global variable address or null is pointless,
1592 // since if both LHS and RHS are constants then we already constant folded
1593 // the compare, and if only one of them is then we moved it to RHS already.
1594 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1595 isa<ConstantPointerNull>(RHS)))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001596 // We already know that LHS != RHS.
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001597 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1598
1599 // If we are comparing with zero then try hard since this is a common case.
1600 if (match(RHS, m_Zero())) {
1601 bool LHSKnownNonNegative, LHSKnownNegative;
1602 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001603 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001604 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001605 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001606 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001607 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001608 case ICmpInst::ICMP_EQ:
1609 case ICmpInst::ICMP_ULE:
1610 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001611 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001612 break;
1613 case ICmpInst::ICMP_NE:
1614 case ICmpInst::ICMP_UGT:
1615 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001616 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001617 break;
1618 case ICmpInst::ICMP_SLT:
1619 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1620 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001621 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001622 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001623 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001624 break;
1625 case ICmpInst::ICMP_SLE:
1626 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1627 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001628 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001629 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001630 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001631 break;
1632 case ICmpInst::ICMP_SGE:
1633 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1634 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001635 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001636 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001637 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001638 break;
1639 case ICmpInst::ICMP_SGT:
1640 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1641 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001642 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001643 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001644 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001645 break;
1646 }
1647 }
1648
1649 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001650 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001651 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1652 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1653 if (RHS_CR.isEmptySet())
1654 return ConstantInt::getFalse(CI->getContext());
1655 if (RHS_CR.isFullSet())
1656 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001657
Nick Lewycky3a73e342011-03-04 07:00:57 +00001658 // Many binary operators with constant RHS have easy to compute constant
1659 // range. Use them to check whether the comparison is a tautology.
1660 uint32_t Width = CI->getBitWidth();
1661 APInt Lower = APInt(Width, 0);
1662 APInt Upper = APInt(Width, 0);
1663 ConstantInt *CI2;
1664 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1665 // 'urem x, CI2' produces [0, CI2).
1666 Upper = CI2->getValue();
1667 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1668 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1669 Upper = CI2->getValue().abs();
1670 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001671 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1672 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001673 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001674 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1675 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1676 APInt NegOne = APInt::getAllOnesValue(Width);
1677 if (!CI2->isZero())
1678 Upper = NegOne.udiv(CI2->getValue()) + 1;
1679 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1680 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1681 APInt IntMin = APInt::getSignedMinValue(Width);
1682 APInt IntMax = APInt::getSignedMaxValue(Width);
1683 APInt Val = CI2->getValue().abs();
1684 if (!Val.isMinValue()) {
1685 Lower = IntMin.sdiv(Val);
1686 Upper = IntMax.sdiv(Val) + 1;
1687 }
1688 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1689 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1690 APInt NegOne = APInt::getAllOnesValue(Width);
1691 if (CI2->getValue().ult(Width))
1692 Upper = NegOne.lshr(CI2->getValue()) + 1;
1693 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1694 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1695 APInt IntMin = APInt::getSignedMinValue(Width);
1696 APInt IntMax = APInt::getSignedMaxValue(Width);
1697 if (CI2->getValue().ult(Width)) {
1698 Lower = IntMin.ashr(CI2->getValue());
1699 Upper = IntMax.ashr(CI2->getValue()) + 1;
1700 }
1701 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1702 // 'or x, CI2' produces [CI2, UINT_MAX].
1703 Lower = CI2->getValue();
1704 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1705 // 'and x, CI2' produces [0, CI2].
1706 Upper = CI2->getValue() + 1;
1707 }
1708 if (Lower != Upper) {
1709 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1710 if (RHS_CR.contains(LHS_CR))
1711 return ConstantInt::getTrue(RHS->getContext());
1712 if (RHS_CR.inverse().contains(LHS_CR))
1713 return ConstantInt::getFalse(RHS->getContext());
1714 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001715 }
1716
Duncan Sands9d32f602011-01-20 13:21:55 +00001717 // Compare of cast, for example (zext X) != 0 -> X != 0
1718 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1719 Instruction *LI = cast<CastInst>(LHS);
1720 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001721 Type *SrcTy = SrcOp->getType();
1722 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001723
1724 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1725 // if the integer type is the same size as the pointer type.
1726 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1727 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1728 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1729 // Transfer the cast to the constant.
1730 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1731 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001732 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001733 return V;
1734 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1735 if (RI->getOperand(0)->getType() == SrcTy)
1736 // Compare without the cast.
1737 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001738 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001739 return V;
1740 }
1741 }
1742
1743 if (isa<ZExtInst>(LHS)) {
1744 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1745 // same type.
1746 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1747 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1748 // Compare X and Y. Note that signed predicates become unsigned.
1749 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Chad Rosier618c1db2011-12-01 03:08:23 +00001750 SrcOp, RI->getOperand(0), TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001751 MaxRecurse-1))
1752 return V;
1753 }
1754 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1755 // too. If not, then try to deduce the result of the comparison.
1756 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1757 // Compute the constant that would happen if we truncated to SrcTy then
1758 // reextended to DstTy.
1759 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1760 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1761
1762 // If the re-extended constant didn't change then this is effectively
1763 // also a case of comparing two zero-extended values.
1764 if (RExt == CI && MaxRecurse)
1765 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Nadav Rotem16087692011-12-05 06:29:09 +00001766 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001767 return V;
1768
1769 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1770 // there. Use this to work out the result of the comparison.
1771 if (RExt != CI) {
1772 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001773 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001774 // LHS <u RHS.
1775 case ICmpInst::ICMP_EQ:
1776 case ICmpInst::ICMP_UGT:
1777 case ICmpInst::ICMP_UGE:
1778 return ConstantInt::getFalse(CI->getContext());
1779
1780 case ICmpInst::ICMP_NE:
1781 case ICmpInst::ICMP_ULT:
1782 case ICmpInst::ICMP_ULE:
1783 return ConstantInt::getTrue(CI->getContext());
1784
1785 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1786 // is non-negative then LHS <s RHS.
1787 case ICmpInst::ICMP_SGT:
1788 case ICmpInst::ICMP_SGE:
1789 return CI->getValue().isNegative() ?
1790 ConstantInt::getTrue(CI->getContext()) :
1791 ConstantInt::getFalse(CI->getContext());
1792
1793 case ICmpInst::ICMP_SLT:
1794 case ICmpInst::ICMP_SLE:
1795 return CI->getValue().isNegative() ?
1796 ConstantInt::getFalse(CI->getContext()) :
1797 ConstantInt::getTrue(CI->getContext());
1798 }
1799 }
1800 }
1801 }
1802
1803 if (isa<SExtInst>(LHS)) {
1804 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1805 // same type.
1806 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1807 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1808 // Compare X and Y. Note that the predicate does not change.
1809 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001810 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001811 return V;
1812 }
1813 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1814 // too. If not, then try to deduce the result of the comparison.
1815 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1816 // Compute the constant that would happen if we truncated to SrcTy then
1817 // reextended to DstTy.
1818 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1819 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1820
1821 // If the re-extended constant didn't change then this is effectively
1822 // also a case of comparing two sign-extended values.
1823 if (RExt == CI && MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00001824 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001825 MaxRecurse-1))
1826 return V;
1827
1828 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1829 // bits there. Use this to work out the result of the comparison.
1830 if (RExt != CI) {
1831 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001832 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001833 case ICmpInst::ICMP_EQ:
1834 return ConstantInt::getFalse(CI->getContext());
1835 case ICmpInst::ICMP_NE:
1836 return ConstantInt::getTrue(CI->getContext());
1837
1838 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1839 // LHS >s RHS.
1840 case ICmpInst::ICMP_SGT:
1841 case ICmpInst::ICMP_SGE:
1842 return CI->getValue().isNegative() ?
1843 ConstantInt::getTrue(CI->getContext()) :
1844 ConstantInt::getFalse(CI->getContext());
1845 case ICmpInst::ICMP_SLT:
1846 case ICmpInst::ICMP_SLE:
1847 return CI->getValue().isNegative() ?
1848 ConstantInt::getFalse(CI->getContext()) :
1849 ConstantInt::getTrue(CI->getContext());
1850
1851 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1852 // LHS >u RHS.
1853 case ICmpInst::ICMP_UGT:
1854 case ICmpInst::ICMP_UGE:
1855 // Comparison is true iff the LHS <s 0.
1856 if (MaxRecurse)
1857 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1858 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001859 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001860 return V;
1861 break;
1862 case ICmpInst::ICMP_ULT:
1863 case ICmpInst::ICMP_ULE:
1864 // Comparison is true iff the LHS >=s 0.
1865 if (MaxRecurse)
1866 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1867 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001868 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001869 return V;
1870 break;
1871 }
1872 }
1873 }
1874 }
1875 }
1876
Duncan Sands52fb8462011-02-13 17:15:40 +00001877 // Special logic for binary operators.
1878 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1879 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1880 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001881 // Analyze the case when either LHS or RHS is an add instruction.
1882 Value *A = 0, *B = 0, *C = 0, *D = 0;
1883 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1884 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1885 if (LBO && LBO->getOpcode() == Instruction::Add) {
1886 A = LBO->getOperand(0); B = LBO->getOperand(1);
1887 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1888 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1889 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1890 }
1891 if (RBO && RBO->getOpcode() == Instruction::Add) {
1892 C = RBO->getOperand(0); D = RBO->getOperand(1);
1893 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1894 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1895 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1896 }
1897
1898 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1899 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1900 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1901 Constant::getNullValue(RHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00001902 TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00001903 return V;
1904
1905 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1906 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1907 if (Value *V = SimplifyICmpInst(Pred,
1908 Constant::getNullValue(LHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00001909 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00001910 return V;
1911
1912 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1913 if (A && C && (A == C || A == D || B == C || B == D) &&
1914 NoLHSWrapProblem && NoRHSWrapProblem) {
1915 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1916 Value *Y = (A == C || A == D) ? B : A;
1917 Value *Z = (C == A || C == B) ? D : C;
Chad Rosier618c1db2011-12-01 03:08:23 +00001918 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00001919 return V;
1920 }
1921 }
1922
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001923 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00001924 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001925 switch (Pred) {
1926 default:
1927 break;
Nick Lewycky78679272011-03-04 10:06:52 +00001928 case ICmpInst::ICMP_SGT:
1929 case ICmpInst::ICMP_SGE:
1930 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1931 if (!KnownNonNegative)
1932 break;
1933 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001934 case ICmpInst::ICMP_EQ:
1935 case ICmpInst::ICMP_UGT:
1936 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001937 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00001938 case ICmpInst::ICMP_SLT:
1939 case ICmpInst::ICMP_SLE:
1940 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1941 if (!KnownNonNegative)
1942 break;
1943 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001944 case ICmpInst::ICMP_NE:
1945 case ICmpInst::ICMP_ULT:
1946 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001947 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001948 }
1949 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001950 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1951 bool KnownNonNegative, KnownNegative;
1952 switch (Pred) {
1953 default:
1954 break;
1955 case ICmpInst::ICMP_SGT:
1956 case ICmpInst::ICMP_SGE:
1957 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1958 if (!KnownNonNegative)
1959 break;
1960 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001961 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001962 case ICmpInst::ICMP_UGT:
1963 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001964 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001965 case ICmpInst::ICMP_SLT:
1966 case ICmpInst::ICMP_SLE:
1967 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1968 if (!KnownNonNegative)
1969 break;
1970 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001971 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001972 case ICmpInst::ICMP_ULT:
1973 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001974 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001975 }
1976 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001977
Duncan Sandsc65c7472011-10-28 18:17:44 +00001978 // x udiv y <=u x.
1979 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
1980 // icmp pred (X /u Y), X
1981 if (Pred == ICmpInst::ICMP_UGT)
1982 return getFalse(ITy);
1983 if (Pred == ICmpInst::ICMP_ULE)
1984 return getTrue(ITy);
1985 }
1986
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001987 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1988 LBO->getOperand(1) == RBO->getOperand(1)) {
1989 switch (LBO->getOpcode()) {
1990 default: break;
1991 case Instruction::UDiv:
1992 case Instruction::LShr:
1993 if (ICmpInst::isSigned(Pred))
1994 break;
1995 // fall-through
1996 case Instruction::SDiv:
1997 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00001998 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001999 break;
2000 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002001 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002002 return V;
2003 break;
2004 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002005 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002006 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2007 if (!NUW && !NSW)
2008 break;
2009 if (!NSW && ICmpInst::isSigned(Pred))
2010 break;
2011 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002012 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002013 return V;
2014 break;
2015 }
2016 }
2017 }
2018
Duncan Sandsad206812011-05-03 19:53:10 +00002019 // Simplify comparisons involving max/min.
2020 Value *A, *B;
2021 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2022 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2023
Duncan Sands8140ad32011-05-04 16:05:05 +00002024 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002025 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2026 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2027 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2028 // We analyze this as smax(A, B) pred A.
2029 P = Pred;
2030 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2031 (A == LHS || B == LHS)) {
2032 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2033 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2034 // We analyze this as smax(A, B) swapped-pred A.
2035 P = CmpInst::getSwappedPredicate(Pred);
2036 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2037 (A == RHS || B == RHS)) {
2038 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2039 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2040 // We analyze this as smax(-A, -B) swapped-pred -A.
2041 // Note that we do not need to actually form -A or -B thanks to EqP.
2042 P = CmpInst::getSwappedPredicate(Pred);
2043 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2044 (A == LHS || B == LHS)) {
2045 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2046 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2047 // We analyze this as smax(-A, -B) pred -A.
2048 // Note that we do not need to actually form -A or -B thanks to EqP.
2049 P = Pred;
2050 }
2051 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2052 // Cases correspond to "max(A, B) p A".
2053 switch (P) {
2054 default:
2055 break;
2056 case CmpInst::ICMP_EQ:
2057 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002058 // Equivalent to "A EqP B". This may be the same as the condition tested
2059 // in the max/min; if so, we can just return that.
2060 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2061 return V;
2062 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2063 return V;
2064 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002065 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002066 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002067 return V;
2068 break;
2069 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002070 case CmpInst::ICMP_SGT: {
2071 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2072 // Equivalent to "A InvEqP B". This may be the same as the condition
2073 // tested in the max/min; if so, we can just return that.
2074 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2075 return V;
2076 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2077 return V;
2078 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002079 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002080 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002081 return V;
2082 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002083 }
Duncan Sandsad206812011-05-03 19:53:10 +00002084 case CmpInst::ICMP_SGE:
2085 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002086 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002087 case CmpInst::ICMP_SLT:
2088 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002089 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002090 }
2091 }
2092
Duncan Sands8140ad32011-05-04 16:05:05 +00002093 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002094 P = CmpInst::BAD_ICMP_PREDICATE;
2095 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2096 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2097 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2098 // We analyze this as umax(A, B) pred A.
2099 P = Pred;
2100 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2101 (A == LHS || B == LHS)) {
2102 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2103 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2104 // We analyze this as umax(A, B) swapped-pred A.
2105 P = CmpInst::getSwappedPredicate(Pred);
2106 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2107 (A == RHS || B == RHS)) {
2108 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2109 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2110 // We analyze this as umax(-A, -B) swapped-pred -A.
2111 // Note that we do not need to actually form -A or -B thanks to EqP.
2112 P = CmpInst::getSwappedPredicate(Pred);
2113 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2114 (A == LHS || B == LHS)) {
2115 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2116 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2117 // We analyze this as umax(-A, -B) pred -A.
2118 // Note that we do not need to actually form -A or -B thanks to EqP.
2119 P = Pred;
2120 }
2121 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2122 // Cases correspond to "max(A, B) p A".
2123 switch (P) {
2124 default:
2125 break;
2126 case CmpInst::ICMP_EQ:
2127 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002128 // Equivalent to "A EqP B". This may be the same as the condition tested
2129 // in the max/min; if so, we can just return that.
2130 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2131 return V;
2132 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2133 return V;
2134 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002135 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002136 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002137 return V;
2138 break;
2139 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002140 case CmpInst::ICMP_UGT: {
2141 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2142 // Equivalent to "A InvEqP B". This may be the same as the condition
2143 // tested in the max/min; if so, we can just return that.
2144 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2145 return V;
2146 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2147 return V;
2148 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002149 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002150 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002151 return V;
2152 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002153 }
Duncan Sandsad206812011-05-03 19:53:10 +00002154 case CmpInst::ICMP_UGE:
2155 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002156 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002157 case CmpInst::ICMP_ULT:
2158 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002159 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002160 }
2161 }
2162
Duncan Sands8140ad32011-05-04 16:05:05 +00002163 // Variants on "max(x,y) >= min(x,z)".
2164 Value *C, *D;
2165 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2166 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2167 (A == C || A == D || B == C || B == D)) {
2168 // max(x, ?) pred min(x, ?).
2169 if (Pred == CmpInst::ICMP_SGE)
2170 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002171 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002172 if (Pred == CmpInst::ICMP_SLT)
2173 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002174 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002175 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2176 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2177 (A == C || A == D || B == C || B == D)) {
2178 // min(x, ?) pred max(x, ?).
2179 if (Pred == CmpInst::ICMP_SLE)
2180 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002181 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002182 if (Pred == CmpInst::ICMP_SGT)
2183 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002184 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002185 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2186 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2187 (A == C || A == D || B == C || B == D)) {
2188 // max(x, ?) pred min(x, ?).
2189 if (Pred == CmpInst::ICMP_UGE)
2190 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002191 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002192 if (Pred == CmpInst::ICMP_ULT)
2193 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002194 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002195 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2196 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2197 (A == C || A == D || B == C || B == D)) {
2198 // min(x, ?) pred max(x, ?).
2199 if (Pred == CmpInst::ICMP_ULE)
2200 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002201 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002202 if (Pred == CmpInst::ICMP_UGT)
2203 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002204 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002205 }
2206
Duncan Sands1ac7c992010-11-07 16:12:23 +00002207 // If the comparison is with the result of a select instruction, check whether
2208 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002209 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002210 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002211 return V;
2212
2213 // If the comparison is with the result of a phi instruction, check whether
2214 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002215 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002216 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002217 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002218
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002219 return 0;
2220}
2221
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002222Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002223 const TargetData *TD,
2224 const TargetLibraryInfo *TLI,
2225 const DominatorTree *DT) {
2226 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002227}
2228
Chris Lattner9dbb4292009-11-09 23:28:39 +00002229/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2230/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002231static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002232 const TargetData *TD,
2233 const TargetLibraryInfo *TLI,
2234 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002235 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002236 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2237 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2238
Chris Lattnerd06094f2009-11-10 00:55:12 +00002239 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002240 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002241 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002242
Chris Lattnerd06094f2009-11-10 00:55:12 +00002243 // If we have a constant, make sure it is on the RHS.
2244 std::swap(LHS, RHS);
2245 Pred = CmpInst::getSwappedPredicate(Pred);
2246 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002247
Chris Lattner210c5d42009-11-09 23:55:12 +00002248 // Fold trivial predicates.
2249 if (Pred == FCmpInst::FCMP_FALSE)
2250 return ConstantInt::get(GetCompareTy(LHS), 0);
2251 if (Pred == FCmpInst::FCMP_TRUE)
2252 return ConstantInt::get(GetCompareTy(LHS), 1);
2253
Chris Lattner210c5d42009-11-09 23:55:12 +00002254 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2255 return UndefValue::get(GetCompareTy(LHS));
2256
2257 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002258 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002259 if (CmpInst::isTrueWhenEqual(Pred))
2260 return ConstantInt::get(GetCompareTy(LHS), 1);
2261 if (CmpInst::isFalseWhenEqual(Pred))
2262 return ConstantInt::get(GetCompareTy(LHS), 0);
2263 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002264
Chris Lattner210c5d42009-11-09 23:55:12 +00002265 // Handle fcmp with constant RHS
2266 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2267 // If the constant is a nan, see if we can fold the comparison based on it.
2268 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2269 if (CFP->getValueAPF().isNaN()) {
2270 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2271 return ConstantInt::getFalse(CFP->getContext());
2272 assert(FCmpInst::isUnordered(Pred) &&
2273 "Comparison must be either ordered or unordered!");
2274 // True if unordered.
2275 return ConstantInt::getTrue(CFP->getContext());
2276 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002277 // Check whether the constant is an infinity.
2278 if (CFP->getValueAPF().isInfinity()) {
2279 if (CFP->getValueAPF().isNegative()) {
2280 switch (Pred) {
2281 case FCmpInst::FCMP_OLT:
2282 // No value is ordered and less than negative infinity.
2283 return ConstantInt::getFalse(CFP->getContext());
2284 case FCmpInst::FCMP_UGE:
2285 // All values are unordered with or at least negative infinity.
2286 return ConstantInt::getTrue(CFP->getContext());
2287 default:
2288 break;
2289 }
2290 } else {
2291 switch (Pred) {
2292 case FCmpInst::FCMP_OGT:
2293 // No value is ordered and greater than infinity.
2294 return ConstantInt::getFalse(CFP->getContext());
2295 case FCmpInst::FCMP_ULE:
2296 // All values are unordered with and at most infinity.
2297 return ConstantInt::getTrue(CFP->getContext());
2298 default:
2299 break;
2300 }
2301 }
2302 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002303 }
2304 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002305
Duncan Sands92826de2010-11-07 16:46:25 +00002306 // If the comparison is with the result of a select instruction, check whether
2307 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002308 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002309 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002310 return V;
2311
2312 // If the comparison is with the result of a phi instruction, check whether
2313 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002314 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002315 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002316 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002317
Chris Lattner9dbb4292009-11-09 23:28:39 +00002318 return 0;
2319}
2320
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002321Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002322 const TargetData *TD,
2323 const TargetLibraryInfo *TLI,
2324 const DominatorTree *DT) {
2325 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002326}
2327
Chris Lattner04754262010-04-20 05:32:14 +00002328/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2329/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00002330Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2331 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00002332 // select true, X, Y -> X
2333 // select false, X, Y -> Y
2334 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2335 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002336
Chris Lattner04754262010-04-20 05:32:14 +00002337 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002338 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002339 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002340
Chris Lattner04754262010-04-20 05:32:14 +00002341 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2342 if (isa<Constant>(TrueVal))
2343 return TrueVal;
2344 return FalseVal;
2345 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002346 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2347 return FalseVal;
2348 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2349 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002350
Chris Lattner04754262010-04-20 05:32:14 +00002351 return 0;
2352}
2353
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002354/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2355/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00002356Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2357 const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002358 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002359 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2360 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2361 if (!PtrTy)
2362 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002363
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002364 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002365 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002366 return Ops[0];
2367
Duncan Sands85bbff62010-11-22 13:42:49 +00002368 if (isa<UndefValue>(Ops[0])) {
2369 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002370 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002371 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002372 return UndefValue::get(GEPTy);
2373 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002374
Jay Foadb9b54eb2011-07-19 15:07:52 +00002375 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002376 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002377 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2378 if (C->isZero())
2379 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002380 // getelementptr P, N -> P if P points to a type of zero size.
2381 if (TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002382 Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00002383 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002384 return Ops[0];
2385 }
2386 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002387
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002388 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002389 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002390 if (!isa<Constant>(Ops[i]))
2391 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002392
Jay Foaddab3d292011-07-21 14:31:17 +00002393 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002394}
2395
Duncan Sandsdabc2802011-09-05 06:52:48 +00002396/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2397/// can fold the result. If not, this returns null.
2398Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2399 ArrayRef<unsigned> Idxs,
2400 const TargetData *,
2401 const DominatorTree *) {
2402 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2403 if (Constant *CVal = dyn_cast<Constant>(Val))
2404 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2405
2406 // insertvalue x, undef, n -> x
2407 if (match(Val, m_Undef()))
2408 return Agg;
2409
2410 // insertvalue x, (extractvalue y, n), n
2411 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002412 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2413 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002414 // insertvalue undef, (extractvalue y, n), n -> y
2415 if (match(Agg, m_Undef()))
2416 return EV->getAggregateOperand();
2417
2418 // insertvalue y, (extractvalue y, n), n -> y
2419 if (Agg == EV->getAggregateOperand())
2420 return Agg;
2421 }
2422
2423 return 0;
2424}
2425
Duncan Sandsff103412010-11-17 04:30:22 +00002426/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2427static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2428 // If all of the PHI's incoming values are the same then replace the PHI node
2429 // with the common value.
2430 Value *CommonValue = 0;
2431 bool HasUndefInput = false;
2432 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2433 Value *Incoming = PN->getIncomingValue(i);
2434 // If the incoming value is the phi node itself, it can safely be skipped.
2435 if (Incoming == PN) continue;
2436 if (isa<UndefValue>(Incoming)) {
2437 // Remember that we saw an undef value, but otherwise ignore them.
2438 HasUndefInput = true;
2439 continue;
2440 }
2441 if (CommonValue && Incoming != CommonValue)
2442 return 0; // Not the same, bail out.
2443 CommonValue = Incoming;
2444 }
2445
2446 // If CommonValue is null then all of the incoming values were either undef or
2447 // equal to the phi node itself.
2448 if (!CommonValue)
2449 return UndefValue::get(PN->getType());
2450
2451 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2452 // instruction, we cannot return X as the result of the PHI node unless it
2453 // dominates the PHI block.
2454 if (HasUndefInput)
2455 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2456
2457 return CommonValue;
2458}
2459
Chris Lattnerd06094f2009-11-10 00:55:12 +00002460//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002461
Chris Lattnerd06094f2009-11-10 00:55:12 +00002462/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2463/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002464static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002465 const TargetData *TD,
2466 const TargetLibraryInfo *TLI,
2467 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002468 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002469 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002470 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002471 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002472 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002473 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002474 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002475 TD, TLI, DT, MaxRecurse);
2476 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2477 MaxRecurse);
2478 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2479 MaxRecurse);
2480 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2481 MaxRecurse);
2482 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2483 MaxRecurse);
2484 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2485 MaxRecurse);
2486 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2487 MaxRecurse);
2488 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2489 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002490 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002491 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002492 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002493 case Instruction::LShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002494 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2495 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002496 case Instruction::AShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002497 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2498 MaxRecurse);
2499 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2500 MaxRecurse);
2501 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2502 MaxRecurse);
2503 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2504 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002505 default:
2506 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2507 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2508 Constant *COps[] = {CLHS, CRHS};
Chad Rosier618c1db2011-12-01 03:08:23 +00002509 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002510 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002511
Duncan Sands566edb02010-12-21 08:49:00 +00002512 // If the operation is associative, try some generic simplifications.
2513 if (Instruction::isAssociative(Opcode))
Chad Rosier618c1db2011-12-01 03:08:23 +00002514 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +00002515 MaxRecurse))
2516 return V;
2517
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002518 // If the operation is with the result of a select instruction, check whether
2519 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002520 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002521 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002522 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002523 return V;
2524
2525 // If the operation is with the result of a phi instruction, check whether
2526 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002527 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002528 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2529 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002530 return V;
2531
Chris Lattnerd06094f2009-11-10 00:55:12 +00002532 return 0;
2533 }
2534}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002535
Duncan Sands12a86f52010-11-14 11:23:23 +00002536Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002537 const TargetData *TD, const TargetLibraryInfo *TLI,
2538 const DominatorTree *DT) {
2539 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002540}
2541
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002542/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2543/// fold the result.
2544static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002545 const TargetData *TD,
2546 const TargetLibraryInfo *TLI,
2547 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002548 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002549 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Chad Rosier618c1db2011-12-01 03:08:23 +00002550 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2551 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002552}
2553
2554Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002555 const TargetData *TD, const TargetLibraryInfo *TLI,
2556 const DominatorTree *DT) {
2557 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002558}
Chris Lattnere3453782009-11-10 01:08:51 +00002559
Dan Gohman71d05032011-11-04 18:32:42 +00002560static Value *SimplifyCallInst(CallInst *CI) {
2561 // call undef -> undef
2562 if (isa<UndefValue>(CI->getCalledValue()))
2563 return UndefValue::get(CI->getType());
2564
2565 return 0;
2566}
2567
Chris Lattnere3453782009-11-10 01:08:51 +00002568/// SimplifyInstruction - See if we can compute a simplified version of this
2569/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002570Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002571 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002572 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002573 Value *Result;
2574
Chris Lattnere3453782009-11-10 01:08:51 +00002575 switch (I->getOpcode()) {
2576 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002577 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002578 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002579 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002580 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2581 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2582 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002583 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002584 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002585 case Instruction::Sub:
2586 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2587 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2588 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002589 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002590 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002591 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002592 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002593 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002594 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002595 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002596 break;
2597 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002598 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002599 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002600 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002601 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002602 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002603 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002604 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002605 break;
2606 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002607 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002608 break;
2609 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002610 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002611 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002612 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002613 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2614 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2615 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002616 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002617 break;
2618 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002619 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2620 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002621 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002622 break;
2623 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002624 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2625 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002626 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002627 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002628 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002629 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002630 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002631 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002632 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002633 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002634 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002635 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002636 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002637 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002638 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002639 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002640 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002641 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002642 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002643 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002644 break;
Chris Lattner04754262010-04-20 05:32:14 +00002645 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002646 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2647 I->getOperand(2), TD, DT);
2648 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002649 case Instruction::GetElementPtr: {
2650 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Jay Foadb9b54eb2011-07-19 15:07:52 +00002651 Result = SimplifyGEPInst(Ops, TD, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002652 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002653 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002654 case Instruction::InsertValue: {
2655 InsertValueInst *IV = cast<InsertValueInst>(I);
2656 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2657 IV->getInsertedValueOperand(),
2658 IV->getIndices(), TD, DT);
2659 break;
2660 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002661 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002662 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2663 break;
Dan Gohman71d05032011-11-04 18:32:42 +00002664 case Instruction::Call:
2665 Result = SimplifyCallInst(cast<CallInst>(I));
2666 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002667 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002668
2669 /// If called on unreachable code, the above logic may report that the
2670 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002671 /// detecting that case here, returning a safe value instead.
2672 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002673}
2674
Chris Lattner40d8c282009-11-10 22:26:15 +00002675/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2676/// delete the From instruction. In addition to a basic RAUW, this does a
2677/// recursive simplification of the newly formed instructions. This catches
2678/// things where one simplification exposes other opportunities. This only
2679/// simplifies and deletes scalar operations, it does not change the CFG.
2680///
2681void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002682 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002683 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002684 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002685 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002686
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002687 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2688 // we can know if it gets deleted out from under us or replaced in a
2689 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002690 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002691 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002692
Chris Lattner40d8c282009-11-10 22:26:15 +00002693 while (!From->use_empty()) {
2694 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002695 Use &TheUse = From->use_begin().getUse();
2696 Instruction *User = cast<Instruction>(TheUse.getUser());
2697 TheUse = To;
2698
2699 // Check to see if the instruction can be folded due to the operand
2700 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2701 // the 'or' with -1.
2702 Value *SimplifiedVal;
2703 {
2704 // Sanity check to make sure 'User' doesn't dangle across
2705 // SimplifyInstruction.
2706 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002707
Chad Rosier618c1db2011-12-01 03:08:23 +00002708 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002709 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002710 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002711
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002712 // Recursively simplify this user to the new value.
Chad Rosier618c1db2011-12-01 03:08:23 +00002713 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002714 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2715 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002716
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002717 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002718
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002719 // If the recursive simplification ended up revisiting and deleting
2720 // 'From' then we're done.
2721 if (From == 0)
2722 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002723 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002724
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002725 // If 'From' has value handles referring to it, do a real RAUW to update them.
2726 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002727
Chris Lattner40d8c282009-11-10 22:26:15 +00002728 From->eraseFromParent();
2729}