blob: 18d90b62ce3580d559dbbfc550df42c50068d9e8 [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.
Micah Villmow3574eca2012-10-08 16:38:25 +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
Chandler Carruth426c2bf2012-11-01 09:14:31 +0000674 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000675 APInt Offset = APInt::getNullValue(IntPtrWidth);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000676
677 // Even though we don't look through PHI nodes, we could be called on an
678 // instruction in an unreachable block, which may be on a cycle.
679 SmallPtrSet<Value *, 4> Visited;
680 Visited.insert(V);
681 do {
682 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruth7550f962012-12-11 11:05:15 +0000683 if (!GEP->isInBounds() || !GEP->accumulateConstantOffset(TD, Offset))
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000684 break;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000685 V = GEP->getPointerOperand();
686 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
687 V = cast<Operator>(V)->getOperand(0);
688 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
689 if (GA->mayBeOverridden())
690 break;
691 V = GA->getAliasee();
692 } else {
693 break;
694 }
695 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
696 } while (Visited.insert(V));
697
Chandler Carruthece6c6b2012-11-01 08:07:29 +0000698 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000699 return ConstantInt::get(IntPtrTy, Offset);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000700}
701
702/// \brief Compute the constant difference between two pointer values.
703/// If the difference is not a constant, returns zero.
Micah Villmow3574eca2012-10-08 16:38:25 +0000704static Constant *computePointerDifference(const DataLayout &TD,
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000705 Value *LHS, Value *RHS) {
706 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000707 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000708
709 // If LHS and RHS are not related via constant offsets to the same base
710 // value, there is nothing we can do here.
711 if (LHS != RHS)
712 return 0;
713
714 // Otherwise, the difference of LHS - RHS can be computed as:
715 // LHS - RHS
716 // = (LHSOffset + Base) - (RHSOffset + Base)
717 // = LHSOffset - RHSOffset
718 return ConstantExpr::getSub(LHSOffset, RHSOffset);
719}
720
Duncan Sandsfea3b212010-12-15 14:07:39 +0000721/// SimplifySubInst - Given operands for a Sub, see if we can
722/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000723static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000724 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000725 if (Constant *CLHS = dyn_cast<Constant>(Op0))
726 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
727 Constant *Ops[] = { CLHS, CRHS };
728 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000729 Ops, Q.TD, Q.TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000730 }
731
732 // X - undef -> undef
733 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000734 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000735 return UndefValue::get(Op0->getType());
736
737 // X - 0 -> X
738 if (match(Op1, m_Zero()))
739 return Op0;
740
741 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000742 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000743 return Constant::getNullValue(Op0->getType());
744
Duncan Sandsfe02c692011-01-18 09:24:58 +0000745 // (X*2) - X -> X
746 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000747 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000748 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
749 match(Op0, m_Shl(m_Specific(Op1), m_One())))
750 return Op1;
751
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000752 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
753 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
754 Value *Y = 0, *Z = Op1;
755 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
756 // See if "V === Y - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000757 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000758 // It does! Now see if "X + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000759 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000760 // It does, we successfully reassociated!
761 ++NumReassoc;
762 return W;
763 }
764 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000765 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000766 // It does! Now see if "Y + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000767 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000768 // It does, we successfully reassociated!
769 ++NumReassoc;
770 return W;
771 }
772 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000773
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000774 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
775 // For example, X - (X + 1) -> -1
776 X = Op0;
777 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
778 // See if "V === X - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000779 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000780 // It does! Now see if "V - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000781 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000782 // It does, we successfully reassociated!
783 ++NumReassoc;
784 return W;
785 }
786 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000787 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000788 // It does! Now see if "V - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000789 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000790 // It does, we successfully reassociated!
791 ++NumReassoc;
792 return W;
793 }
794 }
795
796 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
797 // For example, X - (X - Y) -> Y.
798 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000799 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
800 // See if "V === Z - X" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000801 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000802 // It does! Now see if "V + Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000803 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsc087e202011-01-14 15:26:10 +0000804 // It does, we successfully reassociated!
805 ++NumReassoc;
806 return W;
807 }
808
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000809 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
810 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
811 match(Op1, m_Trunc(m_Value(Y))))
812 if (X->getType() == Y->getType())
813 // See if "V === X - Y" simplifies.
814 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
815 // It does! Now see if "trunc V" simplifies.
816 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
817 // It does, return the simplified "trunc V".
818 return W;
819
820 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
821 if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
822 match(Op1, m_PtrToInt(m_Value(Y))))
823 if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
824 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
825
Duncan Sands3421d902010-12-21 13:32:22 +0000826 // Mul distributes over Sub. Try some generic simplifications based on this.
827 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000828 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000829 return V;
830
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000831 // i1 sub -> xor.
832 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000833 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000834 return V;
835
Duncan Sandsfea3b212010-12-15 14:07:39 +0000836 // Threading Sub over selects and phi nodes is pointless, so don't bother.
837 // Threading over the select in "A - select(cond, B, C)" means evaluating
838 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
839 // only if B and C are equal. If B and C are equal then (since we assume
840 // that operands have already been simplified) "select(cond, B, C)" should
841 // have been simplified to the common value of B and C already. Analysing
842 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
843 // for threading over phi nodes.
844
845 return 0;
846}
847
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000848Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +0000849 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000850 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000851 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
852 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000853}
854
Michael Ilseman09ee2502012-12-12 00:27:46 +0000855/// Given operands for an FAdd, see if we can fold the result. If not, this
856/// returns null.
857static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
858 const Query &Q, unsigned MaxRecurse) {
859 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
860 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
861 Constant *Ops[] = { CLHS, CRHS };
862 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
863 Ops, Q.TD, Q.TLI);
864 }
865
866 // Canonicalize the constant to the RHS.
867 std::swap(Op0, Op1);
868 }
869
870 // fadd X, -0 ==> X
871 if (match(Op1, m_NegZero()))
872 return Op0;
873
874 // fadd X, 0 ==> X, when we know X is not -0
875 if (match(Op1, m_Zero()) &&
876 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
877 return Op0;
878
879 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
880 // where nnan and ninf have to occur at least once somewhere in this
881 // expression
882 Value *SubOp = 0;
883 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
884 SubOp = Op1;
885 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
886 SubOp = Op0;
887 if (SubOp) {
888 Instruction *FSub = cast<Instruction>(SubOp);
889 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
890 (FMF.noInfs() || FSub->hasNoInfs()))
891 return Constant::getNullValue(Op0->getType());
892 }
893
894 return 0;
895}
896
897/// Given operands for an FSub, see if we can fold the result. If not, this
898/// returns null.
899static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
900 const Query &Q, unsigned MaxRecurse) {
901 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
902 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
903 Constant *Ops[] = { CLHS, CRHS };
904 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
905 Ops, Q.TD, Q.TLI);
906 }
907 }
908
909 // fsub X, 0 ==> X
910 if (match(Op1, m_Zero()))
911 return Op0;
912
913 // fsub X, -0 ==> X, when we know X is not -0
914 if (match(Op1, m_NegZero()) &&
915 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
916 return Op0;
917
918 // fsub 0, (fsub -0.0, X) ==> X
919 Value *X;
920 if (match(Op0, m_AnyZero())) {
921 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
922 return X;
923 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
924 return X;
925 }
926
927 // fsub nnan ninf x, x ==> 0.0
928 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
929 return Constant::getNullValue(Op0->getType());
930
931 return 0;
932}
933
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000934/// Given the operands for an FMul, see if we can fold the result
935static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
936 FastMathFlags FMF,
937 const Query &Q,
938 unsigned MaxRecurse) {
939 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
940 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
941 Constant *Ops[] = { CLHS, CRHS };
942 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
943 Ops, Q.TD, Q.TLI);
944 }
Michael Ilseman09ee2502012-12-12 00:27:46 +0000945
946 // Canonicalize the constant to the RHS.
947 std::swap(Op0, Op1);
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000948 }
949
Michael Ilseman09ee2502012-12-12 00:27:46 +0000950 // fmul X, 1.0 ==> X
951 if (match(Op1, m_FPOne()))
952 return Op0;
953
954 // fmul nnan nsz X, 0 ==> 0
955 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
956 return Op1;
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000957
958 return 0;
959}
960
Duncan Sands82fdab32010-12-21 14:00:22 +0000961/// SimplifyMulInst - Given operands for a Mul, see if we can
962/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000963static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
964 unsigned MaxRecurse) {
Duncan Sands82fdab32010-12-21 14:00:22 +0000965 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
966 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
967 Constant *Ops[] = { CLHS, CRHS };
968 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000969 Ops, Q.TD, Q.TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000970 }
971
972 // Canonicalize the constant to the RHS.
973 std::swap(Op0, Op1);
974 }
975
976 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000977 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000978 return Constant::getNullValue(Op0->getType());
979
980 // X * 0 -> 0
981 if (match(Op1, m_Zero()))
982 return Op1;
983
984 // X * 1 -> X
985 if (match(Op1, m_One()))
986 return Op0;
987
Duncan Sands1895e982011-01-30 18:03:50 +0000988 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000989 Value *X = 0;
990 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
991 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
992 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000993
Nick Lewycky54138802011-01-29 19:55:23 +0000994 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000995 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000996 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000997 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000998
999 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001000 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001001 MaxRecurse))
1002 return V;
1003
1004 // Mul distributes over Add. Try some generic simplifications based on this.
1005 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001006 Q, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +00001007 return V;
1008
1009 // If the operation is with the result of a select instruction, check whether
1010 // operating on either branch of the select always yields the same value.
1011 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001012 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001013 MaxRecurse))
1014 return V;
1015
1016 // If the operation is with the result of a phi instruction, check whether
1017 // operating on all incoming values of the phi always yields the same value.
1018 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001019 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001020 MaxRecurse))
1021 return V;
1022
1023 return 0;
1024}
1025
Michael Ilseman09ee2502012-12-12 00:27:46 +00001026Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1027 const DataLayout *TD, const TargetLibraryInfo *TLI,
1028 const DominatorTree *DT) {
1029 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1030}
1031
1032Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1033 const DataLayout *TD, const TargetLibraryInfo *TLI,
1034 const DominatorTree *DT) {
1035 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1036}
1037
Michael Ilsemaneb61c922012-11-27 00:46:26 +00001038Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1039 FastMathFlags FMF,
1040 const DataLayout *TD,
1041 const TargetLibraryInfo *TLI,
1042 const DominatorTree *DT) {
1043 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1044}
1045
Micah Villmow3574eca2012-10-08 16:38:25 +00001046Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001047 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +00001048 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001049 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +00001050}
1051
Duncan Sands593faa52011-01-28 16:51:11 +00001052/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1053/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +00001054static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001055 const Query &Q, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +00001056 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1057 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1058 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001059 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sands593faa52011-01-28 16:51:11 +00001060 }
1061 }
1062
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001063 bool isSigned = Opcode == Instruction::SDiv;
1064
Duncan Sands593faa52011-01-28 16:51:11 +00001065 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001066 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001067 return Op1;
1068
1069 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001070 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001071 return Constant::getNullValue(Op0->getType());
1072
1073 // 0 / X -> 0, we don't need to preserve faults!
1074 if (match(Op0, m_Zero()))
1075 return Op0;
1076
1077 // X / 1 -> X
1078 if (match(Op1, m_One()))
1079 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +00001080
1081 if (Op0->getType()->isIntegerTy(1))
1082 // It can't be division by zero, hence it must be division by one.
1083 return Op0;
1084
1085 // X / X -> 1
1086 if (Op0 == Op1)
1087 return ConstantInt::get(Op0->getType(), 1);
1088
1089 // (X * Y) / Y -> X if the multiplication does not overflow.
1090 Value *X = 0, *Y = 0;
1091 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1092 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +00001093 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +00001094 // If the Mul knows it does not overflow, then we are good to go.
1095 if ((isSigned && Mul->hasNoSignedWrap()) ||
1096 (!isSigned && Mul->hasNoUnsignedWrap()))
1097 return X;
Duncan Sands593faa52011-01-28 16:51:11 +00001098 // If X has the form X = A / Y then X * Y cannot overflow.
1099 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1100 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1101 return X;
1102 }
1103
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001104 // (X rem Y) / Y -> 0
1105 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1106 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1107 return Constant::getNullValue(Op0->getType());
1108
1109 // If the operation is with the result of a select instruction, check whether
1110 // operating on either branch of the select always yields the same value.
1111 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001112 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001113 return V;
1114
1115 // If the operation is with the result of a phi instruction, check whether
1116 // operating on all incoming values of the phi always yields the same value.
1117 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001118 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001119 return V;
1120
Duncan Sands593faa52011-01-28 16:51:11 +00001121 return 0;
1122}
1123
1124/// SimplifySDivInst - Given operands for an SDiv, see if we can
1125/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001126static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1127 unsigned MaxRecurse) {
1128 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001129 return V;
1130
Duncan Sands593faa52011-01-28 16:51:11 +00001131 return 0;
1132}
1133
Micah Villmow3574eca2012-10-08 16:38:25 +00001134Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001135 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001136 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001137 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001138}
1139
1140/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1141/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001142static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1143 unsigned MaxRecurse) {
1144 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001145 return V;
1146
Duncan Sands593faa52011-01-28 16:51:11 +00001147 return 0;
1148}
1149
Micah Villmow3574eca2012-10-08 16:38:25 +00001150Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001151 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001152 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001153 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001154}
1155
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001156static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1157 unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001158 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001159 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001160 return Op0;
1161
1162 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001163 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001164 return Op1;
1165
1166 return 0;
1167}
1168
Micah Villmow3574eca2012-10-08 16:38:25 +00001169Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001170 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001171 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001172 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001173}
1174
Duncan Sandsf24ed772011-05-02 16:27:02 +00001175/// SimplifyRem - Given operands for an SRem or URem, see if we can
1176/// fold the result. If not, this returns null.
1177static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001178 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001179 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1180 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1181 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001182 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001183 }
1184 }
1185
Duncan Sandsf24ed772011-05-02 16:27:02 +00001186 // X % undef -> undef
1187 if (match(Op1, m_Undef()))
1188 return Op1;
1189
1190 // undef % X -> 0
1191 if (match(Op0, m_Undef()))
1192 return Constant::getNullValue(Op0->getType());
1193
1194 // 0 % X -> 0, we don't need to preserve faults!
1195 if (match(Op0, m_Zero()))
1196 return Op0;
1197
1198 // X % 0 -> undef, we don't need to preserve faults!
1199 if (match(Op1, m_Zero()))
1200 return UndefValue::get(Op0->getType());
1201
1202 // X % 1 -> 0
1203 if (match(Op1, m_One()))
1204 return Constant::getNullValue(Op0->getType());
1205
1206 if (Op0->getType()->isIntegerTy(1))
1207 // It can't be remainder by zero, hence it must be remainder by one.
1208 return Constant::getNullValue(Op0->getType());
1209
1210 // X % X -> 0
1211 if (Op0 == Op1)
1212 return Constant::getNullValue(Op0->getType());
1213
1214 // If the operation is with the result of a select instruction, check whether
1215 // operating on either branch of the select always yields the same value.
1216 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001217 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001218 return V;
1219
1220 // If the operation is with the result of a phi instruction, check whether
1221 // operating on all incoming values of the phi always yields the same value.
1222 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001223 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001224 return V;
1225
1226 return 0;
1227}
1228
1229/// SimplifySRemInst - Given operands for an SRem, see if we can
1230/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001231static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1232 unsigned MaxRecurse) {
1233 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001234 return V;
1235
1236 return 0;
1237}
1238
Micah Villmow3574eca2012-10-08 16:38:25 +00001239Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001240 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001241 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001242 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001243}
1244
1245/// SimplifyURemInst - Given operands for a URem, see if we can
1246/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001247static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001248 unsigned MaxRecurse) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001249 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001250 return V;
1251
1252 return 0;
1253}
1254
Micah Villmow3574eca2012-10-08 16:38:25 +00001255Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001256 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001257 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001258 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001259}
1260
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001261static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +00001262 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001263 // undef % X -> undef (the undef could be a snan).
1264 if (match(Op0, m_Undef()))
1265 return Op0;
1266
1267 // X % undef -> undef
1268 if (match(Op1, m_Undef()))
1269 return Op1;
1270
1271 return 0;
1272}
1273
Micah Villmow3574eca2012-10-08 16:38:25 +00001274Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001275 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001276 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001277 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001278}
1279
Duncan Sandscf80bc12011-01-14 14:44:12 +00001280/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001281/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001282static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001283 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001284 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1285 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1286 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001287 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001288 }
1289 }
1290
Duncan Sandscf80bc12011-01-14 14:44:12 +00001291 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001292 if (match(Op0, m_Zero()))
1293 return Op0;
1294
Duncan Sandscf80bc12011-01-14 14:44:12 +00001295 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001296 if (match(Op1, m_Zero()))
1297 return Op0;
1298
Duncan Sandscf80bc12011-01-14 14:44:12 +00001299 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001300 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001301 return Op1;
1302
1303 // Shifting by the bitwidth or more is undefined.
1304 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1305 if (CI->getValue().getLimitedValue() >=
1306 Op0->getType()->getScalarSizeInBits())
1307 return UndefValue::get(Op0->getType());
1308
Duncan Sandscf80bc12011-01-14 14:44:12 +00001309 // If the operation is with the result of a select instruction, check whether
1310 // operating on either branch of the select always yields the same value.
1311 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001312 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001313 return V;
1314
1315 // If the operation is with the result of a phi instruction, check whether
1316 // operating on all incoming values of the phi always yields the same value.
1317 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001318 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001319 return V;
1320
1321 return 0;
1322}
1323
1324/// SimplifyShlInst - Given operands for an Shl, see if we can
1325/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001326static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001327 const Query &Q, unsigned MaxRecurse) {
1328 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001329 return V;
1330
1331 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001332 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001333 return Constant::getNullValue(Op0->getType());
1334
Chris Lattner81a0dc92011-02-09 17:15:04 +00001335 // (X >> A) << A -> X
1336 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001337 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001338 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001339 return 0;
1340}
1341
Chris Lattner81a0dc92011-02-09 17:15:04 +00001342Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +00001343 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00001344 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001345 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1346 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001347}
1348
1349/// SimplifyLShrInst - Given operands for an LShr, see if we can
1350/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001351static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001352 const Query &Q, unsigned MaxRecurse) {
1353 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001354 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001355
1356 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001357 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001358 return Constant::getNullValue(Op0->getType());
1359
Chris Lattner81a0dc92011-02-09 17:15:04 +00001360 // (X << A) >> A -> X
1361 Value *X;
1362 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1363 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1364 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001365
Duncan Sandsc43cee32011-01-14 00:37:45 +00001366 return 0;
1367}
1368
Chris Lattner81a0dc92011-02-09 17:15:04 +00001369Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001370 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001371 const TargetLibraryInfo *TLI,
1372 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001373 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1374 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001375}
1376
1377/// SimplifyAShrInst - Given operands for an AShr, see if we can
1378/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001379static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001380 const Query &Q, unsigned MaxRecurse) {
1381 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001382 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001383
1384 // all ones >>a X -> all ones
1385 if (match(Op0, m_AllOnes()))
1386 return Op0;
1387
1388 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001389 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001390 return Constant::getAllOnesValue(Op0->getType());
1391
Chris Lattner81a0dc92011-02-09 17:15:04 +00001392 // (X << A) >> A -> X
1393 Value *X;
1394 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1395 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1396 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001397
Duncan Sandsc43cee32011-01-14 00:37:45 +00001398 return 0;
1399}
1400
Chris Lattner81a0dc92011-02-09 17:15:04 +00001401Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001402 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001403 const TargetLibraryInfo *TLI,
1404 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001405 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1406 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001407}
1408
Chris Lattnerd06094f2009-11-10 00:55:12 +00001409/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001410/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001411static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001412 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001413 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1414 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1415 Constant *Ops[] = { CLHS, CRHS };
1416 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001417 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001418 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001419
Chris Lattnerd06094f2009-11-10 00:55:12 +00001420 // Canonicalize the constant to the RHS.
1421 std::swap(Op0, Op1);
1422 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001423
Chris Lattnerd06094f2009-11-10 00:55:12 +00001424 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001425 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001426 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001427
Chris Lattnerd06094f2009-11-10 00:55:12 +00001428 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001429 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001430 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001431
Duncan Sands2b749872010-11-17 18:52:15 +00001432 // X & 0 = 0
1433 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001434 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001435
Duncan Sands2b749872010-11-17 18:52:15 +00001436 // X & -1 = X
1437 if (match(Op1, m_AllOnes()))
1438 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001439
Chris Lattnerd06094f2009-11-10 00:55:12 +00001440 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001441 if (match(Op0, m_Not(m_Specific(Op1))) ||
1442 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001443 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001444
Chris Lattnerd06094f2009-11-10 00:55:12 +00001445 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001446 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001447 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001448 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001449 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001450
Chris Lattnerd06094f2009-11-10 00:55:12 +00001451 // A & (A | ?) = A
1452 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001453 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001454 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001455
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001456 // A & (-A) = A if A is a power of two or zero.
1457 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1458 match(Op1, m_Neg(m_Specific(Op0)))) {
Rafael Espindoladbaa2372012-12-13 03:37:24 +00001459 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001460 return Op0;
Rafael Espindoladbaa2372012-12-13 03:37:24 +00001461 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001462 return Op1;
1463 }
1464
Duncan Sands566edb02010-12-21 08:49:00 +00001465 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001466 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1467 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001468 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001469
Duncan Sands3421d902010-12-21 13:32:22 +00001470 // And distributes over Or. Try some generic simplifications based on this.
1471 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001472 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001473 return V;
1474
1475 // And distributes over Xor. Try some generic simplifications based on this.
1476 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001477 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001478 return V;
1479
1480 // Or distributes over And. Try some generic simplifications based on this.
1481 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001482 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001483 return V;
1484
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001485 // If the operation is with the result of a select instruction, check whether
1486 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001487 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001488 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1489 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001490 return V;
1491
1492 // If the operation is with the result of a phi instruction, check whether
1493 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001494 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001495 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001496 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001497 return V;
1498
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001499 return 0;
1500}
1501
Micah Villmow3574eca2012-10-08 16:38:25 +00001502Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001503 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001504 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001505 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001506}
1507
Chris Lattnerd06094f2009-11-10 00:55:12 +00001508/// SimplifyOrInst - Given operands for an Or, see if we can
1509/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001510static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1511 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001512 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1513 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1514 Constant *Ops[] = { CLHS, CRHS };
1515 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001516 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001517 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001518
Chris Lattnerd06094f2009-11-10 00:55:12 +00001519 // Canonicalize the constant to the RHS.
1520 std::swap(Op0, Op1);
1521 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001522
Chris Lattnerd06094f2009-11-10 00:55:12 +00001523 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001524 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001525 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001526
Chris Lattnerd06094f2009-11-10 00:55:12 +00001527 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001528 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001529 return Op0;
1530
Duncan Sands2b749872010-11-17 18:52:15 +00001531 // X | 0 = X
1532 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001533 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001534
Duncan Sands2b749872010-11-17 18:52:15 +00001535 // X | -1 = -1
1536 if (match(Op1, m_AllOnes()))
1537 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001538
Chris Lattnerd06094f2009-11-10 00:55:12 +00001539 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001540 if (match(Op0, m_Not(m_Specific(Op1))) ||
1541 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001542 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001543
Chris Lattnerd06094f2009-11-10 00:55:12 +00001544 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001545 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001546 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001547 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001548 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001549
Chris Lattnerd06094f2009-11-10 00:55:12 +00001550 // A | (A & ?) = A
1551 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001552 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001553 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001554
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001555 // ~(A & ?) | A = -1
1556 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1557 (A == Op1 || B == Op1))
1558 return Constant::getAllOnesValue(Op1->getType());
1559
1560 // A | ~(A & ?) = -1
1561 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1562 (A == Op0 || B == Op0))
1563 return Constant::getAllOnesValue(Op0->getType());
1564
Duncan Sands566edb02010-12-21 08:49:00 +00001565 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001566 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1567 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001568 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001569
Duncan Sands3421d902010-12-21 13:32:22 +00001570 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001571 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1572 MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001573 return V;
1574
1575 // And distributes over Or. Try some generic simplifications based on this.
1576 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001577 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001578 return V;
1579
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001580 // If the operation is with the result of a select instruction, check whether
1581 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001582 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001583 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001584 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001585 return V;
1586
1587 // If the operation is with the result of a phi instruction, check whether
1588 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001589 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001590 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001591 return V;
1592
Chris Lattnerd06094f2009-11-10 00:55:12 +00001593 return 0;
1594}
1595
Micah Villmow3574eca2012-10-08 16:38:25 +00001596Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001597 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001598 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001599 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001600}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001601
Duncan Sands2b749872010-11-17 18:52:15 +00001602/// SimplifyXorInst - Given operands for a Xor, see if we can
1603/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001604static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1605 unsigned MaxRecurse) {
Duncan Sands2b749872010-11-17 18:52:15 +00001606 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1607 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1608 Constant *Ops[] = { CLHS, CRHS };
1609 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001610 Ops, Q.TD, Q.TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001611 }
1612
1613 // Canonicalize the constant to the RHS.
1614 std::swap(Op0, Op1);
1615 }
1616
1617 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001618 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001619 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001620
1621 // A ^ 0 = A
1622 if (match(Op1, m_Zero()))
1623 return Op0;
1624
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001625 // A ^ A = 0
1626 if (Op0 == Op1)
1627 return Constant::getNullValue(Op0->getType());
1628
Duncan Sands2b749872010-11-17 18:52:15 +00001629 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001630 if (match(Op0, m_Not(m_Specific(Op1))) ||
1631 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001632 return Constant::getAllOnesValue(Op0->getType());
1633
Duncan Sands566edb02010-12-21 08:49:00 +00001634 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001635 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1636 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001637 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001638
Duncan Sands3421d902010-12-21 13:32:22 +00001639 // And distributes over Xor. Try some generic simplifications based on this.
1640 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001641 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001642 return V;
1643
Duncan Sands87689cf2010-11-19 09:20:39 +00001644 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1645 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1646 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1647 // only if B and C are equal. If B and C are equal then (since we assume
1648 // that operands have already been simplified) "select(cond, B, C)" should
1649 // have been simplified to the common value of B and C already. Analysing
1650 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1651 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001652
1653 return 0;
1654}
1655
Micah Villmow3574eca2012-10-08 16:38:25 +00001656Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001657 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001658 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001659 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001660}
1661
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001662static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001663 return CmpInst::makeCmpResultType(Op->getType());
1664}
1665
Duncan Sandse864b5b2011-05-07 16:56:49 +00001666/// ExtractEquivalentCondition - Rummage around inside V looking for something
1667/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1668/// otherwise return null. Helper function for analyzing max/min idioms.
1669static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1670 Value *LHS, Value *RHS) {
1671 SelectInst *SI = dyn_cast<SelectInst>(V);
1672 if (!SI)
1673 return 0;
1674 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1675 if (!Cmp)
1676 return 0;
1677 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1678 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1679 return Cmp;
1680 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1681 LHS == CmpRHS && RHS == CmpLHS)
1682 return Cmp;
1683 return 0;
1684}
1685
Micah Villmow3574eca2012-10-08 16:38:25 +00001686static Constant *computePointerICmp(const DataLayout &TD,
Chandler Carruth58725a62012-03-25 21:28:14 +00001687 CmpInst::Predicate Pred,
1688 Value *LHS, Value *RHS) {
1689 // We can only fold certain predicates on pointer comparisons.
1690 switch (Pred) {
1691 default:
1692 return 0;
1693
1694 // Equality comaprisons are easy to fold.
1695 case CmpInst::ICMP_EQ:
1696 case CmpInst::ICMP_NE:
1697 break;
1698
1699 // We can only handle unsigned relational comparisons because 'inbounds' on
1700 // a GEP only protects against unsigned wrapping.
1701 case CmpInst::ICMP_UGT:
1702 case CmpInst::ICMP_UGE:
1703 case CmpInst::ICMP_ULT:
1704 case CmpInst::ICMP_ULE:
1705 // However, we have to switch them to their signed variants to handle
1706 // negative indices from the base pointer.
1707 Pred = ICmpInst::getSignedPredicate(Pred);
1708 break;
1709 }
1710
1711 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
Chandler Carruth58725a62012-03-25 21:28:14 +00001712 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
Chandler Carruth58725a62012-03-25 21:28:14 +00001713
1714 // If LHS and RHS are not related via constant offsets to the same base
1715 // value, there is nothing we can do here.
1716 if (LHS != RHS)
1717 return 0;
1718
1719 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1720}
Chris Lattner009e2652012-02-24 19:01:58 +00001721
Chris Lattner9dbb4292009-11-09 23:28:39 +00001722/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1723/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001724static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001725 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001726 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001727 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001728
Chris Lattnerd06094f2009-11-10 00:55:12 +00001729 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001730 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001731 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001732
1733 // If we have a constant, make sure it is on the RHS.
1734 std::swap(LHS, RHS);
1735 Pred = CmpInst::getSwappedPredicate(Pred);
1736 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001737
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001738 Type *ITy = GetCompareTy(LHS); // The return type.
1739 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001740
Chris Lattner210c5d42009-11-09 23:55:12 +00001741 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001742 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1743 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001744 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001745 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001746
Duncan Sands6dc91252011-01-13 08:56:29 +00001747 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001748 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001749 switch (Pred) {
1750 default: break;
1751 case ICmpInst::ICMP_EQ:
1752 // X == 1 -> X
1753 if (match(RHS, m_One()))
1754 return LHS;
1755 break;
1756 case ICmpInst::ICMP_NE:
1757 // X != 0 -> X
1758 if (match(RHS, m_Zero()))
1759 return LHS;
1760 break;
1761 case ICmpInst::ICMP_UGT:
1762 // X >u 0 -> X
1763 if (match(RHS, m_Zero()))
1764 return LHS;
1765 break;
1766 case ICmpInst::ICMP_UGE:
1767 // X >=u 1 -> X
1768 if (match(RHS, m_One()))
1769 return LHS;
1770 break;
1771 case ICmpInst::ICMP_SLT:
1772 // X <s 0 -> X
1773 if (match(RHS, m_Zero()))
1774 return LHS;
1775 break;
1776 case ICmpInst::ICMP_SLE:
1777 // X <=s -1 -> X
1778 if (match(RHS, m_One()))
1779 return LHS;
1780 break;
1781 }
1782 }
1783
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001784 // icmp <object*>, <object*/null> - Different identified objects have
1785 // different addresses (unless null), and what's more the address of an
1786 // identified local is never equal to another argument (again, barring null).
1787 // Note that generalizing to the case where LHS is a global variable address
1788 // or null is pointless, since if both LHS and RHS are constants then we
1789 // already constant folded the compare, and if only one of them is then we
1790 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001791 Value *LHSPtr = LHS->stripPointerCasts();
1792 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001793 if (LHSPtr == RHSPtr)
1794 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001795
Chris Lattnerb053fc12012-02-20 00:42:49 +00001796 // Be more aggressive about stripping pointer adjustments when checking a
1797 // comparison of an alloca address to another object. We can rip off all
1798 // inbounds GEP operations, even if they are variable.
Chandler Carruth84dfc322012-03-10 08:39:09 +00001799 LHSPtr = LHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001800 if (llvm::isIdentifiedObject(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001801 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001802 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1803 // If both sides are different identified objects, they aren't equal
1804 // unless they're null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001805 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001806 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001807 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001808
1809 // A local identified object (alloca or noalias call) can't equal any
Chandler Carruth961e1ac2012-08-07 10:59:59 +00001810 // incoming argument, unless they're both null or they belong to
1811 // different functions. The latter happens during inlining.
1812 if (Instruction *LHSInst = dyn_cast<Instruction>(LHSPtr))
1813 if (Argument *RHSArg = dyn_cast<Argument>(RHSPtr))
1814 if (LHSInst->getParent()->getParent() == RHSArg->getParent() &&
1815 Pred == CmpInst::ICMP_EQ)
1816 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001817 }
1818
1819 // Assume that the constant null is on the right.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001820 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001821 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001822 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001823 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001824 return ConstantInt::get(ITy, true);
1825 }
Chandler Carruth961e1ac2012-08-07 10:59:59 +00001826 } else if (Argument *LHSArg = dyn_cast<Argument>(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001827 RHSPtr = RHSPtr->stripInBoundsOffsets();
Chandler Carruth961e1ac2012-08-07 10:59:59 +00001828 // An alloca can't be equal to an argument unless they come from separate
1829 // functions via inlining.
1830 if (AllocaInst *RHSInst = dyn_cast<AllocaInst>(RHSPtr)) {
1831 if (LHSArg->getParent() == RHSInst->getParent()->getParent()) {
1832 if (Pred == CmpInst::ICMP_EQ)
1833 return ConstantInt::get(ITy, false);
1834 else if (Pred == CmpInst::ICMP_NE)
1835 return ConstantInt::get(ITy, true);
1836 }
Bill Wendlingc17731d652012-03-10 17:56:03 +00001837 }
Chris Lattnerb053fc12012-02-20 00:42:49 +00001838 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001839
1840 // If we are comparing with zero then try hard since this is a common case.
1841 if (match(RHS, m_Zero())) {
1842 bool LHSKnownNonNegative, LHSKnownNegative;
1843 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001844 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001845 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001846 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001847 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001848 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001849 case ICmpInst::ICMP_EQ:
1850 case ICmpInst::ICMP_ULE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001851 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001852 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001853 break;
1854 case ICmpInst::ICMP_NE:
1855 case ICmpInst::ICMP_UGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001856 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001857 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001858 break;
1859 case ICmpInst::ICMP_SLT:
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 Sandsd70d1a52011-01-25 09:38:29 +00001863 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001864 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001865 break;
1866 case ICmpInst::ICMP_SLE:
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 getTrue(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001870 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001871 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001872 break;
1873 case ICmpInst::ICMP_SGE:
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 Sandsd70d1a52011-01-25 09:38:29 +00001877 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001878 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001879 break;
1880 case ICmpInst::ICMP_SGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001881 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001882 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001883 return getFalse(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001884 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001885 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001886 break;
1887 }
1888 }
1889
1890 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001891 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001892 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1893 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1894 if (RHS_CR.isEmptySet())
1895 return ConstantInt::getFalse(CI->getContext());
1896 if (RHS_CR.isFullSet())
1897 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001898
Nick Lewycky3a73e342011-03-04 07:00:57 +00001899 // Many binary operators with constant RHS have easy to compute constant
1900 // range. Use them to check whether the comparison is a tautology.
1901 uint32_t Width = CI->getBitWidth();
1902 APInt Lower = APInt(Width, 0);
1903 APInt Upper = APInt(Width, 0);
1904 ConstantInt *CI2;
1905 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1906 // 'urem x, CI2' produces [0, CI2).
1907 Upper = CI2->getValue();
1908 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1909 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1910 Upper = CI2->getValue().abs();
1911 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001912 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1913 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001914 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001915 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1916 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1917 APInt NegOne = APInt::getAllOnesValue(Width);
1918 if (!CI2->isZero())
1919 Upper = NegOne.udiv(CI2->getValue()) + 1;
1920 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1921 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1922 APInt IntMin = APInt::getSignedMinValue(Width);
1923 APInt IntMax = APInt::getSignedMaxValue(Width);
1924 APInt Val = CI2->getValue().abs();
1925 if (!Val.isMinValue()) {
1926 Lower = IntMin.sdiv(Val);
1927 Upper = IntMax.sdiv(Val) + 1;
1928 }
1929 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1930 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1931 APInt NegOne = APInt::getAllOnesValue(Width);
1932 if (CI2->getValue().ult(Width))
1933 Upper = NegOne.lshr(CI2->getValue()) + 1;
1934 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1935 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1936 APInt IntMin = APInt::getSignedMinValue(Width);
1937 APInt IntMax = APInt::getSignedMaxValue(Width);
1938 if (CI2->getValue().ult(Width)) {
1939 Lower = IntMin.ashr(CI2->getValue());
1940 Upper = IntMax.ashr(CI2->getValue()) + 1;
1941 }
1942 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1943 // 'or x, CI2' produces [CI2, UINT_MAX].
1944 Lower = CI2->getValue();
1945 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1946 // 'and x, CI2' produces [0, CI2].
1947 Upper = CI2->getValue() + 1;
1948 }
1949 if (Lower != Upper) {
1950 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1951 if (RHS_CR.contains(LHS_CR))
1952 return ConstantInt::getTrue(RHS->getContext());
1953 if (RHS_CR.inverse().contains(LHS_CR))
1954 return ConstantInt::getFalse(RHS->getContext());
1955 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001956 }
1957
Duncan Sands9d32f602011-01-20 13:21:55 +00001958 // Compare of cast, for example (zext X) != 0 -> X != 0
1959 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1960 Instruction *LI = cast<CastInst>(LHS);
1961 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001962 Type *SrcTy = SrcOp->getType();
1963 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001964
1965 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1966 // if the integer type is the same size as the pointer type.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001967 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00001968 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands9d32f602011-01-20 13:21:55 +00001969 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1970 // Transfer the cast to the constant.
1971 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1972 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001973 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001974 return V;
1975 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1976 if (RI->getOperand(0)->getType() == SrcTy)
1977 // Compare without the cast.
1978 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001979 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001980 return V;
1981 }
1982 }
1983
1984 if (isa<ZExtInst>(LHS)) {
1985 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1986 // same type.
1987 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1988 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1989 // Compare X and Y. Note that signed predicates become unsigned.
1990 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001991 SrcOp, RI->getOperand(0), Q,
Duncan Sands9d32f602011-01-20 13:21:55 +00001992 MaxRecurse-1))
1993 return V;
1994 }
1995 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1996 // too. If not, then try to deduce the result of the comparison.
1997 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1998 // Compute the constant that would happen if we truncated to SrcTy then
1999 // reextended to DstTy.
2000 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2001 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2002
2003 // If the re-extended constant didn't change then this is effectively
2004 // also a case of comparing two zero-extended values.
2005 if (RExt == CI && MaxRecurse)
2006 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002007 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002008 return V;
2009
2010 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2011 // there. Use this to work out the result of the comparison.
2012 if (RExt != CI) {
2013 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00002014 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00002015 // LHS <u RHS.
2016 case ICmpInst::ICMP_EQ:
2017 case ICmpInst::ICMP_UGT:
2018 case ICmpInst::ICMP_UGE:
2019 return ConstantInt::getFalse(CI->getContext());
2020
2021 case ICmpInst::ICMP_NE:
2022 case ICmpInst::ICMP_ULT:
2023 case ICmpInst::ICMP_ULE:
2024 return ConstantInt::getTrue(CI->getContext());
2025
2026 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2027 // is non-negative then LHS <s RHS.
2028 case ICmpInst::ICMP_SGT:
2029 case ICmpInst::ICMP_SGE:
2030 return CI->getValue().isNegative() ?
2031 ConstantInt::getTrue(CI->getContext()) :
2032 ConstantInt::getFalse(CI->getContext());
2033
2034 case ICmpInst::ICMP_SLT:
2035 case ICmpInst::ICMP_SLE:
2036 return CI->getValue().isNegative() ?
2037 ConstantInt::getFalse(CI->getContext()) :
2038 ConstantInt::getTrue(CI->getContext());
2039 }
2040 }
2041 }
2042 }
2043
2044 if (isa<SExtInst>(LHS)) {
2045 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2046 // same type.
2047 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2048 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2049 // Compare X and Y. Note that the predicate does not change.
2050 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002051 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002052 return V;
2053 }
2054 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2055 // too. If not, then try to deduce the result of the comparison.
2056 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2057 // Compute the constant that would happen if we truncated to SrcTy then
2058 // reextended to DstTy.
2059 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2060 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2061
2062 // If the re-extended constant didn't change then this is effectively
2063 // also a case of comparing two sign-extended values.
2064 if (RExt == CI && MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002065 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002066 return V;
2067
2068 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2069 // bits there. Use this to work out the result of the comparison.
2070 if (RExt != CI) {
2071 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00002072 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00002073 case ICmpInst::ICMP_EQ:
2074 return ConstantInt::getFalse(CI->getContext());
2075 case ICmpInst::ICMP_NE:
2076 return ConstantInt::getTrue(CI->getContext());
2077
2078 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2079 // LHS >s RHS.
2080 case ICmpInst::ICMP_SGT:
2081 case ICmpInst::ICMP_SGE:
2082 return CI->getValue().isNegative() ?
2083 ConstantInt::getTrue(CI->getContext()) :
2084 ConstantInt::getFalse(CI->getContext());
2085 case ICmpInst::ICMP_SLT:
2086 case ICmpInst::ICMP_SLE:
2087 return CI->getValue().isNegative() ?
2088 ConstantInt::getFalse(CI->getContext()) :
2089 ConstantInt::getTrue(CI->getContext());
2090
2091 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2092 // LHS >u RHS.
2093 case ICmpInst::ICMP_UGT:
2094 case ICmpInst::ICMP_UGE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002095 // Comparison is true iff the LHS <s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002096 if (MaxRecurse)
2097 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2098 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002099 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002100 return V;
2101 break;
2102 case ICmpInst::ICMP_ULT:
2103 case ICmpInst::ICMP_ULE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002104 // Comparison is true iff the LHS >=s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002105 if (MaxRecurse)
2106 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2107 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002108 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002109 return V;
2110 break;
2111 }
2112 }
2113 }
2114 }
2115 }
2116
Duncan Sands52fb8462011-02-13 17:15:40 +00002117 // Special logic for binary operators.
2118 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2119 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2120 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00002121 // Analyze the case when either LHS or RHS is an add instruction.
2122 Value *A = 0, *B = 0, *C = 0, *D = 0;
2123 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2124 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2125 if (LBO && LBO->getOpcode() == Instruction::Add) {
2126 A = LBO->getOperand(0); B = LBO->getOperand(1);
2127 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2128 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2129 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2130 }
2131 if (RBO && RBO->getOpcode() == Instruction::Add) {
2132 C = RBO->getOperand(0); D = RBO->getOperand(1);
2133 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2134 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2135 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2136 }
2137
2138 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2139 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2140 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2141 Constant::getNullValue(RHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002142 Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002143 return V;
2144
2145 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2146 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2147 if (Value *V = SimplifyICmpInst(Pred,
2148 Constant::getNullValue(LHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002149 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002150 return V;
2151
2152 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2153 if (A && C && (A == C || A == D || B == C || B == D) &&
2154 NoLHSWrapProblem && NoRHSWrapProblem) {
2155 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002156 Value *Y, *Z;
2157 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002158 // C + B == C + D -> B == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002159 Y = B;
2160 Z = D;
2161 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002162 // D + B == C + D -> B == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002163 Y = B;
2164 Z = C;
2165 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002166 // A + C == C + D -> A == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002167 Y = A;
2168 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002169 } else {
2170 assert(B == D);
2171 // A + D == C + D -> A == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002172 Y = A;
2173 Z = C;
2174 }
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002175 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002176 return V;
2177 }
2178 }
2179
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002180 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002181 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002182 switch (Pred) {
2183 default:
2184 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002185 case ICmpInst::ICMP_SGT:
2186 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002187 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002188 if (!KnownNonNegative)
2189 break;
2190 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002191 case ICmpInst::ICMP_EQ:
2192 case ICmpInst::ICMP_UGT:
2193 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002194 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002195 case ICmpInst::ICMP_SLT:
2196 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002197 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002198 if (!KnownNonNegative)
2199 break;
2200 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002201 case ICmpInst::ICMP_NE:
2202 case ICmpInst::ICMP_ULT:
2203 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002204 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002205 }
2206 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002207 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2208 bool KnownNonNegative, KnownNegative;
2209 switch (Pred) {
2210 default:
2211 break;
2212 case ICmpInst::ICMP_SGT:
2213 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002214 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002215 if (!KnownNonNegative)
2216 break;
2217 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002218 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002219 case ICmpInst::ICMP_UGT:
2220 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002221 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002222 case ICmpInst::ICMP_SLT:
2223 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002224 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002225 if (!KnownNonNegative)
2226 break;
2227 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002228 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002229 case ICmpInst::ICMP_ULT:
2230 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002231 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002232 }
2233 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002234
Duncan Sandsc65c7472011-10-28 18:17:44 +00002235 // x udiv y <=u x.
2236 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2237 // icmp pred (X /u Y), X
2238 if (Pred == ICmpInst::ICMP_UGT)
2239 return getFalse(ITy);
2240 if (Pred == ICmpInst::ICMP_ULE)
2241 return getTrue(ITy);
2242 }
2243
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002244 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2245 LBO->getOperand(1) == RBO->getOperand(1)) {
2246 switch (LBO->getOpcode()) {
2247 default: break;
2248 case Instruction::UDiv:
2249 case Instruction::LShr:
2250 if (ICmpInst::isSigned(Pred))
2251 break;
2252 // fall-through
2253 case Instruction::SDiv:
2254 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002255 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002256 break;
2257 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002258 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002259 return V;
2260 break;
2261 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002262 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002263 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2264 if (!NUW && !NSW)
2265 break;
2266 if (!NSW && ICmpInst::isSigned(Pred))
2267 break;
2268 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002269 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002270 return V;
2271 break;
2272 }
2273 }
2274 }
2275
Duncan Sandsad206812011-05-03 19:53:10 +00002276 // Simplify comparisons involving max/min.
2277 Value *A, *B;
2278 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002279 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sandsad206812011-05-03 19:53:10 +00002280
Duncan Sands8140ad32011-05-04 16:05:05 +00002281 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002282 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2283 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002284 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002285 // We analyze this as smax(A, B) pred A.
2286 P = Pred;
2287 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2288 (A == LHS || B == LHS)) {
2289 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002290 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002291 // We analyze this as smax(A, B) swapped-pred A.
2292 P = CmpInst::getSwappedPredicate(Pred);
2293 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2294 (A == RHS || B == RHS)) {
2295 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
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) swapped-pred -A.
2298 // Note that we do not need to actually form -A or -B thanks to EqP.
2299 P = CmpInst::getSwappedPredicate(Pred);
2300 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2301 (A == LHS || B == LHS)) {
2302 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002303 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sandsad206812011-05-03 19:53:10 +00002304 // We analyze this as smax(-A, -B) pred -A.
2305 // Note that we do not need to actually form -A or -B thanks to EqP.
2306 P = Pred;
2307 }
2308 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2309 // Cases correspond to "max(A, B) p A".
2310 switch (P) {
2311 default:
2312 break;
2313 case CmpInst::ICMP_EQ:
2314 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002315 // Equivalent to "A EqP B". This may be the same as the condition tested
2316 // in the max/min; if so, we can just return that.
2317 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2318 return V;
2319 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2320 return V;
2321 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002322 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002323 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002324 return V;
2325 break;
2326 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002327 case CmpInst::ICMP_SGT: {
2328 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2329 // Equivalent to "A InvEqP B". This may be the same as the condition
2330 // tested in the max/min; if so, we can just return that.
2331 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2332 return V;
2333 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2334 return V;
2335 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002336 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002337 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002338 return V;
2339 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002340 }
Duncan Sandsad206812011-05-03 19:53:10 +00002341 case CmpInst::ICMP_SGE:
2342 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002343 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002344 case CmpInst::ICMP_SLT:
2345 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002346 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002347 }
2348 }
2349
Duncan Sands8140ad32011-05-04 16:05:05 +00002350 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002351 P = CmpInst::BAD_ICMP_PREDICATE;
2352 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2353 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002354 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002355 // We analyze this as umax(A, B) pred A.
2356 P = Pred;
2357 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2358 (A == LHS || B == LHS)) {
2359 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002360 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002361 // We analyze this as umax(A, B) swapped-pred A.
2362 P = CmpInst::getSwappedPredicate(Pred);
2363 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2364 (A == RHS || B == RHS)) {
2365 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
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) swapped-pred -A.
2368 // Note that we do not need to actually form -A or -B thanks to EqP.
2369 P = CmpInst::getSwappedPredicate(Pred);
2370 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2371 (A == LHS || B == LHS)) {
2372 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002373 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sandsad206812011-05-03 19:53:10 +00002374 // We analyze this as umax(-A, -B) pred -A.
2375 // Note that we do not need to actually form -A or -B thanks to EqP.
2376 P = Pred;
2377 }
2378 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2379 // Cases correspond to "max(A, B) p A".
2380 switch (P) {
2381 default:
2382 break;
2383 case CmpInst::ICMP_EQ:
2384 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002385 // Equivalent to "A EqP B". This may be the same as the condition tested
2386 // in the max/min; if so, we can just return that.
2387 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2388 return V;
2389 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2390 return V;
2391 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002392 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002393 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002394 return V;
2395 break;
2396 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002397 case CmpInst::ICMP_UGT: {
2398 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2399 // Equivalent to "A InvEqP B". This may be the same as the condition
2400 // tested in the max/min; if so, we can just return that.
2401 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2402 return V;
2403 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2404 return V;
2405 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002406 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002407 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002408 return V;
2409 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002410 }
Duncan Sandsad206812011-05-03 19:53:10 +00002411 case CmpInst::ICMP_UGE:
2412 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002413 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002414 case CmpInst::ICMP_ULT:
2415 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002416 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002417 }
2418 }
2419
Duncan Sands8140ad32011-05-04 16:05:05 +00002420 // Variants on "max(x,y) >= min(x,z)".
2421 Value *C, *D;
2422 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2423 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2424 (A == C || A == D || B == C || B == D)) {
2425 // max(x, ?) pred min(x, ?).
2426 if (Pred == CmpInst::ICMP_SGE)
2427 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002428 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002429 if (Pred == CmpInst::ICMP_SLT)
2430 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002431 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002432 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2433 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2434 (A == C || A == D || B == C || B == D)) {
2435 // min(x, ?) pred max(x, ?).
2436 if (Pred == CmpInst::ICMP_SLE)
2437 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002438 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002439 if (Pred == CmpInst::ICMP_SGT)
2440 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002441 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002442 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2443 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2444 (A == C || A == D || B == C || B == D)) {
2445 // max(x, ?) pred min(x, ?).
2446 if (Pred == CmpInst::ICMP_UGE)
2447 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002448 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002449 if (Pred == CmpInst::ICMP_ULT)
2450 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002451 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002452 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2453 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2454 (A == C || A == D || B == C || B == D)) {
2455 // min(x, ?) pred max(x, ?).
2456 if (Pred == CmpInst::ICMP_ULE)
2457 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002458 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002459 if (Pred == CmpInst::ICMP_UGT)
2460 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002461 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002462 }
2463
Chandler Carruth58725a62012-03-25 21:28:14 +00002464 // Simplify comparisons of related pointers using a powerful, recursive
2465 // GEP-walk when we have target data available..
Dan Gohman5f1686f2013-01-31 00:32:11 +00002466 if (Q.TD && LHS->getType()->isPointerTy())
Chandler Carruth58725a62012-03-25 21:28:14 +00002467 if (Constant *C = computePointerICmp(*Q.TD, Pred, LHS, RHS))
2468 return C;
2469
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002470 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2471 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2472 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2473 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2474 (ICmpInst::isEquality(Pred) ||
2475 (GLHS->isInBounds() && GRHS->isInBounds() &&
2476 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2477 // The bases are equal and the indices are constant. Build a constant
2478 // expression GEP with the same indices and a null base pointer to see
2479 // what constant folding can make out of it.
2480 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2481 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2482 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2483
2484 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2485 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2486 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2487 }
2488 }
2489 }
2490
Duncan Sands1ac7c992010-11-07 16:12:23 +00002491 // If the comparison is with the result of a select instruction, check whether
2492 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002493 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002494 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002495 return V;
2496
2497 // If the comparison is with the result of a phi instruction, check whether
2498 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002499 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002500 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002501 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002502
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002503 return 0;
2504}
2505
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002506Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002507 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002508 const TargetLibraryInfo *TLI,
2509 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002510 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2511 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002512}
2513
Chris Lattner9dbb4292009-11-09 23:28:39 +00002514/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2515/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002516static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002517 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002518 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2519 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2520
Chris Lattnerd06094f2009-11-10 00:55:12 +00002521 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002522 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002523 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002524
Chris Lattnerd06094f2009-11-10 00:55:12 +00002525 // If we have a constant, make sure it is on the RHS.
2526 std::swap(LHS, RHS);
2527 Pred = CmpInst::getSwappedPredicate(Pred);
2528 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002529
Chris Lattner210c5d42009-11-09 23:55:12 +00002530 // Fold trivial predicates.
2531 if (Pred == FCmpInst::FCMP_FALSE)
2532 return ConstantInt::get(GetCompareTy(LHS), 0);
2533 if (Pred == FCmpInst::FCMP_TRUE)
2534 return ConstantInt::get(GetCompareTy(LHS), 1);
2535
Chris Lattner210c5d42009-11-09 23:55:12 +00002536 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2537 return UndefValue::get(GetCompareTy(LHS));
2538
2539 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002540 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002541 if (CmpInst::isTrueWhenEqual(Pred))
2542 return ConstantInt::get(GetCompareTy(LHS), 1);
2543 if (CmpInst::isFalseWhenEqual(Pred))
2544 return ConstantInt::get(GetCompareTy(LHS), 0);
2545 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002546
Chris Lattner210c5d42009-11-09 23:55:12 +00002547 // Handle fcmp with constant RHS
2548 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2549 // If the constant is a nan, see if we can fold the comparison based on it.
2550 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2551 if (CFP->getValueAPF().isNaN()) {
2552 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2553 return ConstantInt::getFalse(CFP->getContext());
2554 assert(FCmpInst::isUnordered(Pred) &&
2555 "Comparison must be either ordered or unordered!");
2556 // True if unordered.
2557 return ConstantInt::getTrue(CFP->getContext());
2558 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002559 // Check whether the constant is an infinity.
2560 if (CFP->getValueAPF().isInfinity()) {
2561 if (CFP->getValueAPF().isNegative()) {
2562 switch (Pred) {
2563 case FCmpInst::FCMP_OLT:
2564 // No value is ordered and less than negative infinity.
2565 return ConstantInt::getFalse(CFP->getContext());
2566 case FCmpInst::FCMP_UGE:
2567 // All values are unordered with or at least negative infinity.
2568 return ConstantInt::getTrue(CFP->getContext());
2569 default:
2570 break;
2571 }
2572 } else {
2573 switch (Pred) {
2574 case FCmpInst::FCMP_OGT:
2575 // No value is ordered and greater than infinity.
2576 return ConstantInt::getFalse(CFP->getContext());
2577 case FCmpInst::FCMP_ULE:
2578 // All values are unordered with and at most infinity.
2579 return ConstantInt::getTrue(CFP->getContext());
2580 default:
2581 break;
2582 }
2583 }
2584 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002585 }
2586 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002587
Duncan Sands92826de2010-11-07 16:46:25 +00002588 // If the comparison is with the result of a select instruction, check whether
2589 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002590 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002591 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002592 return V;
2593
2594 // If the comparison is with the result of a phi instruction, check whether
2595 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002596 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002597 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002598 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002599
Chris Lattner9dbb4292009-11-09 23:28:39 +00002600 return 0;
2601}
2602
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002603Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002604 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002605 const TargetLibraryInfo *TLI,
2606 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002607 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2608 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002609}
2610
Chris Lattner04754262010-04-20 05:32:14 +00002611/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2612/// the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002613static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2614 Value *FalseVal, const Query &Q,
2615 unsigned MaxRecurse) {
Chris Lattner04754262010-04-20 05:32:14 +00002616 // select true, X, Y -> X
2617 // select false, X, Y -> Y
2618 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2619 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002620
Chris Lattner04754262010-04-20 05:32:14 +00002621 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002622 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002623 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002624
Chris Lattner04754262010-04-20 05:32:14 +00002625 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2626 if (isa<Constant>(TrueVal))
2627 return TrueVal;
2628 return FalseVal;
2629 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002630 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2631 return FalseVal;
2632 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2633 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002634
Chris Lattner04754262010-04-20 05:32:14 +00002635 return 0;
2636}
2637
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002638Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Micah Villmow3574eca2012-10-08 16:38:25 +00002639 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002640 const TargetLibraryInfo *TLI,
2641 const DominatorTree *DT) {
2642 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2643 RecursionLimit);
2644}
2645
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002646/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2647/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002648static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002649 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002650 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2651 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2652 if (!PtrTy)
2653 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002654
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002655 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002656 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002657 return Ops[0];
2658
Duncan Sands85bbff62010-11-22 13:42:49 +00002659 if (isa<UndefValue>(Ops[0])) {
2660 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002661 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002662 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002663 return UndefValue::get(GEPTy);
2664 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002665
Jay Foadb9b54eb2011-07-19 15:07:52 +00002666 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002667 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002668 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2669 if (C->isZero())
2670 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002671 // getelementptr P, N -> P if P points to a type of zero size.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002672 if (Q.TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002673 Type *Ty = PtrTy->getElementType();
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002674 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002675 return Ops[0];
2676 }
2677 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002678
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002679 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002680 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002681 if (!isa<Constant>(Ops[i]))
2682 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002683
Jay Foaddab3d292011-07-21 14:31:17 +00002684 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002685}
2686
Micah Villmow3574eca2012-10-08 16:38:25 +00002687Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002688 const TargetLibraryInfo *TLI,
2689 const DominatorTree *DT) {
2690 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2691}
2692
Duncan Sandsdabc2802011-09-05 06:52:48 +00002693/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2694/// can fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002695static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2696 ArrayRef<unsigned> Idxs, const Query &Q,
2697 unsigned) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002698 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2699 if (Constant *CVal = dyn_cast<Constant>(Val))
2700 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2701
2702 // insertvalue x, undef, n -> x
2703 if (match(Val, m_Undef()))
2704 return Agg;
2705
2706 // insertvalue x, (extractvalue y, n), n
2707 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002708 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2709 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002710 // insertvalue undef, (extractvalue y, n), n -> y
2711 if (match(Agg, m_Undef()))
2712 return EV->getAggregateOperand();
2713
2714 // insertvalue y, (extractvalue y, n), n -> y
2715 if (Agg == EV->getAggregateOperand())
2716 return Agg;
2717 }
2718
2719 return 0;
2720}
2721
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002722Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2723 ArrayRef<unsigned> Idxs,
Micah Villmow3574eca2012-10-08 16:38:25 +00002724 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002725 const TargetLibraryInfo *TLI,
2726 const DominatorTree *DT) {
2727 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2728 RecursionLimit);
2729}
2730
Duncan Sandsff103412010-11-17 04:30:22 +00002731/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002732static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sandsff103412010-11-17 04:30:22 +00002733 // If all of the PHI's incoming values are the same then replace the PHI node
2734 // with the common value.
2735 Value *CommonValue = 0;
2736 bool HasUndefInput = false;
2737 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2738 Value *Incoming = PN->getIncomingValue(i);
2739 // If the incoming value is the phi node itself, it can safely be skipped.
2740 if (Incoming == PN) continue;
2741 if (isa<UndefValue>(Incoming)) {
2742 // Remember that we saw an undef value, but otherwise ignore them.
2743 HasUndefInput = true;
2744 continue;
2745 }
2746 if (CommonValue && Incoming != CommonValue)
2747 return 0; // Not the same, bail out.
2748 CommonValue = Incoming;
2749 }
2750
2751 // If CommonValue is null then all of the incoming values were either undef or
2752 // equal to the phi node itself.
2753 if (!CommonValue)
2754 return UndefValue::get(PN->getType());
2755
2756 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2757 // instruction, we cannot return X as the result of the PHI node unless it
2758 // dominates the PHI block.
2759 if (HasUndefInput)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002760 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
Duncan Sandsff103412010-11-17 04:30:22 +00002761
2762 return CommonValue;
2763}
2764
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002765static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2766 if (Constant *C = dyn_cast<Constant>(Op))
2767 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2768
2769 return 0;
2770}
2771
Micah Villmow3574eca2012-10-08 16:38:25 +00002772Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002773 const TargetLibraryInfo *TLI,
2774 const DominatorTree *DT) {
2775 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2776}
2777
Chris Lattnerd06094f2009-11-10 00:55:12 +00002778//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002779
Chris Lattnerd06094f2009-11-10 00:55:12 +00002780/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2781/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002782static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002783 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002784 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002785 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002786 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002787 Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002788 case Instruction::FAdd:
2789 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2790
Chris Lattner81a0dc92011-02-09 17:15:04 +00002791 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002792 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002793 Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002794 case Instruction::FSub:
2795 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2796
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002797 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002798 case Instruction::FMul:
2799 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002800 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2801 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2802 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2803 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2804 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2805 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002806 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002807 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002808 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002809 case Instruction::LShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002810 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002811 case Instruction::AShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002812 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2813 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2814 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2815 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002816 default:
2817 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2818 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2819 Constant *COps[] = {CLHS, CRHS};
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002820 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2821 Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002822 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002823
Duncan Sands566edb02010-12-21 08:49:00 +00002824 // If the operation is associative, try some generic simplifications.
2825 if (Instruction::isAssociative(Opcode))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002826 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00002827 return V;
2828
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002829 // If the operation is with the result of a select instruction check whether
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002830 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002831 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002832 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002833 return V;
2834
2835 // If the operation is with the result of a phi instruction, check whether
2836 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002837 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002838 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002839 return V;
2840
Chris Lattnerd06094f2009-11-10 00:55:12 +00002841 return 0;
2842 }
2843}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002844
Duncan Sands12a86f52010-11-14 11:23:23 +00002845Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002846 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002847 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002848 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002849}
2850
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002851/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2852/// fold the result.
2853static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002854 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002855 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002856 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2857 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002858}
2859
2860Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002861 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002862 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002863 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2864 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002865}
Chris Lattnere3453782009-11-10 01:08:51 +00002866
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002867template <typename IterTy>
Chandler Carruthe949aa12012-12-28 14:23:29 +00002868static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002869 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00002870 Type *Ty = V->getType();
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002871 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
2872 Ty = PTy->getElementType();
2873 FunctionType *FTy = cast<FunctionType>(Ty);
2874
Dan Gohman71d05032011-11-04 18:32:42 +00002875 // call undef -> undef
Chandler Carruthe949aa12012-12-28 14:23:29 +00002876 if (isa<UndefValue>(V))
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002877 return UndefValue::get(FTy->getReturnType());
Dan Gohman71d05032011-11-04 18:32:42 +00002878
Chandler Carruthe949aa12012-12-28 14:23:29 +00002879 Function *F = dyn_cast<Function>(V);
2880 if (!F)
2881 return 0;
2882
2883 if (!canConstantFoldCallTo(F))
2884 return 0;
2885
2886 SmallVector<Constant *, 4> ConstantArgs;
2887 ConstantArgs.reserve(ArgEnd - ArgBegin);
2888 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
2889 Constant *C = dyn_cast<Constant>(*I);
2890 if (!C)
2891 return 0;
2892 ConstantArgs.push_back(C);
2893 }
2894
2895 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman71d05032011-11-04 18:32:42 +00002896}
2897
Chandler Carruthe949aa12012-12-28 14:23:29 +00002898Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002899 User::op_iterator ArgEnd, const DataLayout *TD,
2900 const TargetLibraryInfo *TLI,
2901 const DominatorTree *DT) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00002902 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(TD, TLI, DT),
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002903 RecursionLimit);
2904}
2905
Chandler Carruthe949aa12012-12-28 14:23:29 +00002906Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002907 const DataLayout *TD, const TargetLibraryInfo *TLI,
2908 const DominatorTree *DT) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00002909 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(TD, TLI, DT),
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002910 RecursionLimit);
2911}
2912
Chris Lattnere3453782009-11-10 01:08:51 +00002913/// SimplifyInstruction - See if we can compute a simplified version of this
2914/// instruction. If not, this returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00002915Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002916 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002917 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002918 Value *Result;
2919
Chris Lattnere3453782009-11-10 01:08:51 +00002920 switch (I->getOpcode()) {
2921 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002922 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002923 break;
Michael Ilseman09ee2502012-12-12 00:27:46 +00002924 case Instruction::FAdd:
2925 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
2926 I->getFastMathFlags(), TD, TLI, DT);
2927 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002928 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002929 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2930 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2931 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002932 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002933 break;
Michael Ilseman09ee2502012-12-12 00:27:46 +00002934 case Instruction::FSub:
2935 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
2936 I->getFastMathFlags(), TD, TLI, DT);
2937 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002938 case Instruction::Sub:
2939 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2940 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2941 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002942 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002943 break;
Michael Ilsemaneb61c922012-11-27 00:46:26 +00002944 case Instruction::FMul:
2945 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
2946 I->getFastMathFlags(), TD, TLI, DT);
2947 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002948 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002949 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002950 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002951 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002952 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002953 break;
2954 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002955 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002956 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002957 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002958 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002959 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002960 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002961 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002962 break;
2963 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002964 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002965 break;
2966 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002967 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002968 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002969 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002970 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2971 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2972 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002973 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002974 break;
2975 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002976 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2977 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002978 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002979 break;
2980 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002981 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2982 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002983 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002984 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002985 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002986 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002987 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002988 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002989 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002990 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002991 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002992 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002993 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002994 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002995 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002996 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002997 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002998 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002999 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003000 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003001 break;
Chris Lattner04754262010-04-20 05:32:14 +00003002 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00003003 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003004 I->getOperand(2), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003005 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00003006 case Instruction::GetElementPtr: {
3007 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003008 Result = SimplifyGEPInst(Ops, TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003009 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00003010 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00003011 case Instruction::InsertValue: {
3012 InsertValueInst *IV = cast<InsertValueInst>(I);
3013 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3014 IV->getInsertedValueOperand(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003015 IV->getIndices(), TD, TLI, DT);
Duncan Sandsdabc2802011-09-05 06:52:48 +00003016 break;
3017 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00003018 case Instruction::PHI:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003019 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
Duncan Sandsd261dc62010-11-17 08:35:29 +00003020 break;
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003021 case Instruction::Call: {
3022 CallSite CS(cast<CallInst>(I));
3023 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3024 TD, TLI, DT);
Dan Gohman71d05032011-11-04 18:32:42 +00003025 break;
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003026 }
Duncan Sandsbd0fe562012-03-13 14:07:05 +00003027 case Instruction::Trunc:
3028 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
3029 break;
Chris Lattnere3453782009-11-10 01:08:51 +00003030 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00003031
3032 /// If called on unreachable code, the above logic may report that the
3033 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00003034 /// detecting that case here, returning a safe value instead.
3035 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00003036}
3037
Chandler Carruth6b980542012-03-24 21:11:24 +00003038/// \brief Implementation of recursive simplification through an instructions
3039/// uses.
Chris Lattner40d8c282009-11-10 22:26:15 +00003040///
Chandler Carruth6b980542012-03-24 21:11:24 +00003041/// This is the common implementation of the recursive simplification routines.
3042/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3043/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3044/// instructions to process and attempt to simplify it using
3045/// InstructionSimplify.
3046///
3047/// This routine returns 'true' only when *it* simplifies something. The passed
3048/// in simplified value does not count toward this.
3049static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00003050 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003051 const TargetLibraryInfo *TLI,
3052 const DominatorTree *DT) {
3053 bool Simplified = false;
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003054 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands12a86f52010-11-14 11:23:23 +00003055
Chandler Carruth6b980542012-03-24 21:11:24 +00003056 // If we have an explicit value to collapse to, do that round of the
3057 // simplification loop by hand initially.
3058 if (SimpleV) {
3059 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3060 ++UI)
Chandler Carruthc5b785b2012-03-24 22:34:23 +00003061 if (*UI != I)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003062 Worklist.insert(cast<Instruction>(*UI));
Duncan Sands12a86f52010-11-14 11:23:23 +00003063
Chandler Carruth6b980542012-03-24 21:11:24 +00003064 // Replace the instruction with its simplified value.
3065 I->replaceAllUsesWith(SimpleV);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00003066
Chandler Carruth6b980542012-03-24 21:11:24 +00003067 // Gracefully handle edge cases where the instruction is not wired into any
3068 // parent block.
3069 if (I->getParent())
3070 I->eraseFromParent();
3071 } else {
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003072 Worklist.insert(I);
Chris Lattner40d8c282009-11-10 22:26:15 +00003073 }
Duncan Sands12a86f52010-11-14 11:23:23 +00003074
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003075 // Note that we must test the size on each iteration, the worklist can grow.
3076 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3077 I = Worklist[Idx];
Duncan Sands12a86f52010-11-14 11:23:23 +00003078
Chandler Carruth6b980542012-03-24 21:11:24 +00003079 // See if this instruction simplifies.
3080 SimpleV = SimplifyInstruction(I, TD, TLI, DT);
3081 if (!SimpleV)
3082 continue;
3083
3084 Simplified = true;
3085
3086 // Stash away all the uses of the old instruction so we can check them for
3087 // recursive simplifications after a RAUW. This is cheaper than checking all
3088 // uses of To on the recursive step in most cases.
3089 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3090 ++UI)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003091 Worklist.insert(cast<Instruction>(*UI));
Chandler Carruth6b980542012-03-24 21:11:24 +00003092
3093 // Replace the instruction with its simplified value.
3094 I->replaceAllUsesWith(SimpleV);
3095
3096 // Gracefully handle edge cases where the instruction is not wired into any
3097 // parent block.
3098 if (I->getParent())
3099 I->eraseFromParent();
3100 }
3101 return Simplified;
3102}
3103
3104bool llvm::recursivelySimplifyInstruction(Instruction *I,
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 return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
3109}
3110
3111bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00003112 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003113 const TargetLibraryInfo *TLI,
3114 const DominatorTree *DT) {
3115 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3116 assert(SimpleV && "Must provide a simplified value.");
3117 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
Chris Lattner40d8c282009-11-10 22:26:15 +00003118}