blob: d66ecca928aa854e66d5f76113d81557e95433cd [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"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000024#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000025#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000026#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +000027#include "llvm/Analysis/MemoryBuiltins.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.
Benjamin Kramerd9f32c22013-02-01 15:21:10 +0000670static Constant *stripAndComputeConstantOffsets(const DataLayout *TD,
671 Value *&V) {
672 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000673
Dan Gohman3e3de562013-01-31 02:50:36 +0000674 // Without DataLayout, just be conservative for now. Theoretically, more could
675 // be done in this case.
676 if (!TD)
677 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
678
679 unsigned IntPtrWidth = TD->getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000680 APInt Offset = APInt::getNullValue(IntPtrWidth);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000681
682 // Even though we don't look through PHI nodes, we could be called on an
683 // instruction in an unreachable block, which may be on a cycle.
684 SmallPtrSet<Value *, 4> Visited;
685 Visited.insert(V);
686 do {
687 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Dan Gohman3e3de562013-01-31 02:50:36 +0000688 if (!GEP->isInBounds() || !GEP->accumulateConstantOffset(*TD, Offset))
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000689 break;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000690 V = GEP->getPointerOperand();
691 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
692 V = cast<Operator>(V)->getOperand(0);
693 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
694 if (GA->mayBeOverridden())
695 break;
696 V = GA->getAliasee();
697 } else {
698 break;
699 }
Benjamin Kramerd9f32c22013-02-01 15:21:10 +0000700 assert(V->getType()->getScalarType()->isPointerTy() &&
701 "Unexpected operand type!");
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000702 } while (Visited.insert(V));
703
Dan Gohman3e3de562013-01-31 02:50:36 +0000704 Type *IntPtrTy = TD->getIntPtrType(V->getContext());
Benjamin Kramerd9f32c22013-02-01 15:21:10 +0000705 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
706 if (V->getType()->isVectorTy())
707 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
708 OffsetIntPtr);
709 return OffsetIntPtr;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000710}
711
712/// \brief Compute the constant difference between two pointer values.
713/// If the difference is not a constant, returns zero.
Dan Gohman3e3de562013-01-31 02:50:36 +0000714static Constant *computePointerDifference(const DataLayout *TD,
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000715 Value *LHS, Value *RHS) {
716 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000717 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000718
719 // If LHS and RHS are not related via constant offsets to the same base
720 // value, there is nothing we can do here.
721 if (LHS != RHS)
722 return 0;
723
724 // Otherwise, the difference of LHS - RHS can be computed as:
725 // LHS - RHS
726 // = (LHSOffset + Base) - (RHSOffset + Base)
727 // = LHSOffset - RHSOffset
728 return ConstantExpr::getSub(LHSOffset, RHSOffset);
729}
730
Duncan Sandsfea3b212010-12-15 14:07:39 +0000731/// SimplifySubInst - Given operands for a Sub, see if we can
732/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000733static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000734 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000735 if (Constant *CLHS = dyn_cast<Constant>(Op0))
736 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
737 Constant *Ops[] = { CLHS, CRHS };
738 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000739 Ops, Q.TD, Q.TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000740 }
741
742 // X - undef -> undef
743 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000744 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000745 return UndefValue::get(Op0->getType());
746
747 // X - 0 -> X
748 if (match(Op1, m_Zero()))
749 return Op0;
750
751 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000752 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000753 return Constant::getNullValue(Op0->getType());
754
Duncan Sandsfe02c692011-01-18 09:24:58 +0000755 // (X*2) - X -> X
756 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000757 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000758 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
759 match(Op0, m_Shl(m_Specific(Op1), m_One())))
760 return Op1;
761
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000762 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
763 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
764 Value *Y = 0, *Z = Op1;
765 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
766 // See if "V === Y - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000767 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000768 // It does! Now see if "X + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000769 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000770 // It does, we successfully reassociated!
771 ++NumReassoc;
772 return W;
773 }
774 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000775 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000776 // It does! Now see if "Y + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000777 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000778 // It does, we successfully reassociated!
779 ++NumReassoc;
780 return W;
781 }
782 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000783
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000784 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
785 // For example, X - (X + 1) -> -1
786 X = Op0;
787 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
788 // See if "V === X - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000789 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000790 // It does! Now see if "V - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000791 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000792 // It does, we successfully reassociated!
793 ++NumReassoc;
794 return W;
795 }
796 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000797 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000798 // It does! Now see if "V - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000799 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000800 // It does, we successfully reassociated!
801 ++NumReassoc;
802 return W;
803 }
804 }
805
806 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
807 // For example, X - (X - Y) -> Y.
808 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000809 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
810 // See if "V === Z - X" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000811 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000812 // It does! Now see if "V + Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000813 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsc087e202011-01-14 15:26:10 +0000814 // It does, we successfully reassociated!
815 ++NumReassoc;
816 return W;
817 }
818
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000819 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
820 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
821 match(Op1, m_Trunc(m_Value(Y))))
822 if (X->getType() == Y->getType())
823 // See if "V === X - Y" simplifies.
824 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
825 // It does! Now see if "trunc V" simplifies.
826 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
827 // It does, return the simplified "trunc V".
828 return W;
829
830 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman3e3de562013-01-31 02:50:36 +0000831 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000832 match(Op1, m_PtrToInt(m_Value(Y))))
Dan Gohman3e3de562013-01-31 02:50:36 +0000833 if (Constant *Result = computePointerDifference(Q.TD, X, Y))
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000834 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
835
Duncan Sands3421d902010-12-21 13:32:22 +0000836 // Mul distributes over Sub. Try some generic simplifications based on this.
837 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000838 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000839 return V;
840
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000841 // i1 sub -> xor.
842 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000843 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000844 return V;
845
Duncan Sandsfea3b212010-12-15 14:07:39 +0000846 // Threading Sub over selects and phi nodes is pointless, so don't bother.
847 // Threading over the select in "A - select(cond, B, C)" means evaluating
848 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
849 // only if B and C are equal. If B and C are equal then (since we assume
850 // that operands have already been simplified) "select(cond, B, C)" should
851 // have been simplified to the common value of B and C already. Analysing
852 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
853 // for threading over phi nodes.
854
855 return 0;
856}
857
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000858Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +0000859 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000860 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000861 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
862 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000863}
864
Michael Ilseman09ee2502012-12-12 00:27:46 +0000865/// Given operands for an FAdd, see if we can fold the result. If not, this
866/// returns null.
867static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
868 const Query &Q, unsigned MaxRecurse) {
869 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
870 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
871 Constant *Ops[] = { CLHS, CRHS };
872 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
873 Ops, Q.TD, Q.TLI);
874 }
875
876 // Canonicalize the constant to the RHS.
877 std::swap(Op0, Op1);
878 }
879
880 // fadd X, -0 ==> X
881 if (match(Op1, m_NegZero()))
882 return Op0;
883
884 // fadd X, 0 ==> X, when we know X is not -0
885 if (match(Op1, m_Zero()) &&
886 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
887 return Op0;
888
889 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
890 // where nnan and ninf have to occur at least once somewhere in this
891 // expression
892 Value *SubOp = 0;
893 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
894 SubOp = Op1;
895 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
896 SubOp = Op0;
897 if (SubOp) {
898 Instruction *FSub = cast<Instruction>(SubOp);
899 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
900 (FMF.noInfs() || FSub->hasNoInfs()))
901 return Constant::getNullValue(Op0->getType());
902 }
903
904 return 0;
905}
906
907/// Given operands for an FSub, see if we can fold the result. If not, this
908/// returns null.
909static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
910 const Query &Q, unsigned MaxRecurse) {
911 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
912 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
913 Constant *Ops[] = { CLHS, CRHS };
914 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
915 Ops, Q.TD, Q.TLI);
916 }
917 }
918
919 // fsub X, 0 ==> X
920 if (match(Op1, m_Zero()))
921 return Op0;
922
923 // fsub X, -0 ==> X, when we know X is not -0
924 if (match(Op1, m_NegZero()) &&
925 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
926 return Op0;
927
928 // fsub 0, (fsub -0.0, X) ==> X
929 Value *X;
930 if (match(Op0, m_AnyZero())) {
931 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
932 return X;
933 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
934 return X;
935 }
936
937 // fsub nnan ninf x, x ==> 0.0
938 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
939 return Constant::getNullValue(Op0->getType());
940
941 return 0;
942}
943
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000944/// Given the operands for an FMul, see if we can fold the result
945static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
946 FastMathFlags FMF,
947 const Query &Q,
948 unsigned MaxRecurse) {
949 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
950 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
951 Constant *Ops[] = { CLHS, CRHS };
952 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
953 Ops, Q.TD, Q.TLI);
954 }
Michael Ilseman09ee2502012-12-12 00:27:46 +0000955
956 // Canonicalize the constant to the RHS.
957 std::swap(Op0, Op1);
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000958 }
959
Michael Ilseman09ee2502012-12-12 00:27:46 +0000960 // fmul X, 1.0 ==> X
961 if (match(Op1, m_FPOne()))
962 return Op0;
963
964 // fmul nnan nsz X, 0 ==> 0
965 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
966 return Op1;
Michael Ilsemaneb61c922012-11-27 00:46:26 +0000967
968 return 0;
969}
970
Duncan Sands82fdab32010-12-21 14:00:22 +0000971/// SimplifyMulInst - Given operands for a Mul, see if we can
972/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000973static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
974 unsigned MaxRecurse) {
Duncan Sands82fdab32010-12-21 14:00:22 +0000975 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
976 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
977 Constant *Ops[] = { CLHS, CRHS };
978 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000979 Ops, Q.TD, Q.TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000980 }
981
982 // Canonicalize the constant to the RHS.
983 std::swap(Op0, Op1);
984 }
985
986 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000987 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000988 return Constant::getNullValue(Op0->getType());
989
990 // X * 0 -> 0
991 if (match(Op1, m_Zero()))
992 return Op1;
993
994 // X * 1 -> X
995 if (match(Op1, m_One()))
996 return Op0;
997
Duncan Sands1895e982011-01-30 18:03:50 +0000998 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000999 Value *X = 0;
1000 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
1001 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
1002 return X;
Duncan Sands1895e982011-01-30 18:03:50 +00001003
Nick Lewycky54138802011-01-29 19:55:23 +00001004 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +00001005 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001006 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +00001007 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +00001008
1009 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001010 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001011 MaxRecurse))
1012 return V;
1013
1014 // Mul distributes over Add. Try some generic simplifications based on this.
1015 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001016 Q, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +00001017 return V;
1018
1019 // If the operation is with the result of a select instruction, check whether
1020 // operating on either branch of the select always yields the same value.
1021 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001022 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001023 MaxRecurse))
1024 return V;
1025
1026 // If the operation is with the result of a phi instruction, check whether
1027 // operating on all incoming values of the phi always yields the same value.
1028 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001029 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +00001030 MaxRecurse))
1031 return V;
1032
1033 return 0;
1034}
1035
Michael Ilseman09ee2502012-12-12 00:27:46 +00001036Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1037 const DataLayout *TD, const TargetLibraryInfo *TLI,
1038 const DominatorTree *DT) {
1039 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1040}
1041
1042Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1043 const DataLayout *TD, const TargetLibraryInfo *TLI,
1044 const DominatorTree *DT) {
1045 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1046}
1047
Michael Ilsemaneb61c922012-11-27 00:46:26 +00001048Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
1049 FastMathFlags FMF,
1050 const DataLayout *TD,
1051 const TargetLibraryInfo *TLI,
1052 const DominatorTree *DT) {
1053 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (TD, TLI, DT), RecursionLimit);
1054}
1055
Micah Villmow3574eca2012-10-08 16:38:25 +00001056Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001057 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +00001058 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001059 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +00001060}
1061
Duncan Sands593faa52011-01-28 16:51:11 +00001062/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1063/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +00001064static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001065 const Query &Q, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +00001066 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1067 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1068 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001069 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sands593faa52011-01-28 16:51:11 +00001070 }
1071 }
1072
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001073 bool isSigned = Opcode == Instruction::SDiv;
1074
Duncan Sands593faa52011-01-28 16:51:11 +00001075 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001076 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001077 return Op1;
1078
1079 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001080 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001081 return Constant::getNullValue(Op0->getType());
1082
1083 // 0 / X -> 0, we don't need to preserve faults!
1084 if (match(Op0, m_Zero()))
1085 return Op0;
1086
1087 // X / 1 -> X
1088 if (match(Op1, m_One()))
1089 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +00001090
1091 if (Op0->getType()->isIntegerTy(1))
1092 // It can't be division by zero, hence it must be division by one.
1093 return Op0;
1094
1095 // X / X -> 1
1096 if (Op0 == Op1)
1097 return ConstantInt::get(Op0->getType(), 1);
1098
1099 // (X * Y) / Y -> X if the multiplication does not overflow.
1100 Value *X = 0, *Y = 0;
1101 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1102 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +00001103 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +00001104 // If the Mul knows it does not overflow, then we are good to go.
1105 if ((isSigned && Mul->hasNoSignedWrap()) ||
1106 (!isSigned && Mul->hasNoUnsignedWrap()))
1107 return X;
Duncan Sands593faa52011-01-28 16:51:11 +00001108 // If X has the form X = A / Y then X * Y cannot overflow.
1109 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1110 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1111 return X;
1112 }
1113
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001114 // (X rem Y) / Y -> 0
1115 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1116 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1117 return Constant::getNullValue(Op0->getType());
1118
1119 // If the operation is with the result of a select instruction, check whether
1120 // operating on either branch of the select always yields the same value.
1121 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001122 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001123 return V;
1124
1125 // If the operation is with the result of a phi instruction, check whether
1126 // operating on all incoming values of the phi always yields the same value.
1127 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001128 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001129 return V;
1130
Duncan Sands593faa52011-01-28 16:51:11 +00001131 return 0;
1132}
1133
1134/// SimplifySDivInst - Given operands for an SDiv, see if we can
1135/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001136static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1137 unsigned MaxRecurse) {
1138 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001139 return V;
1140
Duncan Sands593faa52011-01-28 16:51:11 +00001141 return 0;
1142}
1143
Micah Villmow3574eca2012-10-08 16:38:25 +00001144Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001145 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001146 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001147 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001148}
1149
1150/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1151/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001152static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1153 unsigned MaxRecurse) {
1154 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001155 return V;
1156
Duncan Sands593faa52011-01-28 16:51:11 +00001157 return 0;
1158}
1159
Micah Villmow3574eca2012-10-08 16:38:25 +00001160Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001161 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001162 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001163 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001164}
1165
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001166static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1167 unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001168 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001169 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001170 return Op0;
1171
1172 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001173 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001174 return Op1;
1175
1176 return 0;
1177}
1178
Micah Villmow3574eca2012-10-08 16:38:25 +00001179Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001180 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001181 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001182 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001183}
1184
Duncan Sandsf24ed772011-05-02 16:27:02 +00001185/// SimplifyRem - Given operands for an SRem or URem, see if we can
1186/// fold the result. If not, this returns null.
1187static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001188 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001189 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1190 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1191 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001192 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001193 }
1194 }
1195
Duncan Sandsf24ed772011-05-02 16:27:02 +00001196 // X % undef -> undef
1197 if (match(Op1, m_Undef()))
1198 return Op1;
1199
1200 // undef % X -> 0
1201 if (match(Op0, m_Undef()))
1202 return Constant::getNullValue(Op0->getType());
1203
1204 // 0 % X -> 0, we don't need to preserve faults!
1205 if (match(Op0, m_Zero()))
1206 return Op0;
1207
1208 // X % 0 -> undef, we don't need to preserve faults!
1209 if (match(Op1, m_Zero()))
1210 return UndefValue::get(Op0->getType());
1211
1212 // X % 1 -> 0
1213 if (match(Op1, m_One()))
1214 return Constant::getNullValue(Op0->getType());
1215
1216 if (Op0->getType()->isIntegerTy(1))
1217 // It can't be remainder by zero, hence it must be remainder by one.
1218 return Constant::getNullValue(Op0->getType());
1219
1220 // X % X -> 0
1221 if (Op0 == Op1)
1222 return Constant::getNullValue(Op0->getType());
1223
1224 // If the operation is with the result of a select instruction, check whether
1225 // operating on either branch of the select always yields the same value.
1226 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001227 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001228 return V;
1229
1230 // If the operation is with the result of a phi instruction, check whether
1231 // operating on all incoming values of the phi always yields the same value.
1232 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001233 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001234 return V;
1235
1236 return 0;
1237}
1238
1239/// SimplifySRemInst - Given operands for an SRem, see if we can
1240/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001241static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1242 unsigned MaxRecurse) {
1243 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001244 return V;
1245
1246 return 0;
1247}
1248
Micah Villmow3574eca2012-10-08 16:38:25 +00001249Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001250 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001251 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001252 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001253}
1254
1255/// SimplifyURemInst - Given operands for a URem, see if we can
1256/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001257static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001258 unsigned MaxRecurse) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001259 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001260 return V;
1261
1262 return 0;
1263}
1264
Micah Villmow3574eca2012-10-08 16:38:25 +00001265Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001266 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001267 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001268 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001269}
1270
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001271static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +00001272 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001273 // undef % X -> undef (the undef could be a snan).
1274 if (match(Op0, m_Undef()))
1275 return Op0;
1276
1277 // X % undef -> undef
1278 if (match(Op1, m_Undef()))
1279 return Op1;
1280
1281 return 0;
1282}
1283
Micah Villmow3574eca2012-10-08 16:38:25 +00001284Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001285 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001286 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001287 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001288}
1289
Duncan Sandscf80bc12011-01-14 14:44:12 +00001290/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001291/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001292static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001293 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001294 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1295 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1296 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001297 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001298 }
1299 }
1300
Duncan Sandscf80bc12011-01-14 14:44:12 +00001301 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001302 if (match(Op0, m_Zero()))
1303 return Op0;
1304
Duncan Sandscf80bc12011-01-14 14:44:12 +00001305 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001306 if (match(Op1, m_Zero()))
1307 return Op0;
1308
Duncan Sandscf80bc12011-01-14 14:44:12 +00001309 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001310 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001311 return Op1;
1312
1313 // Shifting by the bitwidth or more is undefined.
1314 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1315 if (CI->getValue().getLimitedValue() >=
1316 Op0->getType()->getScalarSizeInBits())
1317 return UndefValue::get(Op0->getType());
1318
Duncan Sandscf80bc12011-01-14 14:44:12 +00001319 // If the operation is with the result of a select instruction, check whether
1320 // operating on either branch of the select always yields the same value.
1321 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001322 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001323 return V;
1324
1325 // If the operation is with the result of a phi instruction, check whether
1326 // operating on all incoming values of the phi always yields the same value.
1327 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001328 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001329 return V;
1330
1331 return 0;
1332}
1333
1334/// SimplifyShlInst - Given operands for an Shl, see if we can
1335/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001336static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001337 const Query &Q, unsigned MaxRecurse) {
1338 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001339 return V;
1340
1341 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001342 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001343 return Constant::getNullValue(Op0->getType());
1344
Chris Lattner81a0dc92011-02-09 17:15:04 +00001345 // (X >> A) << A -> X
1346 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001347 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001348 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001349 return 0;
1350}
1351
Chris Lattner81a0dc92011-02-09 17:15:04 +00001352Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Micah Villmow3574eca2012-10-08 16:38:25 +00001353 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00001354 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001355 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1356 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001357}
1358
1359/// SimplifyLShrInst - Given operands for an LShr, see if we can
1360/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001361static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001362 const Query &Q, unsigned MaxRecurse) {
1363 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001364 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001365
David Majnemer8c5c6f02013-07-09 22:01:22 +00001366 // X >> X -> 0
1367 if (Op0 == Op1)
1368 return Constant::getNullValue(Op0->getType());
1369
Duncan Sandsc43cee32011-01-14 00:37:45 +00001370 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001371 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001372 return Constant::getNullValue(Op0->getType());
1373
Chris Lattner81a0dc92011-02-09 17:15:04 +00001374 // (X << A) >> A -> X
1375 Value *X;
1376 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1377 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1378 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001379
Duncan Sandsc43cee32011-01-14 00:37:45 +00001380 return 0;
1381}
1382
Chris Lattner81a0dc92011-02-09 17:15:04 +00001383Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001384 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001385 const TargetLibraryInfo *TLI,
1386 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001387 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1388 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001389}
1390
1391/// SimplifyAShrInst - Given operands for an AShr, see if we can
1392/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001393static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001394 const Query &Q, unsigned MaxRecurse) {
1395 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001396 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001397
David Majnemer8c5c6f02013-07-09 22:01:22 +00001398 // X >> X -> 0
1399 if (Op0 == Op1)
1400 return Constant::getNullValue(Op0->getType());
1401
Duncan Sandsc43cee32011-01-14 00:37:45 +00001402 // all ones >>a X -> all ones
1403 if (match(Op0, m_AllOnes()))
1404 return Op0;
1405
1406 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001407 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001408 return Constant::getAllOnesValue(Op0->getType());
1409
Chris Lattner81a0dc92011-02-09 17:15:04 +00001410 // (X << A) >> A -> X
1411 Value *X;
1412 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1413 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1414 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001415
Duncan Sandsc43cee32011-01-14 00:37:45 +00001416 return 0;
1417}
1418
Chris Lattner81a0dc92011-02-09 17:15:04 +00001419Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Micah Villmow3574eca2012-10-08 16:38:25 +00001420 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001421 const TargetLibraryInfo *TLI,
1422 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001423 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1424 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001425}
1426
Chris Lattnerd06094f2009-11-10 00:55:12 +00001427/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001428/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001429static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001430 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001431 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1432 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1433 Constant *Ops[] = { CLHS, CRHS };
1434 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001435 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001436 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001437
Chris Lattnerd06094f2009-11-10 00:55:12 +00001438 // Canonicalize the constant to the RHS.
1439 std::swap(Op0, Op1);
1440 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001441
Chris Lattnerd06094f2009-11-10 00:55:12 +00001442 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001443 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001444 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001445
Chris Lattnerd06094f2009-11-10 00:55:12 +00001446 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001447 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001448 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001449
Duncan Sands2b749872010-11-17 18:52:15 +00001450 // X & 0 = 0
1451 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001452 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001453
Duncan Sands2b749872010-11-17 18:52:15 +00001454 // X & -1 = X
1455 if (match(Op1, m_AllOnes()))
1456 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001457
Chris Lattnerd06094f2009-11-10 00:55:12 +00001458 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001459 if (match(Op0, m_Not(m_Specific(Op1))) ||
1460 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001461 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001462
Chris Lattnerd06094f2009-11-10 00:55:12 +00001463 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001464 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001465 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001466 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001467 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001468
Chris Lattnerd06094f2009-11-10 00:55:12 +00001469 // A & (A | ?) = A
1470 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001471 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001472 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001473
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001474 // A & (-A) = A if A is a power of two or zero.
1475 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1476 match(Op1, m_Neg(m_Specific(Op0)))) {
Rafael Espindoladbaa2372012-12-13 03:37:24 +00001477 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001478 return Op0;
Rafael Espindoladbaa2372012-12-13 03:37:24 +00001479 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001480 return Op1;
1481 }
1482
Duncan Sands566edb02010-12-21 08:49:00 +00001483 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001484 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1485 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001486 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001487
Duncan Sands3421d902010-12-21 13:32:22 +00001488 // And distributes over Or. Try some generic simplifications based on this.
1489 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001490 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001491 return V;
1492
1493 // And distributes over Xor. Try some generic simplifications based on this.
1494 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001495 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001496 return V;
1497
1498 // Or distributes over And. Try some generic simplifications based on this.
1499 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001500 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001501 return V;
1502
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001503 // If the operation is with the result of a select instruction, check whether
1504 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001505 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001506 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1507 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001508 return V;
1509
1510 // If the operation is with the result of a phi instruction, check whether
1511 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001512 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001513 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001514 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001515 return V;
1516
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001517 return 0;
1518}
1519
Micah Villmow3574eca2012-10-08 16:38:25 +00001520Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001521 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001522 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001523 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001524}
1525
Chris Lattnerd06094f2009-11-10 00:55:12 +00001526/// SimplifyOrInst - Given operands for an Or, see if we can
1527/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001528static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1529 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001530 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1531 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1532 Constant *Ops[] = { CLHS, CRHS };
1533 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001534 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001535 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001536
Chris Lattnerd06094f2009-11-10 00:55:12 +00001537 // Canonicalize the constant to the RHS.
1538 std::swap(Op0, Op1);
1539 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001540
Chris Lattnerd06094f2009-11-10 00:55:12 +00001541 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001542 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001543 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001544
Chris Lattnerd06094f2009-11-10 00:55:12 +00001545 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001546 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001547 return Op0;
1548
Duncan Sands2b749872010-11-17 18:52:15 +00001549 // X | 0 = X
1550 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001551 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001552
Duncan Sands2b749872010-11-17 18:52:15 +00001553 // X | -1 = -1
1554 if (match(Op1, m_AllOnes()))
1555 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001556
Chris Lattnerd06094f2009-11-10 00:55:12 +00001557 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001558 if (match(Op0, m_Not(m_Specific(Op1))) ||
1559 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001560 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001561
Chris Lattnerd06094f2009-11-10 00:55:12 +00001562 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001563 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001564 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001565 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001566 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001567
Chris Lattnerd06094f2009-11-10 00:55:12 +00001568 // A | (A & ?) = A
1569 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001570 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001571 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001572
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001573 // ~(A & ?) | A = -1
1574 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1575 (A == Op1 || B == Op1))
1576 return Constant::getAllOnesValue(Op1->getType());
1577
1578 // A | ~(A & ?) = -1
1579 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1580 (A == Op0 || B == Op0))
1581 return Constant::getAllOnesValue(Op0->getType());
1582
Duncan Sands566edb02010-12-21 08:49:00 +00001583 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001584 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1585 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001586 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001587
Duncan Sands3421d902010-12-21 13:32:22 +00001588 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001589 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1590 MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001591 return V;
1592
1593 // And distributes over Or. Try some generic simplifications based on this.
1594 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001595 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001596 return V;
1597
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001598 // If the operation is with the result of a select instruction, check whether
1599 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001600 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001601 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001602 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001603 return V;
1604
1605 // If the operation is with the result of a phi instruction, check whether
1606 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001607 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001608 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001609 return V;
1610
Chris Lattnerd06094f2009-11-10 00:55:12 +00001611 return 0;
1612}
1613
Micah Villmow3574eca2012-10-08 16:38:25 +00001614Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001615 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001616 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001617 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001618}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001619
Duncan Sands2b749872010-11-17 18:52:15 +00001620/// SimplifyXorInst - Given operands for a Xor, see if we can
1621/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001622static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1623 unsigned MaxRecurse) {
Duncan Sands2b749872010-11-17 18:52:15 +00001624 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1625 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1626 Constant *Ops[] = { CLHS, CRHS };
1627 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001628 Ops, Q.TD, Q.TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001629 }
1630
1631 // Canonicalize the constant to the RHS.
1632 std::swap(Op0, Op1);
1633 }
1634
1635 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001636 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001637 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001638
1639 // A ^ 0 = A
1640 if (match(Op1, m_Zero()))
1641 return Op0;
1642
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001643 // A ^ A = 0
1644 if (Op0 == Op1)
1645 return Constant::getNullValue(Op0->getType());
1646
Duncan Sands2b749872010-11-17 18:52:15 +00001647 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001648 if (match(Op0, m_Not(m_Specific(Op1))) ||
1649 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001650 return Constant::getAllOnesValue(Op0->getType());
1651
Duncan Sands566edb02010-12-21 08:49:00 +00001652 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001653 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1654 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001655 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001656
Duncan Sands3421d902010-12-21 13:32:22 +00001657 // And distributes over Xor. Try some generic simplifications based on this.
1658 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001659 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001660 return V;
1661
Duncan Sands87689cf2010-11-19 09:20:39 +00001662 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1663 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1664 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1665 // only if B and C are equal. If B and C are equal then (since we assume
1666 // that operands have already been simplified) "select(cond, B, C)" should
1667 // have been simplified to the common value of B and C already. Analysing
1668 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1669 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001670
1671 return 0;
1672}
1673
Micah Villmow3574eca2012-10-08 16:38:25 +00001674Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001675 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001676 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001677 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001678}
1679
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001680static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001681 return CmpInst::makeCmpResultType(Op->getType());
1682}
1683
Duncan Sandse864b5b2011-05-07 16:56:49 +00001684/// ExtractEquivalentCondition - Rummage around inside V looking for something
1685/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1686/// otherwise return null. Helper function for analyzing max/min idioms.
1687static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1688 Value *LHS, Value *RHS) {
1689 SelectInst *SI = dyn_cast<SelectInst>(V);
1690 if (!SI)
1691 return 0;
1692 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1693 if (!Cmp)
1694 return 0;
1695 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1696 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1697 return Cmp;
1698 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1699 LHS == CmpRHS && RHS == CmpLHS)
1700 return Cmp;
1701 return 0;
1702}
1703
Dan Gohman901261d2013-02-01 00:49:06 +00001704// A significant optimization not implemented here is assuming that alloca
1705// addresses are not equal to incoming argument values. They don't *alias*,
1706// as we say, but that doesn't mean they aren't equal, so we take a
1707// conservative approach.
1708//
1709// This is inspired in part by C++11 5.10p1:
1710// "Two pointers of the same type compare equal if and only if they are both
1711// null, both point to the same function, or both represent the same
1712// address."
1713//
1714// This is pretty permissive.
1715//
1716// It's also partly due to C11 6.5.9p6:
1717// "Two pointers compare equal if and only if both are null pointers, both are
1718// pointers to the same object (including a pointer to an object and a
1719// subobject at its beginning) or function, both are pointers to one past the
1720// last element of the same array object, or one is a pointer to one past the
1721// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi92c37422013-04-08 23:05:21 +00001722// different array object that happens to immediately follow the first array
Dan Gohman901261d2013-02-01 00:49:06 +00001723// object in the address space.)
1724//
1725// C11's version is more restrictive, however there's no reason why an argument
1726// couldn't be a one-past-the-end value for a stack object in the caller and be
1727// equal to the beginning of a stack object in the callee.
1728//
1729// If the C and C++ standards are ever made sufficiently restrictive in this
1730// area, it may be possible to update LLVM's semantics accordingly and reinstate
1731// this optimization.
Dan Gohman3e3de562013-01-31 02:50:36 +00001732static Constant *computePointerICmp(const DataLayout *TD,
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001733 const TargetLibraryInfo *TLI,
Chandler Carruth58725a62012-03-25 21:28:14 +00001734 CmpInst::Predicate Pred,
1735 Value *LHS, Value *RHS) {
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001736 // First, skip past any trivial no-ops.
1737 LHS = LHS->stripPointerCasts();
1738 RHS = RHS->stripPointerCasts();
1739
1740 // A non-null pointer is not equal to a null pointer.
1741 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
1742 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1743 return ConstantInt::get(GetCompareTy(LHS),
1744 !CmpInst::isTrueWhenEqual(Pred));
1745
Chandler Carruth58725a62012-03-25 21:28:14 +00001746 // We can only fold certain predicates on pointer comparisons.
1747 switch (Pred) {
1748 default:
1749 return 0;
1750
1751 // Equality comaprisons are easy to fold.
1752 case CmpInst::ICMP_EQ:
1753 case CmpInst::ICMP_NE:
1754 break;
1755
1756 // We can only handle unsigned relational comparisons because 'inbounds' on
1757 // a GEP only protects against unsigned wrapping.
1758 case CmpInst::ICMP_UGT:
1759 case CmpInst::ICMP_UGE:
1760 case CmpInst::ICMP_ULT:
1761 case CmpInst::ICMP_ULE:
1762 // However, we have to switch them to their signed variants to handle
1763 // negative indices from the base pointer.
1764 Pred = ICmpInst::getSignedPredicate(Pred);
1765 break;
1766 }
1767
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001768 // Strip off any constant offsets so that we can reason about them.
1769 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1770 // here and compare base addresses like AliasAnalysis does, however there are
1771 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1772 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1773 // doesn't need to guarantee pointer inequality when it says NoAlias.
Benjamin Kramerd9f32c22013-02-01 15:21:10 +00001774 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
1775 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
Chandler Carruth58725a62012-03-25 21:28:14 +00001776
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001777 // If LHS and RHS are related via constant offsets to the same base
1778 // value, we can replace it with an icmp which just compares the offsets.
1779 if (LHS == RHS)
1780 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth58725a62012-03-25 21:28:14 +00001781
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001782 // Various optimizations for (in)equality comparisons.
1783 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1784 // Different non-empty allocations that exist at the same time have
1785 // different addresses (if the program can tell). Global variables always
1786 // exist, so they always exist during the lifetime of each other and all
1787 // allocas. Two different allocas usually have different addresses...
1788 //
1789 // However, if there's an @llvm.stackrestore dynamically in between two
1790 // allocas, they may have the same address. It's tempting to reduce the
1791 // scope of the problem by only looking at *static* allocas here. That would
1792 // cover the majority of allocas while significantly reducing the likelihood
1793 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1794 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1795 // an entry block. Also, if we have a block that's not attached to a
1796 // function, we can't tell if it's "static" under the current definition.
1797 // Theoretically, this problem could be fixed by creating a new kind of
1798 // instruction kind specifically for static allocas. Such a new instruction
1799 // could be required to be at the top of the entry block, thus preventing it
1800 // from being subject to a @llvm.stackrestore. Instcombine could even
1801 // convert regular allocas into these special allocas. It'd be nifty.
1802 // However, until then, this problem remains open.
1803 //
1804 // So, we'll assume that two non-empty allocas have different addresses
1805 // for now.
1806 //
1807 // With all that, if the offsets are within the bounds of their allocations
1808 // (and not one-past-the-end! so we can't use inbounds!), and their
1809 // allocations aren't the same, the pointers are not equal.
1810 //
1811 // Note that it's not necessary to check for LHS being a global variable
1812 // address, due to canonicalization and constant folding.
1813 if (isa<AllocaInst>(LHS) &&
1814 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerd9f32c22013-02-01 15:21:10 +00001815 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1816 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001817 uint64_t LHSSize, RHSSize;
Benjamin Kramerd9f32c22013-02-01 15:21:10 +00001818 if (LHSOffsetCI && RHSOffsetCI &&
1819 getObjectSize(LHS, LHSSize, TD, TLI) &&
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001820 getObjectSize(RHS, RHSSize, TD, TLI)) {
Benjamin Kramerd9f32c22013-02-01 15:21:10 +00001821 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1822 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00001823 if (!LHSOffsetValue.isNegative() &&
1824 !RHSOffsetValue.isNegative() &&
1825 LHSOffsetValue.ult(LHSSize) &&
1826 RHSOffsetValue.ult(RHSSize)) {
1827 return ConstantInt::get(GetCompareTy(LHS),
1828 !CmpInst::isTrueWhenEqual(Pred));
1829 }
1830 }
1831
1832 // Repeat the above check but this time without depending on DataLayout
1833 // or being able to compute a precise size.
1834 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1835 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1836 LHSOffset->isNullValue() &&
1837 RHSOffset->isNullValue())
1838 return ConstantInt::get(GetCompareTy(LHS),
1839 !CmpInst::isTrueWhenEqual(Pred));
1840 }
1841 }
1842
1843 // Otherwise, fail.
1844 return 0;
Chandler Carruth58725a62012-03-25 21:28:14 +00001845}
Chris Lattner009e2652012-02-24 19:01:58 +00001846
Chris Lattner9dbb4292009-11-09 23:28:39 +00001847/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1848/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001849static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001850 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001851 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001852 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001853
Chris Lattnerd06094f2009-11-10 00:55:12 +00001854 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001855 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001856 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001857
1858 // If we have a constant, make sure it is on the RHS.
1859 std::swap(LHS, RHS);
1860 Pred = CmpInst::getSwappedPredicate(Pred);
1861 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001862
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001863 Type *ITy = GetCompareTy(LHS); // The return type.
1864 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001865
Chris Lattner210c5d42009-11-09 23:55:12 +00001866 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001867 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1868 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001869 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001870 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001871
Duncan Sands6dc91252011-01-13 08:56:29 +00001872 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001873 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001874 switch (Pred) {
1875 default: break;
1876 case ICmpInst::ICMP_EQ:
1877 // X == 1 -> X
1878 if (match(RHS, m_One()))
1879 return LHS;
1880 break;
1881 case ICmpInst::ICMP_NE:
1882 // X != 0 -> X
1883 if (match(RHS, m_Zero()))
1884 return LHS;
1885 break;
1886 case ICmpInst::ICMP_UGT:
1887 // X >u 0 -> X
1888 if (match(RHS, m_Zero()))
1889 return LHS;
1890 break;
1891 case ICmpInst::ICMP_UGE:
1892 // X >=u 1 -> X
1893 if (match(RHS, m_One()))
1894 return LHS;
1895 break;
1896 case ICmpInst::ICMP_SLT:
1897 // X <s 0 -> X
1898 if (match(RHS, m_Zero()))
1899 return LHS;
1900 break;
1901 case ICmpInst::ICMP_SLE:
1902 // X <=s -1 -> X
1903 if (match(RHS, m_One()))
1904 return LHS;
1905 break;
1906 }
1907 }
1908
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001909 // If we are comparing with zero then try hard since this is a common case.
1910 if (match(RHS, m_Zero())) {
1911 bool LHSKnownNonNegative, LHSKnownNegative;
1912 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001913 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001914 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001915 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001916 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001917 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001918 case ICmpInst::ICMP_EQ:
1919 case ICmpInst::ICMP_ULE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001920 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001921 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001922 break;
1923 case ICmpInst::ICMP_NE:
1924 case ICmpInst::ICMP_UGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001925 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001926 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001927 break;
1928 case ICmpInst::ICMP_SLT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001929 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001930 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001931 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001932 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001933 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001934 break;
1935 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001936 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001937 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001938 return getTrue(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001939 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001940 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001941 break;
1942 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001943 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001944 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001945 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001946 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001947 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001948 break;
1949 case ICmpInst::ICMP_SGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001950 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001951 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001952 return getFalse(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001953 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001954 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001955 break;
1956 }
1957 }
1958
1959 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001960 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001961 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1962 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1963 if (RHS_CR.isEmptySet())
1964 return ConstantInt::getFalse(CI->getContext());
1965 if (RHS_CR.isFullSet())
1966 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001967
Nick Lewycky3a73e342011-03-04 07:00:57 +00001968 // Many binary operators with constant RHS have easy to compute constant
1969 // range. Use them to check whether the comparison is a tautology.
1970 uint32_t Width = CI->getBitWidth();
1971 APInt Lower = APInt(Width, 0);
1972 APInt Upper = APInt(Width, 0);
1973 ConstantInt *CI2;
1974 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1975 // 'urem x, CI2' produces [0, CI2).
1976 Upper = CI2->getValue();
1977 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1978 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1979 Upper = CI2->getValue().abs();
1980 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001981 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1982 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001983 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001984 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1985 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1986 APInt NegOne = APInt::getAllOnesValue(Width);
1987 if (!CI2->isZero())
1988 Upper = NegOne.udiv(CI2->getValue()) + 1;
1989 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1990 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1991 APInt IntMin = APInt::getSignedMinValue(Width);
1992 APInt IntMax = APInt::getSignedMaxValue(Width);
1993 APInt Val = CI2->getValue().abs();
1994 if (!Val.isMinValue()) {
1995 Lower = IntMin.sdiv(Val);
1996 Upper = IntMax.sdiv(Val) + 1;
1997 }
1998 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1999 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2000 APInt NegOne = APInt::getAllOnesValue(Width);
2001 if (CI2->getValue().ult(Width))
2002 Upper = NegOne.lshr(CI2->getValue()) + 1;
2003 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2004 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2005 APInt IntMin = APInt::getSignedMinValue(Width);
2006 APInt IntMax = APInt::getSignedMaxValue(Width);
2007 if (CI2->getValue().ult(Width)) {
2008 Lower = IntMin.ashr(CI2->getValue());
2009 Upper = IntMax.ashr(CI2->getValue()) + 1;
2010 }
2011 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2012 // 'or x, CI2' produces [CI2, UINT_MAX].
2013 Lower = CI2->getValue();
2014 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2015 // 'and x, CI2' produces [0, CI2].
2016 Upper = CI2->getValue() + 1;
2017 }
2018 if (Lower != Upper) {
2019 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2020 if (RHS_CR.contains(LHS_CR))
2021 return ConstantInt::getTrue(RHS->getContext());
2022 if (RHS_CR.inverse().contains(LHS_CR))
2023 return ConstantInt::getFalse(RHS->getContext());
2024 }
Duncan Sands6dc91252011-01-13 08:56:29 +00002025 }
2026
Duncan Sands9d32f602011-01-20 13:21:55 +00002027 // Compare of cast, for example (zext X) != 0 -> X != 0
2028 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2029 Instruction *LI = cast<CastInst>(LHS);
2030 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002031 Type *SrcTy = SrcOp->getType();
2032 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00002033
2034 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2035 // if the integer type is the same size as the pointer type.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002036 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
Chandler Carruth426c2bf2012-11-01 09:14:31 +00002037 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands9d32f602011-01-20 13:21:55 +00002038 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2039 // Transfer the cast to the constant.
2040 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2041 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002042 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002043 return V;
2044 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2045 if (RI->getOperand(0)->getType() == SrcTy)
2046 // Compare without the cast.
2047 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002048 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002049 return V;
2050 }
2051 }
2052
2053 if (isa<ZExtInst>(LHS)) {
2054 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2055 // same type.
2056 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2057 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2058 // Compare X and Y. Note that signed predicates become unsigned.
2059 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002060 SrcOp, RI->getOperand(0), Q,
Duncan Sands9d32f602011-01-20 13:21:55 +00002061 MaxRecurse-1))
2062 return V;
2063 }
2064 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2065 // too. If not, then try to deduce the result of the comparison.
2066 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2067 // Compute the constant that would happen if we truncated to SrcTy then
2068 // reextended to DstTy.
2069 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2070 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2071
2072 // If the re-extended constant didn't change then this is effectively
2073 // also a case of comparing two zero-extended values.
2074 if (RExt == CI && MaxRecurse)
2075 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002076 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002077 return V;
2078
2079 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2080 // there. Use this to work out the result of the comparison.
2081 if (RExt != CI) {
2082 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00002083 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00002084 // LHS <u RHS.
2085 case ICmpInst::ICMP_EQ:
2086 case ICmpInst::ICMP_UGT:
2087 case ICmpInst::ICMP_UGE:
2088 return ConstantInt::getFalse(CI->getContext());
2089
2090 case ICmpInst::ICMP_NE:
2091 case ICmpInst::ICMP_ULT:
2092 case ICmpInst::ICMP_ULE:
2093 return ConstantInt::getTrue(CI->getContext());
2094
2095 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2096 // is non-negative then LHS <s RHS.
2097 case ICmpInst::ICMP_SGT:
2098 case ICmpInst::ICMP_SGE:
2099 return CI->getValue().isNegative() ?
2100 ConstantInt::getTrue(CI->getContext()) :
2101 ConstantInt::getFalse(CI->getContext());
2102
2103 case ICmpInst::ICMP_SLT:
2104 case ICmpInst::ICMP_SLE:
2105 return CI->getValue().isNegative() ?
2106 ConstantInt::getFalse(CI->getContext()) :
2107 ConstantInt::getTrue(CI->getContext());
2108 }
2109 }
2110 }
2111 }
2112
2113 if (isa<SExtInst>(LHS)) {
2114 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2115 // same type.
2116 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2117 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2118 // Compare X and Y. Note that the predicate does not change.
2119 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002120 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002121 return V;
2122 }
2123 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2124 // too. If not, then try to deduce the result of the comparison.
2125 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2126 // Compute the constant that would happen if we truncated to SrcTy then
2127 // reextended to DstTy.
2128 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2129 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2130
2131 // If the re-extended constant didn't change then this is effectively
2132 // also a case of comparing two sign-extended values.
2133 if (RExt == CI && MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002134 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002135 return V;
2136
2137 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2138 // bits there. Use this to work out the result of the comparison.
2139 if (RExt != CI) {
2140 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00002141 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00002142 case ICmpInst::ICMP_EQ:
2143 return ConstantInt::getFalse(CI->getContext());
2144 case ICmpInst::ICMP_NE:
2145 return ConstantInt::getTrue(CI->getContext());
2146
2147 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2148 // LHS >s RHS.
2149 case ICmpInst::ICMP_SGT:
2150 case ICmpInst::ICMP_SGE:
2151 return CI->getValue().isNegative() ?
2152 ConstantInt::getTrue(CI->getContext()) :
2153 ConstantInt::getFalse(CI->getContext());
2154 case ICmpInst::ICMP_SLT:
2155 case ICmpInst::ICMP_SLE:
2156 return CI->getValue().isNegative() ?
2157 ConstantInt::getFalse(CI->getContext()) :
2158 ConstantInt::getTrue(CI->getContext());
2159
2160 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2161 // LHS >u RHS.
2162 case ICmpInst::ICMP_UGT:
2163 case ICmpInst::ICMP_UGE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002164 // Comparison is true iff the LHS <s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002165 if (MaxRecurse)
2166 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2167 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002168 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002169 return V;
2170 break;
2171 case ICmpInst::ICMP_ULT:
2172 case ICmpInst::ICMP_ULE:
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002173 // Comparison is true iff the LHS >=s 0.
Duncan Sands9d32f602011-01-20 13:21:55 +00002174 if (MaxRecurse)
2175 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2176 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002177 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002178 return V;
2179 break;
2180 }
2181 }
2182 }
2183 }
2184 }
2185
Duncan Sands52fb8462011-02-13 17:15:40 +00002186 // Special logic for binary operators.
2187 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2188 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2189 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00002190 // Analyze the case when either LHS or RHS is an add instruction.
2191 Value *A = 0, *B = 0, *C = 0, *D = 0;
2192 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2193 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2194 if (LBO && LBO->getOpcode() == Instruction::Add) {
2195 A = LBO->getOperand(0); B = LBO->getOperand(1);
2196 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2197 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2198 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2199 }
2200 if (RBO && RBO->getOpcode() == Instruction::Add) {
2201 C = RBO->getOperand(0); D = RBO->getOperand(1);
2202 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2203 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2204 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2205 }
2206
2207 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2208 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2209 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2210 Constant::getNullValue(RHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002211 Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002212 return V;
2213
2214 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2215 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2216 if (Value *V = SimplifyICmpInst(Pred,
2217 Constant::getNullValue(LHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002218 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002219 return V;
2220
2221 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2222 if (A && C && (A == C || A == D || B == C || B == D) &&
2223 NoLHSWrapProblem && NoRHSWrapProblem) {
2224 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002225 Value *Y, *Z;
2226 if (A == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002227 // C + B == C + D -> B == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002228 Y = B;
2229 Z = D;
2230 } else if (A == D) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002231 // D + B == C + D -> B == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002232 Y = B;
2233 Z = C;
2234 } else if (B == C) {
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002235 // A + C == C + D -> A == D
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002236 Y = A;
2237 Z = D;
Duncan Sands4f0dfbb2012-11-16 20:53:08 +00002238 } else {
2239 assert(B == D);
2240 // A + D == C + D -> A == C
Duncan Sandsaceb03e2012-11-16 19:41:26 +00002241 Y = A;
2242 Z = C;
2243 }
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002244 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002245 return V;
2246 }
2247 }
2248
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002249 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002250 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002251 switch (Pred) {
2252 default:
2253 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002254 case ICmpInst::ICMP_SGT:
2255 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002256 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002257 if (!KnownNonNegative)
2258 break;
2259 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002260 case ICmpInst::ICMP_EQ:
2261 case ICmpInst::ICMP_UGT:
2262 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002263 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002264 case ICmpInst::ICMP_SLT:
2265 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002266 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002267 if (!KnownNonNegative)
2268 break;
2269 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002270 case ICmpInst::ICMP_NE:
2271 case ICmpInst::ICMP_ULT:
2272 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002273 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002274 }
2275 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002276 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2277 bool KnownNonNegative, KnownNegative;
2278 switch (Pred) {
2279 default:
2280 break;
2281 case ICmpInst::ICMP_SGT:
2282 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002283 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002284 if (!KnownNonNegative)
2285 break;
2286 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002287 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002288 case ICmpInst::ICMP_UGT:
2289 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002290 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002291 case ICmpInst::ICMP_SLT:
2292 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002293 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002294 if (!KnownNonNegative)
2295 break;
2296 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002297 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002298 case ICmpInst::ICMP_ULT:
2299 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002300 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002301 }
2302 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002303
Duncan Sandsc65c7472011-10-28 18:17:44 +00002304 // x udiv y <=u x.
2305 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2306 // icmp pred (X /u Y), X
2307 if (Pred == ICmpInst::ICMP_UGT)
2308 return getFalse(ITy);
2309 if (Pred == ICmpInst::ICMP_ULE)
2310 return getTrue(ITy);
2311 }
2312
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002313 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2314 LBO->getOperand(1) == RBO->getOperand(1)) {
2315 switch (LBO->getOpcode()) {
2316 default: break;
2317 case Instruction::UDiv:
2318 case Instruction::LShr:
2319 if (ICmpInst::isSigned(Pred))
2320 break;
2321 // fall-through
2322 case Instruction::SDiv:
2323 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002324 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002325 break;
2326 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002327 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002328 return V;
2329 break;
2330 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002331 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002332 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2333 if (!NUW && !NSW)
2334 break;
2335 if (!NSW && ICmpInst::isSigned(Pred))
2336 break;
2337 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002338 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002339 return V;
2340 break;
2341 }
2342 }
2343 }
2344
Duncan Sandsad206812011-05-03 19:53:10 +00002345 // Simplify comparisons involving max/min.
2346 Value *A, *B;
2347 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002348 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sandsad206812011-05-03 19:53:10 +00002349
Duncan Sands8140ad32011-05-04 16:05:05 +00002350 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002351 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2352 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002353 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002354 // We analyze this as smax(A, B) pred A.
2355 P = Pred;
2356 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2357 (A == LHS || B == LHS)) {
2358 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002359 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002360 // We analyze this as smax(A, B) swapped-pred A.
2361 P = CmpInst::getSwappedPredicate(Pred);
2362 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2363 (A == RHS || B == RHS)) {
2364 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002365 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sandsad206812011-05-03 19:53:10 +00002366 // We analyze this as smax(-A, -B) swapped-pred -A.
2367 // Note that we do not need to actually form -A or -B thanks to EqP.
2368 P = CmpInst::getSwappedPredicate(Pred);
2369 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2370 (A == LHS || B == LHS)) {
2371 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002372 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sandsad206812011-05-03 19:53:10 +00002373 // We analyze this as smax(-A, -B) pred -A.
2374 // Note that we do not need to actually form -A or -B thanks to EqP.
2375 P = Pred;
2376 }
2377 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2378 // Cases correspond to "max(A, B) p A".
2379 switch (P) {
2380 default:
2381 break;
2382 case CmpInst::ICMP_EQ:
2383 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002384 // Equivalent to "A EqP B". This may be the same as the condition tested
2385 // in the max/min; if so, we can just return that.
2386 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2387 return V;
2388 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2389 return V;
2390 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002391 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002392 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002393 return V;
2394 break;
2395 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002396 case CmpInst::ICMP_SGT: {
2397 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2398 // Equivalent to "A InvEqP B". This may be the same as the condition
2399 // tested in the max/min; if so, we can just return that.
2400 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2401 return V;
2402 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2403 return V;
2404 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002405 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002406 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002407 return V;
2408 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002409 }
Duncan Sandsad206812011-05-03 19:53:10 +00002410 case CmpInst::ICMP_SGE:
2411 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002412 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002413 case CmpInst::ICMP_SLT:
2414 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002415 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002416 }
2417 }
2418
Duncan Sands8140ad32011-05-04 16:05:05 +00002419 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002420 P = CmpInst::BAD_ICMP_PREDICATE;
2421 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2422 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002423 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002424 // We analyze this as umax(A, B) pred A.
2425 P = Pred;
2426 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2427 (A == LHS || B == LHS)) {
2428 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002429 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sandsad206812011-05-03 19:53:10 +00002430 // We analyze this as umax(A, B) swapped-pred A.
2431 P = CmpInst::getSwappedPredicate(Pred);
2432 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2433 (A == RHS || B == RHS)) {
2434 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002435 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sandsad206812011-05-03 19:53:10 +00002436 // We analyze this as umax(-A, -B) swapped-pred -A.
2437 // Note that we do not need to actually form -A or -B thanks to EqP.
2438 P = CmpInst::getSwappedPredicate(Pred);
2439 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2440 (A == LHS || B == LHS)) {
2441 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru94c22712012-09-27 10:14:43 +00002442 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sandsad206812011-05-03 19:53:10 +00002443 // We analyze this as umax(-A, -B) pred -A.
2444 // Note that we do not need to actually form -A or -B thanks to EqP.
2445 P = Pred;
2446 }
2447 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2448 // Cases correspond to "max(A, B) p A".
2449 switch (P) {
2450 default:
2451 break;
2452 case CmpInst::ICMP_EQ:
2453 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002454 // Equivalent to "A EqP B". This may be the same as the condition tested
2455 // in the max/min; if so, we can just return that.
2456 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2457 return V;
2458 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2459 return V;
2460 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002461 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002462 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002463 return V;
2464 break;
2465 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002466 case CmpInst::ICMP_UGT: {
2467 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2468 // Equivalent to "A InvEqP B". This may be the same as the condition
2469 // tested in the max/min; if so, we can just return that.
2470 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2471 return V;
2472 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2473 return V;
2474 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002475 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002476 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002477 return V;
2478 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002479 }
Duncan Sandsad206812011-05-03 19:53:10 +00002480 case CmpInst::ICMP_UGE:
2481 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002482 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002483 case CmpInst::ICMP_ULT:
2484 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002485 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002486 }
2487 }
2488
Duncan Sands8140ad32011-05-04 16:05:05 +00002489 // Variants on "max(x,y) >= min(x,z)".
2490 Value *C, *D;
2491 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2492 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2493 (A == C || A == D || B == C || B == D)) {
2494 // max(x, ?) pred min(x, ?).
2495 if (Pred == CmpInst::ICMP_SGE)
2496 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002497 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002498 if (Pred == CmpInst::ICMP_SLT)
2499 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002500 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002501 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2502 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2503 (A == C || A == D || B == C || B == D)) {
2504 // min(x, ?) pred max(x, ?).
2505 if (Pred == CmpInst::ICMP_SLE)
2506 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002507 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002508 if (Pred == CmpInst::ICMP_SGT)
2509 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002510 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002511 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2512 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2513 (A == C || A == D || B == C || B == D)) {
2514 // max(x, ?) pred min(x, ?).
2515 if (Pred == CmpInst::ICMP_UGE)
2516 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002517 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002518 if (Pred == CmpInst::ICMP_ULT)
2519 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002520 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002521 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2522 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2523 (A == C || A == D || B == C || B == D)) {
2524 // min(x, ?) pred max(x, ?).
2525 if (Pred == CmpInst::ICMP_ULE)
2526 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002527 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002528 if (Pred == CmpInst::ICMP_UGT)
2529 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002530 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002531 }
2532
Chandler Carruth58725a62012-03-25 21:28:14 +00002533 // Simplify comparisons of related pointers using a powerful, recursive
2534 // GEP-walk when we have target data available..
Dan Gohman3e3de562013-01-31 02:50:36 +00002535 if (LHS->getType()->isPointerTy())
Dan Gohmanfdd1eaf2013-02-01 00:11:13 +00002536 if (Constant *C = computePointerICmp(Q.TD, Q.TLI, Pred, LHS, RHS))
Chandler Carruth58725a62012-03-25 21:28:14 +00002537 return C;
2538
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002539 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2540 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2541 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2542 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2543 (ICmpInst::isEquality(Pred) ||
2544 (GLHS->isInBounds() && GRHS->isInBounds() &&
2545 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2546 // The bases are equal and the indices are constant. Build a constant
2547 // expression GEP with the same indices and a null base pointer to see
2548 // what constant folding can make out of it.
2549 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2550 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2551 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2552
2553 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2554 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2555 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2556 }
2557 }
2558 }
2559
Duncan Sands1ac7c992010-11-07 16:12:23 +00002560 // If the comparison is with the result of a select instruction, check whether
2561 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002562 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002563 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002564 return V;
2565
2566 // If the comparison is with the result of a phi instruction, check whether
2567 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002568 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002569 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002570 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002571
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002572 return 0;
2573}
2574
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002575Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002576 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002577 const TargetLibraryInfo *TLI,
2578 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002579 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2580 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002581}
2582
Chris Lattner9dbb4292009-11-09 23:28:39 +00002583/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2584/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002585static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002586 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002587 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2588 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2589
Chris Lattnerd06094f2009-11-10 00:55:12 +00002590 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002591 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002592 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002593
Chris Lattnerd06094f2009-11-10 00:55:12 +00002594 // If we have a constant, make sure it is on the RHS.
2595 std::swap(LHS, RHS);
2596 Pred = CmpInst::getSwappedPredicate(Pred);
2597 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002598
Chris Lattner210c5d42009-11-09 23:55:12 +00002599 // Fold trivial predicates.
2600 if (Pred == FCmpInst::FCMP_FALSE)
2601 return ConstantInt::get(GetCompareTy(LHS), 0);
2602 if (Pred == FCmpInst::FCMP_TRUE)
2603 return ConstantInt::get(GetCompareTy(LHS), 1);
2604
Chris Lattner210c5d42009-11-09 23:55:12 +00002605 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2606 return UndefValue::get(GetCompareTy(LHS));
2607
2608 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002609 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002610 if (CmpInst::isTrueWhenEqual(Pred))
2611 return ConstantInt::get(GetCompareTy(LHS), 1);
2612 if (CmpInst::isFalseWhenEqual(Pred))
2613 return ConstantInt::get(GetCompareTy(LHS), 0);
2614 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002615
Chris Lattner210c5d42009-11-09 23:55:12 +00002616 // Handle fcmp with constant RHS
2617 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2618 // If the constant is a nan, see if we can fold the comparison based on it.
2619 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2620 if (CFP->getValueAPF().isNaN()) {
2621 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2622 return ConstantInt::getFalse(CFP->getContext());
2623 assert(FCmpInst::isUnordered(Pred) &&
2624 "Comparison must be either ordered or unordered!");
2625 // True if unordered.
2626 return ConstantInt::getTrue(CFP->getContext());
2627 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002628 // Check whether the constant is an infinity.
2629 if (CFP->getValueAPF().isInfinity()) {
2630 if (CFP->getValueAPF().isNegative()) {
2631 switch (Pred) {
2632 case FCmpInst::FCMP_OLT:
2633 // No value is ordered and less than negative infinity.
2634 return ConstantInt::getFalse(CFP->getContext());
2635 case FCmpInst::FCMP_UGE:
2636 // All values are unordered with or at least negative infinity.
2637 return ConstantInt::getTrue(CFP->getContext());
2638 default:
2639 break;
2640 }
2641 } else {
2642 switch (Pred) {
2643 case FCmpInst::FCMP_OGT:
2644 // No value is ordered and greater than infinity.
2645 return ConstantInt::getFalse(CFP->getContext());
2646 case FCmpInst::FCMP_ULE:
2647 // All values are unordered with and at most infinity.
2648 return ConstantInt::getTrue(CFP->getContext());
2649 default:
2650 break;
2651 }
2652 }
2653 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002654 }
2655 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002656
Duncan Sands92826de2010-11-07 16:46:25 +00002657 // If the comparison is with the result of a select instruction, check whether
2658 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002659 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002660 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002661 return V;
2662
2663 // If the comparison is with the result of a phi instruction, check whether
2664 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002665 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002666 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002667 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002668
Chris Lattner9dbb4292009-11-09 23:28:39 +00002669 return 0;
2670}
2671
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002672Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002673 const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002674 const TargetLibraryInfo *TLI,
2675 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002676 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2677 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002678}
2679
Chris Lattner04754262010-04-20 05:32:14 +00002680/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2681/// the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002682static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2683 Value *FalseVal, const Query &Q,
2684 unsigned MaxRecurse) {
Chris Lattner04754262010-04-20 05:32:14 +00002685 // select true, X, Y -> X
2686 // select false, X, Y -> Y
2687 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2688 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002689
Chris Lattner04754262010-04-20 05:32:14 +00002690 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002691 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002692 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002693
Chris Lattner04754262010-04-20 05:32:14 +00002694 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2695 if (isa<Constant>(TrueVal))
2696 return TrueVal;
2697 return FalseVal;
2698 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002699 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2700 return FalseVal;
2701 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2702 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002703
Chris Lattner04754262010-04-20 05:32:14 +00002704 return 0;
2705}
2706
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002707Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Micah Villmow3574eca2012-10-08 16:38:25 +00002708 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002709 const TargetLibraryInfo *TLI,
2710 const DominatorTree *DT) {
2711 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2712 RecursionLimit);
2713}
2714
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002715/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2716/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002717static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002718 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002719 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2720 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2721 if (!PtrTy)
2722 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002723
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002724 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002725 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002726 return Ops[0];
2727
Duncan Sands85bbff62010-11-22 13:42:49 +00002728 if (isa<UndefValue>(Ops[0])) {
2729 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002730 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002731 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002732 return UndefValue::get(GEPTy);
2733 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002734
Jay Foadb9b54eb2011-07-19 15:07:52 +00002735 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002736 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002737 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2738 if (C->isZero())
2739 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002740 // getelementptr P, N -> P if P points to a type of zero size.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002741 if (Q.TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002742 Type *Ty = PtrTy->getElementType();
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002743 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002744 return Ops[0];
2745 }
2746 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002747
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002748 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002749 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002750 if (!isa<Constant>(Ops[i]))
2751 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002752
Jay Foaddab3d292011-07-21 14:31:17 +00002753 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002754}
2755
Micah Villmow3574eca2012-10-08 16:38:25 +00002756Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002757 const TargetLibraryInfo *TLI,
2758 const DominatorTree *DT) {
2759 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2760}
2761
Duncan Sandsdabc2802011-09-05 06:52:48 +00002762/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2763/// can fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002764static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2765 ArrayRef<unsigned> Idxs, const Query &Q,
2766 unsigned) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002767 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2768 if (Constant *CVal = dyn_cast<Constant>(Val))
2769 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2770
2771 // insertvalue x, undef, n -> x
2772 if (match(Val, m_Undef()))
2773 return Agg;
2774
2775 // insertvalue x, (extractvalue y, n), n
2776 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002777 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2778 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002779 // insertvalue undef, (extractvalue y, n), n -> y
2780 if (match(Agg, m_Undef()))
2781 return EV->getAggregateOperand();
2782
2783 // insertvalue y, (extractvalue y, n), n -> y
2784 if (Agg == EV->getAggregateOperand())
2785 return Agg;
2786 }
2787
2788 return 0;
2789}
2790
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002791Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2792 ArrayRef<unsigned> Idxs,
Micah Villmow3574eca2012-10-08 16:38:25 +00002793 const DataLayout *TD,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002794 const TargetLibraryInfo *TLI,
2795 const DominatorTree *DT) {
2796 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2797 RecursionLimit);
2798}
2799
Duncan Sandsff103412010-11-17 04:30:22 +00002800/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002801static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sandsff103412010-11-17 04:30:22 +00002802 // If all of the PHI's incoming values are the same then replace the PHI node
2803 // with the common value.
2804 Value *CommonValue = 0;
2805 bool HasUndefInput = false;
2806 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2807 Value *Incoming = PN->getIncomingValue(i);
2808 // If the incoming value is the phi node itself, it can safely be skipped.
2809 if (Incoming == PN) continue;
2810 if (isa<UndefValue>(Incoming)) {
2811 // Remember that we saw an undef value, but otherwise ignore them.
2812 HasUndefInput = true;
2813 continue;
2814 }
2815 if (CommonValue && Incoming != CommonValue)
2816 return 0; // Not the same, bail out.
2817 CommonValue = Incoming;
2818 }
2819
2820 // If CommonValue is null then all of the incoming values were either undef or
2821 // equal to the phi node itself.
2822 if (!CommonValue)
2823 return UndefValue::get(PN->getType());
2824
2825 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2826 // instruction, we cannot return X as the result of the PHI node unless it
2827 // dominates the PHI block.
2828 if (HasUndefInput)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002829 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
Duncan Sandsff103412010-11-17 04:30:22 +00002830
2831 return CommonValue;
2832}
2833
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002834static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2835 if (Constant *C = dyn_cast<Constant>(Op))
2836 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2837
2838 return 0;
2839}
2840
Micah Villmow3574eca2012-10-08 16:38:25 +00002841Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *TD,
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002842 const TargetLibraryInfo *TLI,
2843 const DominatorTree *DT) {
2844 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2845}
2846
Chris Lattnerd06094f2009-11-10 00:55:12 +00002847//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002848
Chris Lattnerd06094f2009-11-10 00:55:12 +00002849/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2850/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002851static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002852 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002853 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002854 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002855 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002856 Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002857 case Instruction::FAdd:
2858 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2859
Chris Lattner81a0dc92011-02-09 17:15:04 +00002860 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002861 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002862 Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002863 case Instruction::FSub:
2864 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2865
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002866 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand0a0d222012-12-12 00:29:16 +00002867 case Instruction::FMul:
2868 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002869 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2870 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2871 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2872 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2873 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2874 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002875 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002876 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002877 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002878 case Instruction::LShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002879 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002880 case Instruction::AShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002881 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2882 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2883 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2884 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002885 default:
2886 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2887 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2888 Constant *COps[] = {CLHS, CRHS};
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002889 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2890 Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002891 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002892
Duncan Sands566edb02010-12-21 08:49:00 +00002893 // If the operation is associative, try some generic simplifications.
2894 if (Instruction::isAssociative(Opcode))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002895 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00002896 return V;
2897
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002898 // If the operation is with the result of a select instruction check whether
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002899 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002900 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002901 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002902 return V;
2903
2904 // If the operation is with the result of a phi instruction, check whether
2905 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002906 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002907 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002908 return V;
2909
Chris Lattnerd06094f2009-11-10 00:55:12 +00002910 return 0;
2911 }
2912}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002913
Duncan Sands12a86f52010-11-14 11:23:23 +00002914Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002915 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002916 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002917 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002918}
2919
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002920/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2921/// fold the result.
2922static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002923 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002924 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002925 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2926 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002927}
2928
2929Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Micah Villmow3574eca2012-10-08 16:38:25 +00002930 const DataLayout *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +00002931 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002932 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2933 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002934}
Chris Lattnere3453782009-11-10 01:08:51 +00002935
Michael Ilsemanf89de812013-02-07 19:26:05 +00002936static bool IsIdempotent(Intrinsic::ID ID) {
2937 switch (ID) {
2938 default: return false;
2939
2940 // Unary idempotent: f(f(x)) = f(x)
2941 case Intrinsic::fabs:
2942 case Intrinsic::floor:
2943 case Intrinsic::ceil:
2944 case Intrinsic::trunc:
2945 case Intrinsic::rint:
2946 case Intrinsic::nearbyint:
2947 return true;
2948 }
2949}
2950
2951template <typename IterTy>
2952static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
2953 const Query &Q, unsigned MaxRecurse) {
2954 // Perform idempotent optimizations
2955 if (!IsIdempotent(IID))
2956 return 0;
2957
2958 // Unary Ops
2959 if (std::distance(ArgBegin, ArgEnd) == 1)
2960 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
2961 if (II->getIntrinsicID() == IID)
2962 return II;
2963
2964 return 0;
2965}
2966
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002967template <typename IterTy>
Chandler Carruthe949aa12012-12-28 14:23:29 +00002968static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002969 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00002970 Type *Ty = V->getType();
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002971 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
2972 Ty = PTy->getElementType();
2973 FunctionType *FTy = cast<FunctionType>(Ty);
2974
Dan Gohman71d05032011-11-04 18:32:42 +00002975 // call undef -> undef
Chandler Carruthe949aa12012-12-28 14:23:29 +00002976 if (isa<UndefValue>(V))
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00002977 return UndefValue::get(FTy->getReturnType());
Dan Gohman71d05032011-11-04 18:32:42 +00002978
Chandler Carruthe949aa12012-12-28 14:23:29 +00002979 Function *F = dyn_cast<Function>(V);
2980 if (!F)
2981 return 0;
2982
Michael Ilsemanf89de812013-02-07 19:26:05 +00002983 if (unsigned IID = F->getIntrinsicID())
2984 if (Value *Ret =
2985 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
2986 return Ret;
2987
Chandler Carruthe949aa12012-12-28 14:23:29 +00002988 if (!canConstantFoldCallTo(F))
2989 return 0;
2990
2991 SmallVector<Constant *, 4> ConstantArgs;
2992 ConstantArgs.reserve(ArgEnd - ArgBegin);
2993 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
2994 Constant *C = dyn_cast<Constant>(*I);
2995 if (!C)
2996 return 0;
2997 ConstantArgs.push_back(C);
2998 }
2999
3000 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman71d05032011-11-04 18:32:42 +00003001}
3002
Chandler Carruthe949aa12012-12-28 14:23:29 +00003003Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003004 User::op_iterator ArgEnd, const DataLayout *TD,
3005 const TargetLibraryInfo *TLI,
3006 const DominatorTree *DT) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00003007 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(TD, TLI, DT),
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003008 RecursionLimit);
3009}
3010
Chandler Carruthe949aa12012-12-28 14:23:29 +00003011Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003012 const DataLayout *TD, const TargetLibraryInfo *TLI,
3013 const DominatorTree *DT) {
Chandler Carruthe949aa12012-12-28 14:23:29 +00003014 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(TD, TLI, DT),
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003015 RecursionLimit);
3016}
3017
Chris Lattnere3453782009-11-10 01:08:51 +00003018/// SimplifyInstruction - See if we can compute a simplified version of this
3019/// instruction. If not, this returns null.
Micah Villmow3574eca2012-10-08 16:38:25 +00003020Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00003021 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00003022 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00003023 Value *Result;
3024
Chris Lattnere3453782009-11-10 01:08:51 +00003025 switch (I->getOpcode()) {
3026 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00003027 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003028 break;
Michael Ilseman09ee2502012-12-12 00:27:46 +00003029 case Instruction::FAdd:
3030 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3031 I->getFastMathFlags(), TD, TLI, DT);
3032 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00003033 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00003034 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3035 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3036 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003037 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003038 break;
Michael Ilseman09ee2502012-12-12 00:27:46 +00003039 case Instruction::FSub:
3040 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3041 I->getFastMathFlags(), TD, TLI, DT);
3042 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00003043 case Instruction::Sub:
3044 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3045 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3046 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003047 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00003048 break;
Michael Ilsemaneb61c922012-11-27 00:46:26 +00003049 case Instruction::FMul:
3050 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3051 I->getFastMathFlags(), TD, TLI, DT);
3052 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00003053 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00003054 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00003055 break;
Duncan Sands593faa52011-01-28 16:51:11 +00003056 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00003057 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00003058 break;
3059 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00003060 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00003061 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00003062 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00003063 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00003064 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00003065 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00003066 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00003067 break;
3068 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00003069 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00003070 break;
3071 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00003072 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00003073 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00003074 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00003075 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3076 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3077 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003078 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00003079 break;
3080 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00003081 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3082 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003083 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00003084 break;
3085 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00003086 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3087 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003088 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00003089 break;
Chris Lattnere3453782009-11-10 01:08:51 +00003090 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00003091 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003092 break;
Chris Lattnere3453782009-11-10 01:08:51 +00003093 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00003094 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003095 break;
Duncan Sands2b749872010-11-17 18:52:15 +00003096 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00003097 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00003098 break;
Chris Lattnere3453782009-11-10 01:08:51 +00003099 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00003100 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003101 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003102 break;
Chris Lattnere3453782009-11-10 01:08:51 +00003103 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00003104 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00003105 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003106 break;
Chris Lattner04754262010-04-20 05:32:14 +00003107 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00003108 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003109 I->getOperand(2), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003110 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00003111 case Instruction::GetElementPtr: {
3112 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003113 Result = SimplifyGEPInst(Ops, TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00003114 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00003115 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00003116 case Instruction::InsertValue: {
3117 InsertValueInst *IV = cast<InsertValueInst>(I);
3118 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3119 IV->getInsertedValueOperand(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003120 IV->getIndices(), TD, TLI, DT);
Duncan Sandsdabc2802011-09-05 06:52:48 +00003121 break;
3122 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00003123 case Instruction::PHI:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00003124 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
Duncan Sandsd261dc62010-11-17 08:35:29 +00003125 break;
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003126 case Instruction::Call: {
3127 CallSite CS(cast<CallInst>(I));
3128 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3129 TD, TLI, DT);
Dan Gohman71d05032011-11-04 18:32:42 +00003130 break;
Chandler Carruthc98bd9f2012-12-28 11:30:55 +00003131 }
Duncan Sandsbd0fe562012-03-13 14:07:05 +00003132 case Instruction::Trunc:
3133 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
3134 break;
Chris Lattnere3453782009-11-10 01:08:51 +00003135 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00003136
3137 /// If called on unreachable code, the above logic may report that the
3138 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00003139 /// detecting that case here, returning a safe value instead.
3140 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00003141}
3142
Chandler Carruth6b980542012-03-24 21:11:24 +00003143/// \brief Implementation of recursive simplification through an instructions
3144/// uses.
Chris Lattner40d8c282009-11-10 22:26:15 +00003145///
Chandler Carruth6b980542012-03-24 21:11:24 +00003146/// This is the common implementation of the recursive simplification routines.
3147/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3148/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3149/// instructions to process and attempt to simplify it using
3150/// InstructionSimplify.
3151///
3152/// This routine returns 'true' only when *it* simplifies something. The passed
3153/// in simplified value does not count toward this.
3154static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00003155 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003156 const TargetLibraryInfo *TLI,
3157 const DominatorTree *DT) {
3158 bool Simplified = false;
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003159 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands12a86f52010-11-14 11:23:23 +00003160
Chandler Carruth6b980542012-03-24 21:11:24 +00003161 // If we have an explicit value to collapse to, do that round of the
3162 // simplification loop by hand initially.
3163 if (SimpleV) {
3164 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3165 ++UI)
Chandler Carruthc5b785b2012-03-24 22:34:23 +00003166 if (*UI != I)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003167 Worklist.insert(cast<Instruction>(*UI));
Duncan Sands12a86f52010-11-14 11:23:23 +00003168
Chandler Carruth6b980542012-03-24 21:11:24 +00003169 // Replace the instruction with its simplified value.
3170 I->replaceAllUsesWith(SimpleV);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00003171
Chandler Carruth6b980542012-03-24 21:11:24 +00003172 // Gracefully handle edge cases where the instruction is not wired into any
3173 // parent block.
3174 if (I->getParent())
3175 I->eraseFromParent();
3176 } else {
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003177 Worklist.insert(I);
Chris Lattner40d8c282009-11-10 22:26:15 +00003178 }
Duncan Sands12a86f52010-11-14 11:23:23 +00003179
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003180 // Note that we must test the size on each iteration, the worklist can grow.
3181 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3182 I = Worklist[Idx];
Duncan Sands12a86f52010-11-14 11:23:23 +00003183
Chandler Carruth6b980542012-03-24 21:11:24 +00003184 // See if this instruction simplifies.
3185 SimpleV = SimplifyInstruction(I, TD, TLI, DT);
3186 if (!SimpleV)
3187 continue;
3188
3189 Simplified = true;
3190
3191 // Stash away all the uses of the old instruction so we can check them for
3192 // recursive simplifications after a RAUW. This is cheaper than checking all
3193 // uses of To on the recursive step in most cases.
3194 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
3195 ++UI)
Chandler Carruth6231d5b2012-03-24 22:34:26 +00003196 Worklist.insert(cast<Instruction>(*UI));
Chandler Carruth6b980542012-03-24 21:11:24 +00003197
3198 // Replace the instruction with its simplified value.
3199 I->replaceAllUsesWith(SimpleV);
3200
3201 // Gracefully handle edge cases where the instruction is not wired into any
3202 // parent block.
3203 if (I->getParent())
3204 I->eraseFromParent();
3205 }
3206 return Simplified;
3207}
3208
3209bool llvm::recursivelySimplifyInstruction(Instruction *I,
Micah Villmow3574eca2012-10-08 16:38:25 +00003210 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003211 const TargetLibraryInfo *TLI,
3212 const DominatorTree *DT) {
3213 return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
3214}
3215
3216bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Micah Villmow3574eca2012-10-08 16:38:25 +00003217 const DataLayout *TD,
Chandler Carruth6b980542012-03-24 21:11:24 +00003218 const TargetLibraryInfo *TLI,
3219 const DominatorTree *DT) {
3220 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3221 assert(SimpleV && "Must provide a simplified value.");
3222 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
Chris Lattner40d8c282009-11-10 22:26:15 +00003223}