blob: f8e76ca22077c501a751dc9a70a6c9598291049d [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"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000021#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000022#include "llvm/ADT/SetVector.h"
23#include "llvm/ADT/Statistic.h"
Nick Lewyckyf7087ea2012-02-26 02:09:49 +000024#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000025#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000026#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000027#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/GlobalAlias.h"
30#include "llvm/IR/Operator.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000031#include "llvm/Support/ConstantRange.h"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000032#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000033#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000034#include "llvm/Support/ValueHandle.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000035using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000036using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000037
Chris Lattner81a0dc92011-02-09 17:15:04 +000038enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000039
Duncan Sandsa3c44a52010-12-22 09:40:51 +000040STATISTIC(NumExpand, "Number of expansions");
41STATISTIC(NumFactor , "Number of factorizations");
42STATISTIC(NumReassoc, "Number of reassociations");
43
Duncan Sands0aa85eb2012-03-13 11:42:19 +000044struct Query {
Micah Villmow3574eca2012-10-08 16:38:25 +000045 const DataLayout *TD;
Duncan Sands0aa85eb2012-03-13 11:42:19 +000046 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
48
Micah Villmow3574eca2012-10-08 16:38:25 +000049 Query(const DataLayout *td, const TargetLibraryInfo *tli,
Bill Wendling91337832012-05-17 20:27:58 +000050 const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {}
Duncan Sands0aa85eb2012-03-13 11:42:19 +000051};
52
53static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000055 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000056static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000057 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000058static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sandsbd0fe562012-03-13 14:07:05 +000060static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000061
Duncan Sandsf56138d2011-07-26 15:03:53 +000062/// getFalse - For a boolean type, or a vector of boolean type, return false, or
63/// a vector with every element false, as appropriate for the type.
64static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000065 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000066 "Expected i1 type or a vector of i1!");
67 return Constant::getNullValue(Ty);
68}
69
70/// getTrue - For a boolean type, or a vector of boolean type, return true, or
71/// a vector with every element true, as appropriate for the type.
72static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000073 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000074 "Expected i1 type or a vector of i1!");
75 return Constant::getAllOnesValue(Ty);
76}
77
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000078/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
80 Value *RHS) {
81 CmpInst *Cmp = dyn_cast<CmpInst>(V);
82 if (!Cmp)
83 return false;
84 CmpInst::Predicate CPred = Cmp->getPredicate();
85 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
87 return true;
88 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89 CRHS == LHS;
90}
91
Duncan Sands18450092010-11-16 12:16:38 +000092/// ValueDominatesPHI - Does the given value dominate the specified phi node?
93static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94 Instruction *I = dyn_cast<Instruction>(V);
95 if (!I)
96 // Arguments and constants dominate all instructions.
97 return true;
98
Chandler Carruthff739c12012-03-21 10:58:47 +000099 // If we are processing instructions (and/or basic blocks) that have not been
100 // fully added to a function, the parent nodes may still be null. Simply
101 // return the conservative answer in these cases.
102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
103 return false;
104
Duncan Sands18450092010-11-16 12:16:38 +0000105 // If we have a DominatorTree then do a precise test.
Eli Friedman5b8f0dd2012-03-13 01:06:07 +0000106 if (DT) {
107 if (!DT->isReachableFromEntry(P->getParent()))
108 return true;
109 if (!DT->isReachableFromEntry(I->getParent()))
110 return false;
111 return DT->dominates(I, P);
112 }
Duncan Sands18450092010-11-16 12:16:38 +0000113
114 // Otherwise, if the instruction is in the entry block, and is not an invoke,
115 // then it obviously dominates all phi nodes.
116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
117 !isa<InvokeInst>(I))
118 return true;
119
120 return false;
121}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000122
Duncan Sands3421d902010-12-21 13:32:22 +0000123/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
125/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127/// Returns the simplified value, or null if no simplification was performed.
128static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000129 unsigned OpcToExpand, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000130 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000132 // Recursion is always used, so bail out at once if we already hit the limit.
133 if (!MaxRecurse--)
134 return 0;
135
136 // Check whether the expression has the form "(A op' B) op C".
137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138 if (Op0->getOpcode() == OpcodeToExpand) {
139 // It does! Try turning it into "(A op C) op' (B op C)".
140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141 // Do "A op C" and "B op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000144 // They do! Return "L op' R" if it simplifies or is already available.
145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000148 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000149 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000150 }
Duncan Sands3421d902010-12-21 13:32:22 +0000151 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000153 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000154 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000155 }
Duncan Sands3421d902010-12-21 13:32:22 +0000156 }
157 }
158
159 // Check whether the expression has the form "A op (B op' C)".
160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161 if (Op1->getOpcode() == OpcodeToExpand) {
162 // It does! Try turning it into "(A op B) op' (A op C)".
163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164 // Do "A op B" and "A op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000167 // They do! Return "L op' R" if it simplifies or is already available.
168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000171 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000172 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000173 }
Duncan Sands3421d902010-12-21 13:32:22 +0000174 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000176 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000177 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000178 }
Duncan Sands3421d902010-12-21 13:32:22 +0000179 }
180 }
181
182 return 0;
183}
184
185/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
186/// using the operation OpCodeToExtract. For example, when Opcode is Add and
187/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
188/// Returns the simplified value, or null if no simplification was performed.
189static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000190 unsigned OpcToExtract, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000191 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000192 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000193 // Recursion is always used, so bail out at once if we already hit the limit.
194 if (!MaxRecurse--)
195 return 0;
196
197 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
198 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
199
200 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
201 !Op1 || Op1->getOpcode() != OpcodeToExtract)
202 return 0;
203
204 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000205 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
206 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000207
208 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
209 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
210 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000211 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
212 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000213 // Form "A op' (B op DD)" if it simplifies completely.
214 // Does "B op DD" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000215 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000216 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000217 // If V equals B then "A op' V" is just the LHS. If V equals DD then
218 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000219 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000220 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000221 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000222 }
Duncan Sands3421d902010-12-21 13:32:22 +0000223 // Otherwise return "A op' V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000224 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000225 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000226 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000227 }
Duncan Sands3421d902010-12-21 13:32:22 +0000228 }
229 }
230
231 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
232 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
233 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000234 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
235 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000236 // Form "(A op CC) op' B" if it simplifies completely..
237 // Does "A op CC" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000238 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000239 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000240 // If V equals A then "V op' B" is just the LHS. If V equals CC then
241 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000242 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000243 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000244 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000245 }
Duncan Sands3421d902010-12-21 13:32:22 +0000246 // Otherwise return "V op' B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000247 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000248 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000249 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000250 }
Duncan Sands3421d902010-12-21 13:32:22 +0000251 }
252 }
253
254 return 0;
255}
256
257/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
258/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000259static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000260 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000261 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000262 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
263
264 // Recursion is always used, so bail out at once if we already hit the limit.
265 if (!MaxRecurse--)
266 return 0;
267
268 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
269 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
270
271 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
272 if (Op0 && Op0->getOpcode() == Opcode) {
273 Value *A = Op0->getOperand(0);
274 Value *B = Op0->getOperand(1);
275 Value *C = RHS;
276
277 // Does "B op C" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000278 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000279 // It does! Return "A op V" if it simplifies or is already available.
280 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000281 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000282 // Otherwise return "A op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000283 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000284 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000285 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000286 }
Duncan Sands566edb02010-12-21 08:49:00 +0000287 }
288 }
289
290 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
291 if (Op1 && Op1->getOpcode() == Opcode) {
292 Value *A = LHS;
293 Value *B = Op1->getOperand(0);
294 Value *C = Op1->getOperand(1);
295
296 // Does "A op B" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000297 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000298 // It does! Return "V op C" if it simplifies or is already available.
299 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000300 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000301 // Otherwise return "V op C" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000302 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000303 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000304 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000305 }
Duncan Sands566edb02010-12-21 08:49:00 +0000306 }
307 }
308
309 // The remaining transforms require commutativity as well as associativity.
310 if (!Instruction::isCommutative(Opcode))
311 return 0;
312
313 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
314 if (Op0 && Op0->getOpcode() == Opcode) {
315 Value *A = Op0->getOperand(0);
316 Value *B = Op0->getOperand(1);
317 Value *C = RHS;
318
319 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000320 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000321 // It does! Return "V op B" if it simplifies or is already available.
322 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000323 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000324 // Otherwise return "V op B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000325 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000326 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000327 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000328 }
Duncan Sands566edb02010-12-21 08:49:00 +0000329 }
330 }
331
332 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
333 if (Op1 && Op1->getOpcode() == Opcode) {
334 Value *A = LHS;
335 Value *B = Op1->getOperand(0);
336 Value *C = Op1->getOperand(1);
337
338 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000339 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000340 // It does! Return "B op V" if it simplifies or is already available.
341 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000342 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000343 // Otherwise return "B op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000344 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000345 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000346 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000347 }
Duncan Sands566edb02010-12-21 08:49:00 +0000348 }
349 }
350
351 return 0;
352}
353
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000354/// ThreadBinOpOverSelect - In the case of a binary operation with a select
355/// instruction as an operand, try to simplify the binop by seeing whether
356/// evaluating it on both branches of the select results in the same value.
357/// Returns the common value if so, otherwise returns null.
358static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000359 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000360 // Recursion is always used, so bail out at once if we already hit the limit.
361 if (!MaxRecurse--)
362 return 0;
363
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000364 SelectInst *SI;
365 if (isa<SelectInst>(LHS)) {
366 SI = cast<SelectInst>(LHS);
367 } else {
368 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369 SI = cast<SelectInst>(RHS);
370 }
371
372 // Evaluate the BinOp on the true and false branches of the select.
373 Value *TV;
374 Value *FV;
375 if (SI == LHS) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000378 } else {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000381 }
382
Duncan Sands7cf85e72011-01-01 16:12:09 +0000383 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000384 // If they both failed to simplify then return null.
385 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000386 return TV;
387
388 // If one branch simplified to undef, return the other one.
389 if (TV && isa<UndefValue>(TV))
390 return FV;
391 if (FV && isa<UndefValue>(FV))
392 return TV;
393
394 // If applying the operation did not change the true and false select values,
395 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000397 return SI;
398
399 // If one branch simplified and the other did not, and the simplified
400 // value is equal to the unsimplified one, return the simplified value.
401 // For example, select (cond, X, X & Z) & Z -> X & Z.
402 if ((FV && !TV) || (TV && !FV)) {
403 // Check that the simplified value has the form "X op Y" where "op" is the
404 // same as the original operation.
405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406 if (Simplified && Simplified->getOpcode() == Opcode) {
407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408 // We already know that "op" is the same as for the simplified value. See
409 // if the operands match too. If so, return the simplified value.
410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000413 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000415 return Simplified;
416 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000417 Simplified->getOperand(1) == UnsimplifiedLHS &&
418 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000419 return Simplified;
420 }
421 }
422
423 return 0;
424}
425
426/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427/// try to simplify the comparison by seeing whether both branches of the select
428/// result in the same value. Returns the common value if so, otherwise returns
429/// null.
430static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000431 Value *RHS, const Query &Q,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000432 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000433 // Recursion is always used, so bail out at once if we already hit the limit.
434 if (!MaxRecurse--)
435 return 0;
436
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000437 // Make sure the select is on the LHS.
438 if (!isa<SelectInst>(LHS)) {
439 std::swap(LHS, RHS);
440 Pred = CmpInst::getSwappedPredicate(Pred);
441 }
442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000444 Value *Cond = SI->getCondition();
445 Value *TV = SI->getTrueValue();
446 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000447
Duncan Sands50ca4d32011-02-03 09:37:39 +0000448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000449 // Does "cmp TV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000451 if (TCmp == Cond) {
452 // It not only simplified, it simplified to the select condition. Replace
453 // it with 'true'.
454 TCmp = getTrue(Cond->getType());
455 } else if (!TCmp) {
456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
457 // condition then we can replace it with 'true'. Otherwise give up.
458 if (!isSameCompare(Cond, Pred, TV, RHS))
459 return 0;
460 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000461 }
462
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000463 // Does "cmp FV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000465 if (FCmp == Cond) {
466 // It not only simplified, it simplified to the select condition. Replace
467 // it with 'false'.
468 FCmp = getFalse(Cond->getType());
469 } else if (!FCmp) {
470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
471 // condition then we can replace it with 'false'. Otherwise give up.
472 if (!isSameCompare(Cond, Pred, FV, RHS))
473 return 0;
474 FCmp = getFalse(Cond->getType());
475 }
476
477 // If both sides simplified to the same value, then use it as the result of
478 // the original comparison.
479 if (TCmp == FCmp)
480 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000481
482 // The remaining cases only make sense if the select condition has the same
483 // type as the result of the comparison, so bail out if this is not so.
484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
485 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000486 // If the false value simplified to false, then the result of the compare
487 // is equal to "Cond && TCmp". This also catches the case when the false
488 // value simplified to false and the true value to true, returning "Cond".
489 if (match(FCmp, m_Zero()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000490 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000491 return V;
492 // If the true value simplified to true, then the result of the compare
493 // is equal to "Cond || FCmp".
494 if (match(TCmp, m_One()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000495 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000496 return V;
497 // Finally, if the false value simplified to true and the true value to
498 // false, then the result of the compare is equal to "!Cond".
499 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
500 if (Value *V =
501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000502 Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000503 return V;
504
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000505 return 0;
506}
507
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000508/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510/// it on the incoming phi values yields the same result for every value. If so
511/// returns the common value, otherwise returns null.
512static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000513 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000514 // Recursion is always used, so bail out at once if we already hit the limit.
515 if (!MaxRecurse--)
516 return 0;
517
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000518 PHINode *PI;
519 if (isa<PHINode>(LHS)) {
520 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000521 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000522 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000523 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000524 } else {
525 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
526 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000527 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000528 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000529 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000530 }
531
532 // Evaluate the BinOp on the incoming phi values.
533 Value *CommonValue = 0;
534 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000535 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000536 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000537 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000538 Value *V = PI == LHS ?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000539 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
540 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000541 // If the operation failed to simplify, or simplified to a different value
542 // to previously, then give up.
543 if (!V || (CommonValue && V != CommonValue))
544 return 0;
545 CommonValue = V;
546 }
547
548 return CommonValue;
549}
550
551/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
552/// try to simplify the comparison by seeing whether comparing with all of the
553/// incoming phi values yields the same result every time. If so returns the
554/// common result, otherwise returns null.
555static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000556 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000557 // Recursion is always used, so bail out at once if we already hit the limit.
558 if (!MaxRecurse--)
559 return 0;
560
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000561 // Make sure the phi is on the LHS.
562 if (!isa<PHINode>(LHS)) {
563 std::swap(LHS, RHS);
564 Pred = CmpInst::getSwappedPredicate(Pred);
565 }
566 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
567 PHINode *PI = cast<PHINode>(LHS);
568
Duncan Sands18450092010-11-16 12:16:38 +0000569 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000570 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000571 return 0;
572
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000573 // Evaluate the BinOp on the incoming phi values.
574 Value *CommonValue = 0;
575 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000576 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000577 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000578 if (Incoming == PI) continue;
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000579 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000580 // If the operation failed to simplify, or simplified to a different value
581 // to previously, then give up.
582 if (!V || (CommonValue && V != CommonValue))
583 return 0;
584 CommonValue = V;
585 }
586
587 return CommonValue;
588}
589
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000590/// SimplifyAddInst - Given operands for an Add, see if we can
591/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000592static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000593 const Query &Q, unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000594 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596 Constant *Ops[] = { CLHS, CRHS };
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000597 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
598 Q.TD, Q.TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000599 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000600
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000601 // Canonicalize the constant to the RHS.
602 std::swap(Op0, Op1);
603 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000604
Duncan Sandsfea3b212010-12-15 14:07:39 +0000605 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000606 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000607 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000608
Duncan Sandsfea3b212010-12-15 14:07:39 +0000609 // X + 0 -> X
610 if (match(Op1, m_Zero()))
611 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000612
Duncan Sandsfea3b212010-12-15 14:07:39 +0000613 // X + (Y - X) -> Y
614 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000615 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000616 Value *Y = 0;
617 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
618 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000619 return Y;
620
621 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000622 if (match(Op0, m_Not(m_Specific(Op1))) ||
623 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000624 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000625
Duncan Sands82fdab32010-12-21 14:00:22 +0000626 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000627 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000628 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000629 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000630
Duncan Sands566edb02010-12-21 08:49:00 +0000631 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands566edb02010-12-21 08:49:00 +0000633 MaxRecurse))
634 return V;
635
Duncan Sands3421d902010-12-21 13:32:22 +0000636 // Mul distributes over Add. Try some generic simplifications based on this.
637 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000638 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000639 return V;
640
Duncan Sands87689cf2010-11-19 09:20:39 +0000641 // Threading Add over selects and phi nodes is pointless, so don't bother.
642 // Threading over the select in "A + select(cond, B, C)" means evaluating
643 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
644 // only if B and C are equal. If B and C are equal then (since we assume
645 // that operands have already been simplified) "select(cond, B, C)" should
646 // have been simplified to the common value of B and C already. Analysing
647 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
648 // for threading over phi nodes.
649
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000650 return 0;
651}
652
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000653Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +0000654 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000655 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000656 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
657 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000658}
659
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000660/// \brief Compute the base pointer and cumulative constant offsets for V.
661///
662/// This strips all constant offsets off of V, leaving it the base pointer, and
663/// accumulates the total constant offset applied in the returned constant. It
664/// returns 0 if V is not a pointer, and returns the constant '0' if there are
665/// no constant offsets applied.
Dan Gohman819f9d62013-01-31 02:45:26 +0000666///
667/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
668/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
669/// folding.
Dan Gohman3e3de562013-01-31 02:50:36 +0000670static Constant *stripAndComputeConstantOffsets(const DataLayout *TD,
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000671 Value *&V) {
Dan Gohmanf2335dc2013-01-31 00:12:20 +0000672 assert(V->getType()->isPointerTy());
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000673
Dan Gohman3e3de562013-01-31 02:50:36 +0000674 // Without DataLayout, just be conservative for now. Theoretically, more could
675 // be done in this case.
676 if (!TD)
677 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
678
679 unsigned IntPtrWidth = TD->getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000680 APInt Offset = APInt::getNullValue(IntPtrWidth);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000681
682 // Even though we don't look through PHI nodes, we could be called on an
683 // instruction in an unreachable block, which may be on a cycle.
684 SmallPtrSet<Value *, 4> Visited;
685 Visited.insert(V);
686 do {
687 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Dan Gohman3e3de562013-01-31 02:50:36 +0000688 if (!GEP->isInBounds() || !GEP->accumulateConstantOffset(*TD, Offset))
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000689 break;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000690 V = GEP->getPointerOperand();
691 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
692 V = cast<Operator>(V)->getOperand(0);
693 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
694 if (GA->mayBeOverridden())
695 break;
696 V = GA->getAliasee();
697 } else {
698 break;
699 }
700 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
701 } while (Visited.insert(V));
702
Dan Gohman3e3de562013-01-31 02:50:36 +0000703 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000704 return ConstantInt::get(IntPtrTy, Offset);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000705}
706
707/// \brief Compute the constant difference between two pointer values.
708/// If the difference is not a constant, returns zero.
Dan Gohman3e3de562013-01-31 02:50:36 +0000709static Constant *computePointerDifference(const DataLayout *TD,
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000710 Value *LHS, Value *RHS) {
711 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000712 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000713
714 // If LHS and RHS are not related via constant offsets to the same base
715 // value, there is nothing we can do here.
716 if (LHS != RHS)
717 return 0;
718
719 // Otherwise, the difference of LHS - RHS can be computed as:
720 // LHS - RHS
721 // = (LHSOffset + Base) - (RHSOffset + Base)
722 // = LHSOffset - RHSOffset
723 return ConstantExpr::getSub(LHSOffset, RHSOffset);
724}
725
Duncan Sandsfea3b212010-12-15 14:07:39 +0000726/// SimplifySubInst - Given operands for a Sub, see if we can
727/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000728static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000729 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000730 if (Constant *CLHS = dyn_cast<Constant>(Op0))
731 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
732 Constant *Ops[] = { CLHS, CRHS };
733 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000734 Ops, Q.TD, Q.TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000735 }
736
737 // X - undef -> undef
738 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000739 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000740 return UndefValue::get(Op0->getType());
741
742 // X - 0 -> X
743 if (match(Op1, m_Zero()))
744 return Op0;
745
746 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000747 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000748 return Constant::getNullValue(Op0->getType());
749
Duncan Sandsfe02c692011-01-18 09:24:58 +0000750 // (X*2) - X -> X
751 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000752 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000753 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
754 match(Op0, m_Shl(m_Specific(Op1), m_One())))
755 return Op1;
756
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000757 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
758 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
759 Value *Y = 0, *Z = Op1;
760 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
761 // See if "V === Y - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000762 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000763 // It does! Now see if "X + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000764 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000765 // It does, we successfully reassociated!
766 ++NumReassoc;
767 return W;
768 }
769 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000770 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000771 // It does! Now see if "Y + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000772 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000773 // It does, we successfully reassociated!
774 ++NumReassoc;
775 return W;
776 }
777 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000778
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000779 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
780 // For example, X - (X + 1) -> -1
781 X = Op0;
782 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
783 // See if "V === X - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000784 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000785 // It does! Now see if "V - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000786 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000787 // It does, we successfully reassociated!
788 ++NumReassoc;
789 return W;
790 }
791 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000792 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000793 // It does! Now see if "V - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000794 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000795 // It does, we successfully reassociated!
796 ++NumReassoc;
797 return W;
798 }
799 }
800
801 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
802 // For example, X - (X - Y) -> Y.
803 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000804 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
805 // See if "V === Z - X" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000806 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000807 // It does! Now see if "V + Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000808 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsc087e202011-01-14 15:26:10 +0000809 // It does, we successfully reassociated!
810 ++NumReassoc;
811 return W;
812 }
813
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000814 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
815 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
816 match(Op1, m_Trunc(m_Value(Y))))
817 if (X->getType() == Y->getType())
818 // See if "V === X - Y" simplifies.
819 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
820 // It does! Now see if "trunc V" simplifies.
821 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
822 // It does, return the simplified "trunc V".
823 return W;
824
825 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman3e3de562013-01-31 02:50:36 +0000826 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000827 match(Op1, m_PtrToInt(m_Value(Y))))
Dan Gohman3e3de562013-01-31 02:50:36 +0000828 if (Constant *Result = computePointerDifference(Q.TD, X, Y))
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000829 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
830
Duncan Sands3421d902010-12-21 13:32:22 +0000831 // Mul distributes over Sub. Try some generic simplifications based on this.
832 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000833 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000834 return V;
835
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000836 // i1 sub -> xor.
837 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000838 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000839 return V;
840
Duncan Sandsfea3b212010-12-15 14:07:39 +0000841 // Threading Sub over selects and phi nodes is pointless, so don't bother.
842 // Threading over the select in "A - select(cond, B, C)" means evaluating
843 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
844 // only if B and C are equal. If B and C are equal then (since we assume
845 // that operands have already been simplified) "select(cond, B, C)" should
846 // have been simplified to the common value of B and C already. Analysing
847 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
848 // for threading over phi nodes.
849
850 return 0;
851}
852
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000853Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +0000854 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000855 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000856 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
857 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000858}
859
Michael Ilseman09ee2502012-12-12 00:27:46 +0000860/// Given operands for an FAdd, see if we can fold the result. If not, this
861/// returns null.
862static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
863 const Query &Q, unsigned MaxRecurse) {
864 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
865 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
866 Constant *Ops[] = { CLHS, CRHS };
867 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
868 Ops, Q.TD, Q.TLI);
869 }
870
871 // Canonicalize the constant to the RHS.
872 std::swap(Op0, Op1);
873 }
874
875 // fadd X, -0 ==> X
876 if (match(Op1, m_NegZero()))
877 return Op0;
878
879 // fadd X, 0 ==> X, when we know X is not -0
880 if (match(Op1, m_Zero()) &&
881 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
882 return Op0;
883
884 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
885 // where nnan and ninf have to occur at least once somewhere in this
886 // expression
887 Value *SubOp = 0;
888 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
889 SubOp = Op1;
890 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
891 SubOp = Op0;
892 if (SubOp) {
893 Instruction *FSub = cast<Instruction>(SubOp);
894 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
895 (FMF.noInfs() || FSub->hasNoInfs()))
896 return Constant::getNullValue(Op0->getType());
897 }
898
899 return 0;
900}
901
902/// Given operands for an FSub, see if we can fold the result. If not, this
903/// returns null.
904static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
905 const Query &Q, unsigned MaxRecurse) {
906 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
907 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
908 Constant *Ops[] = { CLHS, CRHS };
909 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
910 Ops, Q.TD, Q.TLI);
911 }
912 }
913
914 // fsub X, 0 ==> X
915 if (match(Op1, m_Zero()))
916 return Op0;
917
918 // fsub X, -0 ==> X, when we know X is not -0
919 if (match(Op1, m_NegZero()) &&
920 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
921 return Op0;
922
923 // fsub 0, (fsub -0.0, X) ==> X
924 Value *X;
925 if (match(Op0, m_AnyZero())) {
926 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
927 return X;
928 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
929 return X;
930 }
931
932 // fsub nnan ninf x, x ==> 0.0
933 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
934 return Constant::getNullValue(Op0->getType());
935
936 return 0;
937}
938
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000939/// Given the operands for an FMul, see if we can fold the result
940static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
941 FastMathFlags FMF,
942 const Query &Q,
943 unsigned MaxRecurse) {
944 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
945 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
946 Constant *Ops[] = { CLHS, CRHS };
947 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
948 Ops, Q.TD, Q.TLI);
949 }
Michael Ilseman09ee2502012-12-12 00:27:46 +0000950
951 // Canonicalize the constant to the RHS.
952 std::swap(Op0, Op1);
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000953 }
954
Michael Ilseman09ee2502012-12-12 00:27:46 +0000955 // fmul X, 1.0 ==> X
956 if (match(Op1, m_FPOne()))
957 return Op0;
958
959 // fmul nnan nsz X, 0 ==> 0
960 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
961 return Op1;
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000962
963 return 0;
964}
965
Duncan Sands82fdab32010-12-21 14:00:22 +0000966/// SimplifyMulInst - Given operands for a Mul, see if we can
967/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000968static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
969 unsigned MaxRecurse) {
Duncan Sands82fdab32010-12-21 14:00:22 +0000970 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
971 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
972 Constant *Ops[] = { CLHS, CRHS };
973 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000974 Ops, Q.TD, Q.TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000975 }
976
977 // Canonicalize the constant to the RHS.
978 std::swap(Op0, Op1);
979 }
980
981 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000982 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000983 return Constant::getNullValue(Op0->getType());
984
985 // X * 0 -> 0
986 if (match(Op1, m_Zero()))
987 return Op1;
988
989 // X * 1 -> X
990 if (match(Op1, m_One()))
991 return Op0;
992
Duncan Sands1895e982011-01-30 18:03:50 +0000993 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000994 Value *X = 0;
995 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
996 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
997 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000998
Nick Lewycky54138802011-01-29 19:55:23 +0000999 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +00001000 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001001 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +00001002 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +00001003
1004 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001005 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001006 MaxRecurse))
1007 return V;
1008
1009 // Mul distributes over Add. Try some generic simplifications based on this.
1010 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001011 Q, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +00001012 return V;
1013
1014 // If the operation is with the result of a select instruction, check whether
1015 // operating on either branch of the select always yields the same value.
1016 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001017 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001018 MaxRecurse))
1019 return V;
1020
1021 // If the operation is with the result of a phi instruction, check whether
1022 // operating on all incoming values of the phi always yields the same value.
1023 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001024 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001025 MaxRecurse))
1026 return V;
1027
1028 return 0;
1029}
1030
Michael Ilseman09ee2502012-12-12 00:27:46 +00001031Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1032 const DataLayout *TD, const TargetLibraryInfo *TLI,
1033 const DominatorTree *DT) {
1034 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1035}
1036
1037Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1038 const DataLayout *TD, const TargetLibraryInfo *TLI,
1039 const DominatorTree *DT) {
1040 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1041}
1042
Michael Ilsemaneb61c922012-11-27 00:46:26 +00001043Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1044 FastMathFlags FMF,
1045 const DataLayout *TD,
1046 const TargetLibraryInfo *TLI,
1047 const DominatorTree *DT) {
1048 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1049}
1050
Micah Villmow3574eca2012-10-08 16:38:25 +00001051Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001052 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +00001053 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001054 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +00001055}
1056
Duncan Sands593faa52011-01-28 16:51:11 +00001057/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1058/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +00001059static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001060 const Query &Q, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +00001061 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1062 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1063 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001064 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sands593faa52011-01-28 16:51:11 +00001065 }
1066 }
1067
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001068 bool isSigned = Opcode == Instruction::SDiv;
1069
Duncan Sands593faa52011-01-28 16:51:11 +00001070 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001071 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001072 return Op1;
1073
1074 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001075 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001076 return Constant::getNullValue(Op0->getType());
1077
1078 // 0 / X -> 0, we don't need to preserve faults!
1079 if (match(Op0, m_Zero()))
1080 return Op0;
1081
1082 // X / 1 -> X
1083 if (match(Op1, m_One()))
1084 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +00001085
1086 if (Op0->getType()->isIntegerTy(1))
1087 // It can't be division by zero, hence it must be division by one.
1088 return Op0;
1089
1090 // X / X -> 1
1091 if (Op0 == Op1)
1092 return ConstantInt::get(Op0->getType(), 1);
1093
1094 // (X * Y) / Y -> X if the multiplication does not overflow.
1095 Value *X = 0, *Y = 0;
1096 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1097 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +00001098 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +00001099 // If the Mul knows it does not overflow, then we are good to go.
1100 if ((isSigned && Mul->hasNoSignedWrap()) ||
1101 (!isSigned && Mul->hasNoUnsignedWrap()))
1102 return X;
Duncan Sands593faa52011-01-28 16:51:11 +00001103 // If X has the form X = A / Y then X * Y cannot overflow.
1104 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1105 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1106 return X;
1107 }
1108
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001109 // (X rem Y) / Y -> 0
1110 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1111 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1112 return Constant::getNullValue(Op0->getType());
1113
1114 // If the operation is with the result of a select instruction, check whether
1115 // operating on either branch of the select always yields the same value.
1116 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001117 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001118 return V;
1119
1120 // If the operation is with the result of a phi instruction, check whether
1121 // operating on all incoming values of the phi always yields the same value.
1122 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001123 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001124 return V;
1125
Duncan Sands593faa52011-01-28 16:51:11 +00001126 return 0;
1127}
1128
1129/// SimplifySDivInst - Given operands for an SDiv, see if we can
1130/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001131static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1132 unsigned MaxRecurse) {
1133 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001134 return V;
1135
Duncan Sands593faa52011-01-28 16:51:11 +00001136 return 0;
1137}
1138
Micah Villmow3574eca2012-10-08 16:38:25 +00001139Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001140 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001141 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001142 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001143}
1144
1145/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1146/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001147static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1148 unsigned MaxRecurse) {
1149 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001150 return V;
1151
Duncan Sands593faa52011-01-28 16:51:11 +00001152 return 0;
1153}
1154
Micah Villmow3574eca2012-10-08 16:38:25 +00001155Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001156 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001157 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001158 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001159}
1160
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001161static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1162 unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001163 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001164 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001165 return Op0;
1166
1167 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001168 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001169 return Op1;
1170
1171 return 0;
1172}
1173
Micah Villmow3574eca2012-10-08 16:38:25 +00001174Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001175 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001176 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001177 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001178}
1179
Duncan Sandsf24ed772011-05-02 16:27:02 +00001180/// SimplifyRem - Given operands for an SRem or URem, see if we can
1181/// fold the result. If not, this returns null.
1182static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001183 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001184 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1185 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1186 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001187 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001188 }
1189 }
1190
Duncan Sandsf24ed772011-05-02 16:27:02 +00001191 // X % undef -> undef
1192 if (match(Op1, m_Undef()))
1193 return Op1;
1194
1195 // undef % X -> 0
1196 if (match(Op0, m_Undef()))
1197 return Constant::getNullValue(Op0->getType());
1198
1199 // 0 % X -> 0, we don't need to preserve faults!
1200 if (match(Op0, m_Zero()))
1201 return Op0;
1202
1203 // X % 0 -> undef, we don't need to preserve faults!
1204 if (match(Op1, m_Zero()))
1205 return UndefValue::get(Op0->getType());
1206
1207 // X % 1 -> 0
1208 if (match(Op1, m_One()))
1209 return Constant::getNullValue(Op0->getType());
1210
1211 if (Op0->getType()->isIntegerTy(1))
1212 // It can't be remainder by zero, hence it must be remainder by one.
1213 return Constant::getNullValue(Op0->getType());
1214
1215 // X % X -> 0
1216 if (Op0 == Op1)
1217 return Constant::getNullValue(Op0->getType());
1218
1219 // If the operation is with the result of a select instruction, check whether
1220 // operating on either branch of the select always yields the same value.
1221 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001222 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001223 return V;
1224
1225 // If the operation is with the result of a phi instruction, check whether
1226 // operating on all incoming values of the phi always yields the same value.
1227 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001228 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001229 return V;
1230
1231 return 0;
1232}
1233
1234/// SimplifySRemInst - Given operands for an SRem, see if we can
1235/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001236static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1237 unsigned MaxRecurse) {
1238 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001239 return V;
1240
1241 return 0;
1242}
1243
Micah Villmow3574eca2012-10-08 16:38:25 +00001244Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001245 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001246 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001247 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001248}
1249
1250/// SimplifyURemInst - Given operands for a URem, see if we can
1251/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001252static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001253 unsigned MaxRecurse) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001254 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001255 return V;
1256
1257 return 0;
1258}
1259
Micah Villmow3574eca2012-10-08 16:38:25 +00001260Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001261 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001262 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001263 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001264}
1265
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001266static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +00001267 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001268 // undef % X -> undef (the undef could be a snan).
1269 if (match(Op0, m_Undef()))
1270 return Op0;
1271
1272 // X % undef -> undef
1273 if (match(Op1, m_Undef()))
1274 return Op1;
1275
1276 return 0;
1277}
1278
Micah Villmow3574eca2012-10-08 16:38:25 +00001279Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001280 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001281 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001282 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001283}
1284
Duncan Sandscf80bc12011-01-14 14:44:12 +00001285/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001286/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001287static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001288 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001289 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1290 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1291 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001292 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001293 }
1294 }
1295
Duncan Sandscf80bc12011-01-14 14:44:12 +00001296 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001297 if (match(Op0, m_Zero()))
1298 return Op0;
1299
Duncan Sandscf80bc12011-01-14 14:44:12 +00001300 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001301 if (match(Op1, m_Zero()))
1302 return Op0;
1303
Duncan Sandscf80bc12011-01-14 14:44:12 +00001304 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001305 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001306 return Op1;
1307
1308 // Shifting by the bitwidth or more is undefined.
1309 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1310 if (CI->getValue().getLimitedValue() >=
1311 Op0->getType()->getScalarSizeInBits())
1312 return UndefValue::get(Op0->getType());
1313
Duncan Sandscf80bc12011-01-14 14:44:12 +00001314 // If the operation is with the result of a select instruction, check whether
1315 // operating on either branch of the select always yields the same value.
1316 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001317 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001318 return V;
1319
1320 // If the operation is with the result of a phi instruction, check whether
1321 // operating on all incoming values of the phi always yields the same value.
1322 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001323 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001324 return V;
1325
1326 return 0;
1327}
1328
1329/// SimplifyShlInst - Given operands for an Shl, see if we can
1330/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001331static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001332 const Query &Q, unsigned MaxRecurse) {
1333 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001334 return V;
1335
1336 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001337 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001338 return Constant::getNullValue(Op0->getType());
1339
Chris Lattner81a0dc92011-02-09 17:15:04 +00001340 // (X >> A) << A -> X
1341 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001342 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001343 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001344 return 0;
1345}
1346
Chris Lattner81a0dc92011-02-09 17:15:04 +00001347Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +00001348 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00001349 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001350 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1351 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001352}
1353
1354/// SimplifyLShrInst - Given operands for an LShr, see if we can
1355/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001356static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001357 const Query &Q, unsigned MaxRecurse) {
1358 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001359 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001360
1361 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001362 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001363 return Constant::getNullValue(Op0->getType());
1364
Chris Lattner81a0dc92011-02-09 17:15:04 +00001365 // (X << A) >> A -> X
1366 Value *X;
1367 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1368 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1369 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001370
Duncan Sandsc43cee32011-01-14 00:37:45 +00001371 return 0;
1372}
1373
Chris Lattner81a0dc92011-02-09 17:15:04 +00001374Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001375 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001376 const TargetLibraryInfo *TLI,
1377 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001378 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1379 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001380}
1381
1382/// SimplifyAShrInst - Given operands for an AShr, see if we can
1383/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001384static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001385 const Query &Q, unsigned MaxRecurse) {
1386 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001387 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001388
1389 // all ones >>a X -> all ones
1390 if (match(Op0, m_AllOnes()))
1391 return Op0;
1392
1393 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001394 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001395 return Constant::getAllOnesValue(Op0->getType());
1396
Chris Lattner81a0dc92011-02-09 17:15:04 +00001397 // (X << A) >> A -> X
1398 Value *X;
1399 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1400 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1401 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001402
Duncan Sandsc43cee32011-01-14 00:37:45 +00001403 return 0;
1404}
1405
Chris Lattner81a0dc92011-02-09 17:15:04 +00001406Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001407 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001408 const TargetLibraryInfo *TLI,
1409 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001410 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1411 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001412}
1413
Chris Lattnerd06094f2009-11-10 00:55:12 +00001414/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001415/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001416static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001417 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001418 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1419 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1420 Constant *Ops[] = { CLHS, CRHS };
1421 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001422 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001423 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001424
Chris Lattnerd06094f2009-11-10 00:55:12 +00001425 // Canonicalize the constant to the RHS.
1426 std::swap(Op0, Op1);
1427 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001428
Chris Lattnerd06094f2009-11-10 00:55:12 +00001429 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001430 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001431 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001432
Chris Lattnerd06094f2009-11-10 00:55:12 +00001433 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001434 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001435 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001436
Duncan Sands2b749872010-11-17 18:52:15 +00001437 // X & 0 = 0
1438 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001439 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001440
Duncan Sands2b749872010-11-17 18:52:15 +00001441 // X & -1 = X
1442 if (match(Op1, m_AllOnes()))
1443 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001444
Chris Lattnerd06094f2009-11-10 00:55:12 +00001445 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001446 if (match(Op0, m_Not(m_Specific(Op1))) ||
1447 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001448 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001449
Chris Lattnerd06094f2009-11-10 00:55:12 +00001450 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001451 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001452 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001453 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001454 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001455
Chris Lattnerd06094f2009-11-10 00:55:12 +00001456 // A & (A | ?) = A
1457 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001458 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001459 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001460
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001461 // A & (-A) = A if A is a power of two or zero.
1462 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1463 match(Op1, m_Neg(m_Specific(Op0)))) {
Rafael Espindoladbaa2372012-12-13 03:37:24 +00001464 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001465 return Op0;
Rafael Espindoladbaa2372012-12-13 03:37:24 +00001466 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001467 return Op1;
1468 }
1469
Duncan Sands566edb02010-12-21 08:49:00 +00001470 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001471 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1472 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001473 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001474
Duncan Sands3421d902010-12-21 13:32:22 +00001475 // And distributes over Or. Try some generic simplifications based on this.
1476 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001477 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001478 return V;
1479
1480 // And distributes over Xor. Try some generic simplifications based on this.
1481 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001482 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001483 return V;
1484
1485 // Or distributes over And. Try some generic simplifications based on this.
1486 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001487 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001488 return V;
1489
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001490 // If the operation is with the result of a select instruction, check whether
1491 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001492 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001493 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1494 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001495 return V;
1496
1497 // If the operation is with the result of a phi instruction, check whether
1498 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001499 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001500 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001501 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001502 return V;
1503
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001504 return 0;
1505}
1506
Micah Villmow3574eca2012-10-08 16:38:25 +00001507Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001508 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001509 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001510 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001511}
1512
Chris Lattnerd06094f2009-11-10 00:55:12 +00001513/// SimplifyOrInst - Given operands for an Or, see if we can
1514/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001515static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1516 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001517 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1518 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1519 Constant *Ops[] = { CLHS, CRHS };
1520 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001521 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001522 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001523
Chris Lattnerd06094f2009-11-10 00:55:12 +00001524 // Canonicalize the constant to the RHS.
1525 std::swap(Op0, Op1);
1526 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001527
Chris Lattnerd06094f2009-11-10 00:55:12 +00001528 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001529 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001530 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001531
Chris Lattnerd06094f2009-11-10 00:55:12 +00001532 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001533 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001534 return Op0;
1535
Duncan Sands2b749872010-11-17 18:52:15 +00001536 // X | 0 = X
1537 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001538 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001539
Duncan Sands2b749872010-11-17 18:52:15 +00001540 // X | -1 = -1
1541 if (match(Op1, m_AllOnes()))
1542 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001543
Chris Lattnerd06094f2009-11-10 00:55:12 +00001544 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001545 if (match(Op0, m_Not(m_Specific(Op1))) ||
1546 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001547 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001548
Chris Lattnerd06094f2009-11-10 00:55:12 +00001549 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001550 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001551 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001552 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001553 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001554
Chris Lattnerd06094f2009-11-10 00:55:12 +00001555 // A | (A & ?) = A
1556 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001557 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001558 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001559
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001560 // ~(A & ?) | A = -1
1561 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1562 (A == Op1 || B == Op1))
1563 return Constant::getAllOnesValue(Op1->getType());
1564
1565 // A | ~(A & ?) = -1
1566 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1567 (A == Op0 || B == Op0))
1568 return Constant::getAllOnesValue(Op0->getType());
1569
Duncan Sands566edb02010-12-21 08:49:00 +00001570 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001571 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1572 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001573 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001574
Duncan Sands3421d902010-12-21 13:32:22 +00001575 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001576 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1577 MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001578 return V;
1579
1580 // And distributes over Or. Try some generic simplifications based on this.
1581 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001582 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001583 return V;
1584
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001585 // If the operation is with the result of a select instruction, check whether
1586 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001587 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001588 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001589 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001590 return V;
1591
1592 // If the operation is with the result of a phi instruction, check whether
1593 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001594 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001595 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001596 return V;
1597
Chris Lattnerd06094f2009-11-10 00:55:12 +00001598 return 0;
1599}
1600
Micah Villmow3574eca2012-10-08 16:38:25 +00001601Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001602 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001603 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001604 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001605}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001606
Duncan Sands2b749872010-11-17 18:52:15 +00001607/// SimplifyXorInst - Given operands for a Xor, see if we can
1608/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001609static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1610 unsigned MaxRecurse) {
Duncan Sands2b749872010-11-17 18:52:15 +00001611 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1612 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1613 Constant *Ops[] = { CLHS, CRHS };
1614 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001615 Ops, Q.TD, Q.TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001616 }
1617
1618 // Canonicalize the constant to the RHS.
1619 std::swap(Op0, Op1);
1620 }
1621
1622 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001623 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001624 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001625
1626 // A ^ 0 = A
1627 if (match(Op1, m_Zero()))
1628 return Op0;
1629
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001630 // A ^ A = 0
1631 if (Op0 == Op1)
1632 return Constant::getNullValue(Op0->getType());
1633
Duncan Sands2b749872010-11-17 18:52:15 +00001634 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001635 if (match(Op0, m_Not(m_Specific(Op1))) ||
1636 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001637 return Constant::getAllOnesValue(Op0->getType());
1638
Duncan Sands566edb02010-12-21 08:49:00 +00001639 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001640 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1641 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001642 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001643
Duncan Sands3421d902010-12-21 13:32:22 +00001644 // And distributes over Xor. Try some generic simplifications based on this.
1645 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001646 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001647 return V;
1648
Duncan Sands87689cf2010-11-19 09:20:39 +00001649 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1650 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1651 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1652 // only if B and C are equal. If B and C are equal then (since we assume
1653 // that operands have already been simplified) "select(cond, B, C)" should
1654 // have been simplified to the common value of B and C already. Analysing
1655 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1656 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001657
1658 return 0;
1659}
1660
Micah Villmow3574eca2012-10-08 16:38:25 +00001661Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001662 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001663 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001664 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001665}
1666
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001667static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001668 return CmpInst::makeCmpResultType(Op->getType());
1669}
1670
Duncan Sandse864b5b2011-05-07 16:56:49 +00001671/// ExtractEquivalentCondition - Rummage around inside V looking for something
1672/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1673/// otherwise return null. Helper function for analyzing max/min idioms.
1674static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1675 Value *LHS, Value *RHS) {
1676 SelectInst *SI = dyn_cast<SelectInst>(V);
1677 if (!SI)
1678 return 0;
1679 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1680 if (!Cmp)
1681 return 0;
1682 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1683 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1684 return Cmp;
1685 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1686 LHS == CmpRHS && RHS == CmpLHS)
1687 return Cmp;
1688 return 0;
1689}
1690
Dan Gohman3e3de562013-01-31 02:50:36 +00001691static Constant *computePointerICmp(const DataLayout *TD,
Chandler Carruth58725a62012-03-25 21:28:14 +00001692 CmpInst::Predicate Pred,
1693 Value *LHS, Value *RHS) {
1694 // We can only fold certain predicates on pointer comparisons.
1695 switch (Pred) {
1696 default:
1697 return 0;
1698
1699 // Equality comaprisons are easy to fold.
1700 case CmpInst::ICMP_EQ:
1701 case CmpInst::ICMP_NE:
1702 break;
1703
1704 // We can only handle unsigned relational comparisons because 'inbounds' on
1705 // a GEP only protects against unsigned wrapping.
1706 case CmpInst::ICMP_UGT:
1707 case CmpInst::ICMP_UGE:
1708 case CmpInst::ICMP_ULT:
1709 case CmpInst::ICMP_ULE:
1710 // However, we have to switch them to their signed variants to handle
1711 // negative indices from the base pointer.
1712 Pred = ICmpInst::getSignedPredicate(Pred);
1713 break;
1714 }
1715
1716 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
Chandler Carruth58725a62012-03-25 21:28:14 +00001717 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
Chandler Carruth58725a62012-03-25 21:28:14 +00001718
1719 // If LHS and RHS are not related via constant offsets to the same base
1720 // value, there is nothing we can do here.
1721 if (LHS != RHS)
1722 return 0;
1723
1724 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1725}
Chris Lattner009e2652012-02-24 19:01:58 +00001726
Chris Lattner9dbb4292009-11-09 23:28:39 +00001727/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1728/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001729static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001730 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001731 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001732 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001733
Chris Lattnerd06094f2009-11-10 00:55:12 +00001734 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001735 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001736 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001737
1738 // If we have a constant, make sure it is on the RHS.
1739 std::swap(LHS, RHS);
1740 Pred = CmpInst::getSwappedPredicate(Pred);
1741 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001742
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001743 Type *ITy = GetCompareTy(LHS); // The return type.
1744 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001745
Chris Lattner210c5d42009-11-09 23:55:12 +00001746 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001747 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1748 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001749 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001750 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001751
Duncan Sands6dc91252011-01-13 08:56:29 +00001752 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001753 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001754 switch (Pred) {
1755 default: break;
1756 case ICmpInst::ICMP_EQ:
1757 // X == 1 -> X
1758 if (match(RHS, m_One()))
1759 return LHS;
1760 break;
1761 case ICmpInst::ICMP_NE:
1762 // X != 0 -> X
1763 if (match(RHS, m_Zero()))
1764 return LHS;
1765 break;
1766 case ICmpInst::ICMP_UGT:
1767 // X >u 0 -> X
1768 if (match(RHS, m_Zero()))
1769 return LHS;
1770 break;
1771 case ICmpInst::ICMP_UGE:
1772 // X >=u 1 -> X
1773 if (match(RHS, m_One()))
1774 return LHS;
1775 break;
1776 case ICmpInst::ICMP_SLT:
1777 // X <s 0 -> X
1778 if (match(RHS, m_Zero()))
1779 return LHS;
1780 break;
1781 case ICmpInst::ICMP_SLE:
1782 // X <=s -1 -> X
1783 if (match(RHS, m_One()))
1784 return LHS;
1785 break;
1786 }
1787 }
1788
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001789 // icmp <object*>, <object*/null> - Different identified objects have
1790 // different addresses (unless null), and what's more the address of an
1791 // identified local is never equal to another argument (again, barring null).
1792 // Note that generalizing to the case where LHS is a global variable address
1793 // or null is pointless, since if both LHS and RHS are constants then we
1794 // already constant folded the compare, and if only one of them is then we
1795 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001796 Value *LHSPtr = LHS->stripPointerCasts();
1797 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001798 if (LHSPtr == RHSPtr)
1799 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001800
Chris Lattnerb053fc12012-02-20 00:42:49 +00001801 // Be more aggressive about stripping pointer adjustments when checking a
1802 // comparison of an alloca address to another object. We can rip off all
1803 // inbounds GEP operations, even if they are variable.
Chandler Carruth84dfc322012-03-10 08:39:09 +00001804 LHSPtr = LHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001805 if (llvm::isIdentifiedObject(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001806 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001807 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1808 // If both sides are different identified objects, they aren't equal
1809 // unless they're null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001810 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001811 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001812 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001813
1814 // A local identified object (alloca or noalias call) can't equal any
Chandler Carruth961e1ac2012-08-07 10:59:59 +00001815 // incoming argument, unless they're both null or they belong to
1816 // different functions. The latter happens during inlining.
1817 if (Instruction *LHSInst = dyn_cast<Instruction>(LHSPtr))
1818 if (Argument *RHSArg = dyn_cast<Argument>(RHSPtr))
1819 if (LHSInst->getParent()->getParent() == RHSArg->getParent() &&
1820 Pred == CmpInst::ICMP_EQ)
1821 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001822 }
1823
1824 // Assume that the constant null is on the right.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001825 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001826 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001827 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001828 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001829 return ConstantInt::get(ITy, true);
1830 }
Chris Lattnerb053fc12012-02-20 00:42:49 +00001831 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001832
1833 // If we are comparing with zero then try hard since this is a common case.
1834 if (match(RHS, m_Zero())) {
1835 bool LHSKnownNonNegative, LHSKnownNegative;
1836 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001837 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001838 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001839 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001840 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001841 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001842 case ICmpInst::ICMP_EQ:
1843 case ICmpInst::ICMP_ULE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001844 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001845 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001846 break;
1847 case ICmpInst::ICMP_NE:
1848 case ICmpInst::ICMP_UGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001849 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001850 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001851 break;
1852 case ICmpInst::ICMP_SLT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001853 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001854 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001855 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001856 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001857 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001858 break;
1859 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001860 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001861 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001862 return getTrue(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001863 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001864 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001865 break;
1866 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001867 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001868 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001869 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001870 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001871 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001872 break;
1873 case ICmpInst::ICMP_SGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001874 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001875 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001876 return getFalse(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001877 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001878 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001879 break;
1880 }
1881 }
1882
1883 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001884 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001885 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1886 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1887 if (RHS_CR.isEmptySet())
1888 return ConstantInt::getFalse(CI->getContext());
1889 if (RHS_CR.isFullSet())
1890 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001891
Nick Lewycky3a73e342011-03-04 07:00:57 +00001892 // Many binary operators with constant RHS have easy to compute constant
1893 // range. Use them to check whether the comparison is a tautology.
1894 uint32_t Width = CI->getBitWidth();
1895 APInt Lower = APInt(Width, 0);
1896 APInt Upper = APInt(Width, 0);
1897 ConstantInt *CI2;
1898 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1899 // 'urem x, CI2' produces [0, CI2).
1900 Upper = CI2->getValue();
1901 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1902 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1903 Upper = CI2->getValue().abs();
1904 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001905 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1906 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001907 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001908 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1909 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1910 APInt NegOne = APInt::getAllOnesValue(Width);
1911 if (!CI2->isZero())
1912 Upper = NegOne.udiv(CI2->getValue()) + 1;
1913 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1914 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1915 APInt IntMin = APInt::getSignedMinValue(Width);
1916 APInt IntMax = APInt::getSignedMaxValue(Width);
1917 APInt Val = CI2->getValue().abs();
1918 if (!Val.isMinValue()) {
1919 Lower = IntMin.sdiv(Val);
1920 Upper = IntMax.sdiv(Val) + 1;
1921 }
1922 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1923 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1924 APInt NegOne = APInt::getAllOnesValue(Width);
1925 if (CI2->getValue().ult(Width))
1926 Upper = NegOne.lshr(CI2->getValue()) + 1;
1927 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1928 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1929 APInt IntMin = APInt::getSignedMinValue(Width);
1930 APInt IntMax = APInt::getSignedMaxValue(Width);
1931 if (CI2->getValue().ult(Width)) {
1932 Lower = IntMin.ashr(CI2->getValue());
1933 Upper = IntMax.ashr(CI2->getValue()) + 1;
1934 }
1935 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1936 // 'or x, CI2' produces [CI2, UINT_MAX].
1937 Lower = CI2->getValue();
1938 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1939 // 'and x, CI2' produces [0, CI2].
1940 Upper = CI2->getValue() + 1;
1941 }
1942 if (Lower != Upper) {
1943 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1944 if (RHS_CR.contains(LHS_CR))
1945 return ConstantInt::getTrue(RHS->getContext());
1946 if (RHS_CR.inverse().contains(LHS_CR))
1947 return ConstantInt::getFalse(RHS->getContext());
1948 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001949 }
1950
Duncan Sands9d32f602011-01-20 13:21:55 +00001951 // Compare of cast, for example (zext X) != 0 -> X != 0
1952 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1953 Instruction *LI = cast<CastInst>(LHS);
1954 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001955 Type *SrcTy = SrcOp->getType();
1956 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001957
1958 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1959 // if the integer type is the same size as the pointer type.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001960 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001961 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands9d32f602011-01-20 13:21:55 +00001962 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1963 // Transfer the cast to the constant.
1964 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1965 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001966 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001967 return V;
1968 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1969 if (RI->getOperand(0)->getType() == SrcTy)
1970 // Compare without the cast.
1971 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001972 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001973 return V;
1974 }
1975 }
1976
1977 if (isa<ZExtInst>(LHS)) {
1978 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1979 // same type.
1980 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1981 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1982 // Compare X and Y. Note that signed predicates become unsigned.
1983 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001984 SrcOp, RI->getOperand(0), Q,
Duncan Sands9d32f602011-01-20 13:21:55 +00001985 MaxRecurse-1))
1986 return V;
1987 }
1988 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1989 // too. If not, then try to deduce the result of the comparison.
1990 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1991 // Compute the constant that would happen if we truncated to SrcTy then
1992 // reextended to DstTy.
1993 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1994 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1995
1996 // If the re-extended constant didn't change then this is effectively
1997 // also a case of comparing two zero-extended values.
1998 if (RExt == CI && MaxRecurse)
1999 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002000 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002001 return V;
2002
2003 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2004 // there. Use this to work out the result of the comparison.
2005 if (RExt != CI) {
2006 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00002007 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00002008 // LHS <u RHS.
2009 case ICmpInst::ICMP_EQ:
2010 case ICmpInst::ICMP_UGT:
2011 case ICmpInst::ICMP_UGE:
2012 return ConstantInt::getFalse(CI->getContext());
2013
2014 case ICmpInst::ICMP_NE:
2015 case ICmpInst::ICMP_ULT:
2016 case ICmpInst::ICMP_ULE:
2017 return ConstantInt::getTrue(CI->getContext());
2018
2019 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2020 // is non-negative then LHS <s RHS.
2021 case ICmpInst::ICMP_SGT:
2022 case ICmpInst::ICMP_SGE:
2023 return CI->getValue().isNegative() ?
2024 ConstantInt::getTrue(CI->getContext()) :
2025 ConstantInt::getFalse(CI->getContext());
2026
2027 case ICmpInst::ICMP_SLT:
2028 case ICmpInst::ICMP_SLE:
2029 return CI->getValue().isNegative() ?
2030 ConstantInt::getFalse(CI->getContext()) :
2031 ConstantInt::getTrue(CI->getContext());
2032 }
2033 }
2034 }
2035 }
2036
2037 if (isa<SExtInst>(LHS)) {
2038 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2039 // same type.
2040 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2041 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2042 // Compare X and Y. Note that the predicate does not change.
2043 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002044 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002045 return V;
2046 }
2047 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2048 // too. If not, then try to deduce the result of the comparison.
2049 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2050 // Compute the constant that would happen if we truncated to SrcTy then
2051 // reextended to DstTy.
2052 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2053 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2054
2055 // If the re-extended constant didn't change then this is effectively
2056 // also a case of comparing two sign-extended values.
2057 if (RExt == CI && MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002058 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002059 return V;
2060
2061 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2062 // bits there. Use this to work out the result of the comparison.
2063 if (RExt != CI) {
2064 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00002065 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00002066 case ICmpInst::ICMP_EQ:
2067 return ConstantInt::getFalse(CI->getContext());
2068 case ICmpInst::ICMP_NE:
2069 return ConstantInt::getTrue(CI->getContext());
2070
2071 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2072 // LHS >s RHS.
2073 case ICmpInst::ICMP_SGT:
2074 case ICmpInst::ICMP_SGE:
2075 return CI->getValue().isNegative() ?
2076 ConstantInt::getTrue(CI->getContext()) :
2077 ConstantInt::getFalse(CI->getContext());
2078 case ICmpInst::ICMP_SLT:
2079 case ICmpInst::ICMP_SLE:
2080 return CI->getValue().isNegative() ?
2081 ConstantInt::getFalse(CI->getContext()) :
2082 ConstantInt::getTrue(CI->getContext());
2083
2084 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2085 // LHS >u RHS.
2086 case ICmpInst::ICMP_UGT:
2087 case ICmpInst::ICMP_UGE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002088 // Comparison is true iff the LHS <s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002089 if (MaxRecurse)
2090 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2091 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002092 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002093 return V;
2094 break;
2095 case ICmpInst::ICMP_ULT:
2096 case ICmpInst::ICMP_ULE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002097 // Comparison is true iff the LHS >=s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002098 if (MaxRecurse)
2099 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2100 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002101 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002102 return V;
2103 break;
2104 }
2105 }
2106 }
2107 }
2108 }
2109
Duncan Sands52fb8462011-02-13 17:15:40 +00002110 // Special logic for binary operators.
2111 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2112 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2113 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00002114 // Analyze the case when either LHS or RHS is an add instruction.
2115 Value *A = 0, *B = 0, *C = 0, *D = 0;
2116 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2117 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2118 if (LBO && LBO->getOpcode() == Instruction::Add) {
2119 A = LBO->getOperand(0); B = LBO->getOperand(1);
2120 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2121 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2122 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2123 }
2124 if (RBO && RBO->getOpcode() == Instruction::Add) {
2125 C = RBO->getOperand(0); D = RBO->getOperand(1);
2126 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2127 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2128 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2129 }
2130
2131 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2132 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2133 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2134 Constant::getNullValue(RHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002135 Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002136 return V;
2137
2138 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2139 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2140 if (Value *V = SimplifyICmpInst(Pred,
2141 Constant::getNullValue(LHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002142 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002143 return V;
2144
2145 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2146 if (A && C && (A == C || A == D || B == C || B == D) &&
2147 NoLHSWrapProblem && NoRHSWrapProblem) {
2148 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002149 Value *Y, *Z;
2150 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002151 // C + B == C + D -> B == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002152 Y = B;
2153 Z = D;
2154 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002155 // D + B == C + D -> B == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002156 Y = B;
2157 Z = C;
2158 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002159 // A + C == C + D -> A == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002160 Y = A;
2161 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002162 } else {
2163 assert(B == D);
2164 // A + D == C + D -> A == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002165 Y = A;
2166 Z = C;
2167 }
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002168 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002169 return V;
2170 }
2171 }
2172
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002173 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002174 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002175 switch (Pred) {
2176 default:
2177 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002178 case ICmpInst::ICMP_SGT:
2179 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002180 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002181 if (!KnownNonNegative)
2182 break;
2183 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002184 case ICmpInst::ICMP_EQ:
2185 case ICmpInst::ICMP_UGT:
2186 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002187 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002188 case ICmpInst::ICMP_SLT:
2189 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002190 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002191 if (!KnownNonNegative)
2192 break;
2193 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002194 case ICmpInst::ICMP_NE:
2195 case ICmpInst::ICMP_ULT:
2196 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002197 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002198 }
2199 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002200 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2201 bool KnownNonNegative, KnownNegative;
2202 switch (Pred) {
2203 default:
2204 break;
2205 case ICmpInst::ICMP_SGT:
2206 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002207 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002208 if (!KnownNonNegative)
2209 break;
2210 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002211 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002212 case ICmpInst::ICMP_UGT:
2213 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002214 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002215 case ICmpInst::ICMP_SLT:
2216 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002217 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002218 if (!KnownNonNegative)
2219 break;
2220 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002221 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002222 case ICmpInst::ICMP_ULT:
2223 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002224 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002225 }
2226 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002227
Duncan Sandsc65c7472011-10-28 18:17:44 +00002228 // x udiv y <=u x.
2229 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2230 // icmp pred (X /u Y), X
2231 if (Pred == ICmpInst::ICMP_UGT)
2232 return getFalse(ITy);
2233 if (Pred == ICmpInst::ICMP_ULE)
2234 return getTrue(ITy);
2235 }
2236
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002237 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2238 LBO->getOperand(1) == RBO->getOperand(1)) {
2239 switch (LBO->getOpcode()) {
2240 default: break;
2241 case Instruction::UDiv:
2242 case Instruction::LShr:
2243 if (ICmpInst::isSigned(Pred))
2244 break;
2245 // fall-through
2246 case Instruction::SDiv:
2247 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002248 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002249 break;
2250 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002251 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002252 return V;
2253 break;
2254 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002255 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002256 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2257 if (!NUW && !NSW)
2258 break;
2259 if (!NSW && ICmpInst::isSigned(Pred))
2260 break;
2261 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002262 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002263 return V;
2264 break;
2265 }
2266 }
2267 }
2268
Duncan Sandsad206812011-05-03 19:53:10 +00002269 // Simplify comparisons involving max/min.
2270 Value *A, *B;
2271 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002272 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sandsad206812011-05-03 19:53:10 +00002273
Duncan Sands8140ad32011-05-04 16:05:05 +00002274 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002275 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2276 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002277 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002278 // We analyze this as smax(A, B) pred A.
2279 P = Pred;
2280 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2281 (A == LHS || B == LHS)) {
2282 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002283 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002284 // We analyze this as smax(A, B) swapped-pred A.
2285 P = CmpInst::getSwappedPredicate(Pred);
2286 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2287 (A == RHS || B == RHS)) {
2288 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002289 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sandsad206812011-05-03 19:53:10 +00002290 // We analyze this as smax(-A, -B) swapped-pred -A.
2291 // Note that we do not need to actually form -A or -B thanks to EqP.
2292 P = CmpInst::getSwappedPredicate(Pred);
2293 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2294 (A == LHS || B == LHS)) {
2295 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002296 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sandsad206812011-05-03 19:53:10 +00002297 // We analyze this as smax(-A, -B) pred -A.
2298 // Note that we do not need to actually form -A or -B thanks to EqP.
2299 P = Pred;
2300 }
2301 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2302 // Cases correspond to "max(A, B) p A".
2303 switch (P) {
2304 default:
2305 break;
2306 case CmpInst::ICMP_EQ:
2307 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002308 // Equivalent to "A EqP B". This may be the same as the condition tested
2309 // in the max/min; if so, we can just return that.
2310 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2311 return V;
2312 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2313 return V;
2314 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002315 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002316 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002317 return V;
2318 break;
2319 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002320 case CmpInst::ICMP_SGT: {
2321 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2322 // Equivalent to "A InvEqP B". This may be the same as the condition
2323 // tested in the max/min; if so, we can just return that.
2324 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2325 return V;
2326 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2327 return V;
2328 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002329 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002330 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002331 return V;
2332 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002333 }
Duncan Sandsad206812011-05-03 19:53:10 +00002334 case CmpInst::ICMP_SGE:
2335 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002336 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002337 case CmpInst::ICMP_SLT:
2338 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002339 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002340 }
2341 }
2342
Duncan Sands8140ad32011-05-04 16:05:05 +00002343 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002344 P = CmpInst::BAD_ICMP_PREDICATE;
2345 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2346 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002347 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002348 // We analyze this as umax(A, B) pred A.
2349 P = Pred;
2350 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2351 (A == LHS || B == LHS)) {
2352 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002353 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002354 // We analyze this as umax(A, B) swapped-pred A.
2355 P = CmpInst::getSwappedPredicate(Pred);
2356 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2357 (A == RHS || B == RHS)) {
2358 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002359 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sandsad206812011-05-03 19:53:10 +00002360 // We analyze this as umax(-A, -B) swapped-pred -A.
2361 // Note that we do not need to actually form -A or -B thanks to EqP.
2362 P = CmpInst::getSwappedPredicate(Pred);
2363 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2364 (A == LHS || B == LHS)) {
2365 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002366 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sandsad206812011-05-03 19:53:10 +00002367 // We analyze this as umax(-A, -B) pred -A.
2368 // Note that we do not need to actually form -A or -B thanks to EqP.
2369 P = Pred;
2370 }
2371 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2372 // Cases correspond to "max(A, B) p A".
2373 switch (P) {
2374 default:
2375 break;
2376 case CmpInst::ICMP_EQ:
2377 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002378 // Equivalent to "A EqP B". This may be the same as the condition tested
2379 // in the max/min; if so, we can just return that.
2380 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2381 return V;
2382 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2383 return V;
2384 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002385 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002386 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002387 return V;
2388 break;
2389 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002390 case CmpInst::ICMP_UGT: {
2391 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2392 // Equivalent to "A InvEqP B". This may be the same as the condition
2393 // tested in the max/min; if so, we can just return that.
2394 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2395 return V;
2396 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2397 return V;
2398 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002399 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002400 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002401 return V;
2402 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002403 }
Duncan Sandsad206812011-05-03 19:53:10 +00002404 case CmpInst::ICMP_UGE:
2405 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002406 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002407 case CmpInst::ICMP_ULT:
2408 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002409 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002410 }
2411 }
2412
Duncan Sands8140ad32011-05-04 16:05:05 +00002413 // Variants on "max(x,y) >= min(x,z)".
2414 Value *C, *D;
2415 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2416 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2417 (A == C || A == D || B == C || B == D)) {
2418 // max(x, ?) pred min(x, ?).
2419 if (Pred == CmpInst::ICMP_SGE)
2420 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002421 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002422 if (Pred == CmpInst::ICMP_SLT)
2423 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002424 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002425 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2426 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2427 (A == C || A == D || B == C || B == D)) {
2428 // min(x, ?) pred max(x, ?).
2429 if (Pred == CmpInst::ICMP_SLE)
2430 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002431 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002432 if (Pred == CmpInst::ICMP_SGT)
2433 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002434 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002435 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2436 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2437 (A == C || A == D || B == C || B == D)) {
2438 // max(x, ?) pred min(x, ?).
2439 if (Pred == CmpInst::ICMP_UGE)
2440 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002441 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002442 if (Pred == CmpInst::ICMP_ULT)
2443 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002444 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002445 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2446 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2447 (A == C || A == D || B == C || B == D)) {
2448 // min(x, ?) pred max(x, ?).
2449 if (Pred == CmpInst::ICMP_ULE)
2450 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002451 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002452 if (Pred == CmpInst::ICMP_UGT)
2453 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002454 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002455 }
2456
Chandler Carruth58725a62012-03-25 21:28:14 +00002457 // Simplify comparisons of related pointers using a powerful, recursive
2458 // GEP-walk when we have target data available..
Dan Gohman3e3de562013-01-31 02:50:36 +00002459 if (LHS->getType()->isPointerTy())
2460 if (Constant *C = computePointerICmp(Q.TD, Pred, LHS, RHS))
Chandler Carruth58725a62012-03-25 21:28:14 +00002461 return C;
2462
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002463 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2464 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2465 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2466 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2467 (ICmpInst::isEquality(Pred) ||
2468 (GLHS->isInBounds() && GRHS->isInBounds() &&
2469 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2470 // The bases are equal and the indices are constant. Build a constant
2471 // expression GEP with the same indices and a null base pointer to see
2472 // what constant folding can make out of it.
2473 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2474 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2475 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2476
2477 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2478 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2479 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2480 }
2481 }
2482 }
2483
Duncan Sands1ac7c992010-11-07 16:12:23 +00002484 // If the comparison is with the result of a select instruction, check whether
2485 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002486 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002487 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002488 return V;
2489
2490 // If the comparison is with the result of a phi instruction, check whether
2491 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002492 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002493 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002494 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002495
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002496 return 0;
2497}
2498
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002499Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002500 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002501 const TargetLibraryInfo *TLI,
2502 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002503 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2504 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002505}
2506
Chris Lattner9dbb4292009-11-09 23:28:39 +00002507/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2508/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002509static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002510 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002511 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2512 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2513
Chris Lattnerd06094f2009-11-10 00:55:12 +00002514 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002515 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002516 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002517
Chris Lattnerd06094f2009-11-10 00:55:12 +00002518 // If we have a constant, make sure it is on the RHS.
2519 std::swap(LHS, RHS);
2520 Pred = CmpInst::getSwappedPredicate(Pred);
2521 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002522
Chris Lattner210c5d42009-11-09 23:55:12 +00002523 // Fold trivial predicates.
2524 if (Pred == FCmpInst::FCMP_FALSE)
2525 return ConstantInt::get(GetCompareTy(LHS), 0);
2526 if (Pred == FCmpInst::FCMP_TRUE)
2527 return ConstantInt::get(GetCompareTy(LHS), 1);
2528
Chris Lattner210c5d42009-11-09 23:55:12 +00002529 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2530 return UndefValue::get(GetCompareTy(LHS));
2531
2532 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002533 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002534 if (CmpInst::isTrueWhenEqual(Pred))
2535 return ConstantInt::get(GetCompareTy(LHS), 1);
2536 if (CmpInst::isFalseWhenEqual(Pred))
2537 return ConstantInt::get(GetCompareTy(LHS), 0);
2538 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002539
Chris Lattner210c5d42009-11-09 23:55:12 +00002540 // Handle fcmp with constant RHS
2541 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2542 // If the constant is a nan, see if we can fold the comparison based on it.
2543 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2544 if (CFP->getValueAPF().isNaN()) {
2545 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2546 return ConstantInt::getFalse(CFP->getContext());
2547 assert(FCmpInst::isUnordered(Pred) &&
2548 "Comparison must be either ordered or unordered!");
2549 // True if unordered.
2550 return ConstantInt::getTrue(CFP->getContext());
2551 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002552 // Check whether the constant is an infinity.
2553 if (CFP->getValueAPF().isInfinity()) {
2554 if (CFP->getValueAPF().isNegative()) {
2555 switch (Pred) {
2556 case FCmpInst::FCMP_OLT:
2557 // No value is ordered and less than negative infinity.
2558 return ConstantInt::getFalse(CFP->getContext());
2559 case FCmpInst::FCMP_UGE:
2560 // All values are unordered with or at least negative infinity.
2561 return ConstantInt::getTrue(CFP->getContext());
2562 default:
2563 break;
2564 }
2565 } else {
2566 switch (Pred) {
2567 case FCmpInst::FCMP_OGT:
2568 // No value is ordered and greater than infinity.
2569 return ConstantInt::getFalse(CFP->getContext());
2570 case FCmpInst::FCMP_ULE:
2571 // All values are unordered with and at most infinity.
2572 return ConstantInt::getTrue(CFP->getContext());
2573 default:
2574 break;
2575 }
2576 }
2577 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002578 }
2579 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002580
Duncan Sands92826de2010-11-07 16:46:25 +00002581 // If the comparison is with the result of a select instruction, check whether
2582 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002583 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002584 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002585 return V;
2586
2587 // If the comparison is with the result of a phi instruction, check whether
2588 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002589 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002590 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002591 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002592
Chris Lattner9dbb4292009-11-09 23:28:39 +00002593 return 0;
2594}
2595
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002596Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002597 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002598 const TargetLibraryInfo *TLI,
2599 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002600 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2601 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002602}
2603
Chris Lattner04754262010-04-20 05:32:14 +00002604/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2605/// the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002606static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2607 Value *FalseVal, const Query &Q,
2608 unsigned MaxRecurse) {
Chris Lattner04754262010-04-20 05:32:14 +00002609 // select true, X, Y -> X
2610 // select false, X, Y -> Y
2611 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2612 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002613
Chris Lattner04754262010-04-20 05:32:14 +00002614 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002615 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002616 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002617
Chris Lattner04754262010-04-20 05:32:14 +00002618 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2619 if (isa<Constant>(TrueVal))
2620 return TrueVal;
2621 return FalseVal;
2622 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002623 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2624 return FalseVal;
2625 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2626 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002627
Chris Lattner04754262010-04-20 05:32:14 +00002628 return 0;
2629}
2630
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002631Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Micah Villmow3574eca2012-10-08 16:38:25 +00002632 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002633 const TargetLibraryInfo *TLI,
2634 const DominatorTree *DT) {
2635 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2636 RecursionLimit);
2637}
2638
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002639/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2640/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002641static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002642 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002643 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2644 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2645 if (!PtrTy)
2646 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002647
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002648 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002649 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002650 return Ops[0];
2651
Duncan Sands85bbff62010-11-22 13:42:49 +00002652 if (isa<UndefValue>(Ops[0])) {
2653 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002654 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002655 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002656 return UndefValue::get(GEPTy);
2657 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002658
Jay Foadb9b54eb2011-07-19 15:07:52 +00002659 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002660 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002661 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2662 if (C->isZero())
2663 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002664 // getelementptr P, N -> P if P points to a type of zero size.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002665 if (Q.TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002666 Type *Ty = PtrTy->getElementType();
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002667 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002668 return Ops[0];
2669 }
2670 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002671
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002672 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002673 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002674 if (!isa<Constant>(Ops[i]))
2675 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002676
Jay Foaddab3d292011-07-21 14:31:17 +00002677 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002678}
2679
Micah Villmow3574eca2012-10-08 16:38:25 +00002680Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002681 const TargetLibraryInfo *TLI,
2682 const DominatorTree *DT) {
2683 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2684}
2685
Duncan Sandsdabc2802011-09-05 06:52:48 +00002686/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2687/// can fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002688static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2689 ArrayRef<unsigned> Idxs, const Query &Q,
2690 unsigned) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002691 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2692 if (Constant *CVal = dyn_cast<Constant>(Val))
2693 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2694
2695 // insertvalue x, undef, n -> x
2696 if (match(Val, m_Undef()))
2697 return Agg;
2698
2699 // insertvalue x, (extractvalue y, n), n
2700 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002701 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2702 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002703 // insertvalue undef, (extractvalue y, n), n -> y
2704 if (match(Agg, m_Undef()))
2705 return EV->getAggregateOperand();
2706
2707 // insertvalue y, (extractvalue y, n), n -> y
2708 if (Agg == EV->getAggregateOperand())
2709 return Agg;
2710 }
2711
2712 return 0;
2713}
2714
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002715Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2716 ArrayRef<unsigned> Idxs,
Micah Villmow3574eca2012-10-08 16:38:25 +00002717 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002718 const TargetLibraryInfo *TLI,
2719 const DominatorTree *DT) {
2720 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2721 RecursionLimit);
2722}
2723
Duncan Sandsff103412010-11-17 04:30:22 +00002724/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002725static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sandsff103412010-11-17 04:30:22 +00002726 // If all of the PHI's incoming values are the same then replace the PHI node
2727 // with the common value.
2728 Value *CommonValue = 0;
2729 bool HasUndefInput = false;
2730 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2731 Value *Incoming = PN->getIncomingValue(i);
2732 // If the incoming value is the phi node itself, it can safely be skipped.
2733 if (Incoming == PN) continue;
2734 if (isa<UndefValue>(Incoming)) {
2735 // Remember that we saw an undef value, but otherwise ignore them.
2736 HasUndefInput = true;
2737 continue;
2738 }
2739 if (CommonValue && Incoming != CommonValue)
2740 return 0; // Not the same, bail out.
2741 CommonValue = Incoming;
2742 }
2743
2744 // If CommonValue is null then all of the incoming values were either undef or
2745 // equal to the phi node itself.
2746 if (!CommonValue)
2747 return UndefValue::get(PN->getType());
2748
2749 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2750 // instruction, we cannot return X as the result of the PHI node unless it
2751 // dominates the PHI block.
2752 if (HasUndefInput)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002753 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
Duncan Sandsff103412010-11-17 04:30:22 +00002754
2755 return CommonValue;
2756}
2757
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002758static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2759 if (Constant *C = dyn_cast<Constant>(Op))
2760 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2761
2762 return 0;
2763}
2764
Micah Villmow3574eca2012-10-08 16:38:25 +00002765Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002766 const TargetLibraryInfo *TLI,
2767 const DominatorTree *DT) {
2768 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2769}
2770
Chris Lattnerd06094f2009-11-10 00:55:12 +00002771//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002772
Chris Lattnerd06094f2009-11-10 00:55:12 +00002773/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2774/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002775static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002776 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002777 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002778 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002779 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002780 Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002781 case Instruction::FAdd:
2782 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2783
Chris Lattner81a0dc92011-02-09 17:15:04 +00002784 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002785 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002786 Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002787 case Instruction::FSub:
2788 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2789
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002790 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002791 case Instruction::FMul:
2792 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002793 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2794 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2795 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2796 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2797 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2798 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002799 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002800 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002801 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002802 case Instruction::LShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002803 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002804 case Instruction::AShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002805 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2806 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2807 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2808 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002809 default:
2810 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2811 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2812 Constant *COps[] = {CLHS, CRHS};
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002813 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2814 Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002815 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002816
Duncan Sands566edb02010-12-21 08:49:00 +00002817 // If the operation is associative, try some generic simplifications.
2818 if (Instruction::isAssociative(Opcode))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002819 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00002820 return V;
2821
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002822 // If the operation is with the result of a select instruction check whether
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002823 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002824 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002825 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002826 return V;
2827
2828 // If the operation is with the result of a phi instruction, check whether
2829 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002830 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002831 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002832 return V;
2833
Chris Lattnerd06094f2009-11-10 00:55:12 +00002834 return 0;
2835 }
2836}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002837
Duncan Sands12a86f52010-11-14 11:23:23 +00002838Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002839 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002840 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002841 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002842}
2843
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002844/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2845/// fold the result.
2846static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002847 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002848 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002849 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2850 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002851}
2852
2853Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002854 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002855 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002856 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2857 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002858}
Chris Lattnere3453782009-11-10 01:08:51 +00002859
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002860template <typename IterTy>
Chandler Carruthe949aa12012-12-28 14:23:29 +00002861static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002862 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00002863 Type *Ty = V->getType();
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002864 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
2865 Ty = PTy->getElementType();
2866 FunctionType *FTy = cast<FunctionType>(Ty);
2867
Dan Gohman71d05032011-11-04 18:32:42 +00002868 // call undef -> undef
Chandler Carruthe949aa12012-12-28 14:23:29 +00002869 if (isa<UndefValue>(V))
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002870 return UndefValue::get(FTy->getReturnType());
Dan Gohman71d05032011-11-04 18:32:42 +00002871
Chandler Carruthe949aa12012-12-28 14:23:29 +00002872 Function *F = dyn_cast<Function>(V);
2873 if (!F)
2874 return 0;
2875
2876 if (!canConstantFoldCallTo(F))
2877 return 0;
2878
2879 SmallVector<Constant *, 4> ConstantArgs;
2880 ConstantArgs.reserve(ArgEnd - ArgBegin);
2881 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
2882 Constant *C = dyn_cast<Constant>(*I);
2883 if (!C)
2884 return 0;
2885 ConstantArgs.push_back(C);
2886 }
2887
2888 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman71d05032011-11-04 18:32:42 +00002889}
2890
Chandler Carruthe949aa12012-12-28 14:23:29 +00002891Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002892 User::op_iterator ArgEnd, const DataLayout *TD,
2893 const TargetLibraryInfo *TLI,
2894 const DominatorTree *DT) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00002895 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(TD, TLI, DT),
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002896 RecursionLimit);
2897}
2898
Chandler Carruthe949aa12012-12-28 14:23:29 +00002899Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002900 const DataLayout *TD, const TargetLibraryInfo *TLI,
2901 const DominatorTree *DT) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00002902 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(TD, TLI, DT),
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002903 RecursionLimit);
2904}
2905
Chris Lattnere3453782009-11-10 01:08:51 +00002906/// SimplifyInstruction - See if we can compute a simplified version of this
2907/// instruction. If not, this returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00002908Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002909 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002910 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002911 Value *Result;
2912
Chris Lattnere3453782009-11-10 01:08:51 +00002913 switch (I->getOpcode()) {
2914 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002915 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002916 break;
Michael Ilseman09ee2502012-12-12 00:27:46 +00002917 case Instruction::FAdd:
2918 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
2919 I->getFastMathFlags(), TD, TLI, DT);
2920 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002921 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002922 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2923 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2924 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002925 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002926 break;
Michael Ilseman09ee2502012-12-12 00:27:46 +00002927 case Instruction::FSub:
2928 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
2929 I->getFastMathFlags(), TD, TLI, DT);
2930 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002931 case Instruction::Sub:
2932 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2933 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2934 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002935 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002936 break;
Michael Ilsemaneb61c922012-11-27 00:46:26 +00002937 case Instruction::FMul:
2938 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
2939 I->getFastMathFlags(), TD, TLI, DT);
2940 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002941 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002942 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002943 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002944 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002945 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002946 break;
2947 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002948 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002949 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002950 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002951 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002952 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002953 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002954 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002955 break;
2956 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002957 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002958 break;
2959 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002960 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002961 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002962 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002963 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2964 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2965 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002966 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002967 break;
2968 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002969 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2970 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002971 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002972 break;
2973 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002974 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2975 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002976 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002977 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002978 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002979 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002980 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002981 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002982 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002983 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002984 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002985 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002986 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002987 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002988 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002989 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002990 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002991 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002992 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002993 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002994 break;
Chris Lattner04754262010-04-20 05:32:14 +00002995 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002996 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002997 I->getOperand(2), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002998 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002999 case Instruction::GetElementPtr: {
3000 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003001 Result = SimplifyGEPInst(Ops, TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003002 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00003003 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00003004 case Instruction::InsertValue: {
3005 InsertValueInst *IV = cast<InsertValueInst>(I);
3006 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3007 IV->getInsertedValueOperand(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003008 IV->getIndices(), TD, TLI, DT);
Duncan Sandsdabc2802011-09-05 06:52:48 +00003009 break;
3010 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00003011 case Instruction::PHI:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003012 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
Duncan Sandsd261dc62010-11-17 08:35:29 +00003013 break;
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003014 case Instruction::Call: {
3015 CallSite CS(cast<CallInst>(I));
3016 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3017 TD, TLI, DT);
Dan Gohman71d05032011-11-04 18:32:42 +00003018 break;
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003019 }
Duncan Sandsbd0fe562012-03-13 14:07:05 +00003020 case Instruction::Trunc:
3021 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
3022 break;
Chris Lattnere3453782009-11-10 01:08:51 +00003023 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00003024
3025 /// If called on unreachable code, the above logic may report that the
3026 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00003027 /// detecting that case here, returning a safe value instead.
3028 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00003029}
3030
Chandler Carruth6b980542012-03-24 21:11:24 +00003031/// \brief Implementation of recursive simplification through an instructions
3032/// uses.
Chris Lattner40d8c282009-11-10 22:26:15 +00003033///
Chandler Carruth6b980542012-03-24 21:11:24 +00003034/// This is the common implementation of the recursive simplification routines.
3035/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3036/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3037/// instructions to process and attempt to simplify it using
3038/// InstructionSimplify.
3039///
3040/// This routine returns 'true' only when *it* simplifies something. The passed
3041/// in simplified value does not count toward this.
3042static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00003043 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003044 const TargetLibraryInfo *TLI,
3045 const DominatorTree *DT) {
3046 bool Simplified = false;
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003047 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands12a86f52010-11-14 11:23:23 +00003048
Chandler Carruth6b980542012-03-24 21:11:24 +00003049 // If we have an explicit value to collapse to, do that round of the
3050 // simplification loop by hand initially.
3051 if (SimpleV) {
3052 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3053 ++UI)
Chandler Carruthc5b785b2012-03-24 22:34:23 +00003054 if (*UI != I)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003055 Worklist.insert(cast<Instruction>(*UI));
Duncan Sands12a86f52010-11-14 11:23:23 +00003056
Chandler Carruth6b980542012-03-24 21:11:24 +00003057 // Replace the instruction with its simplified value.
3058 I->replaceAllUsesWith(SimpleV);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00003059
Chandler Carruth6b980542012-03-24 21:11:24 +00003060 // Gracefully handle edge cases where the instruction is not wired into any
3061 // parent block.
3062 if (I->getParent())
3063 I->eraseFromParent();
3064 } else {
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003065 Worklist.insert(I);
Chris Lattner40d8c282009-11-10 22:26:15 +00003066 }
Duncan Sands12a86f52010-11-14 11:23:23 +00003067
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003068 // Note that we must test the size on each iteration, the worklist can grow.
3069 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3070 I = Worklist[Idx];
Duncan Sands12a86f52010-11-14 11:23:23 +00003071
Chandler Carruth6b980542012-03-24 21:11:24 +00003072 // See if this instruction simplifies.
3073 SimpleV = SimplifyInstruction(I, TD, TLI, DT);
3074 if (!SimpleV)
3075 continue;
3076
3077 Simplified = true;
3078
3079 // Stash away all the uses of the old instruction so we can check them for
3080 // recursive simplifications after a RAUW. This is cheaper than checking all
3081 // uses of To on the recursive step in most cases.
3082 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3083 ++UI)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003084 Worklist.insert(cast<Instruction>(*UI));
Chandler Carruth6b980542012-03-24 21:11:24 +00003085
3086 // Replace the instruction with its simplified value.
3087 I->replaceAllUsesWith(SimpleV);
3088
3089 // Gracefully handle edge cases where the instruction is not wired into any
3090 // parent block.
3091 if (I->getParent())
3092 I->eraseFromParent();
3093 }
3094 return Simplified;
3095}
3096
3097bool llvm::recursivelySimplifyInstruction(Instruction *I,
Micah Villmow3574eca2012-10-08 16:38:25 +00003098 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003099 const TargetLibraryInfo *TLI,
3100 const DominatorTree *DT) {
3101 return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
3102}
3103
3104bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00003105 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003106 const TargetLibraryInfo *TLI,
3107 const DominatorTree *DT) {
3108 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3109 assert(SimpleV && "Must provide a simplified value.");
3110 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
Chris Lattner40d8c282009-11-10 22:26:15 +00003111}