blob: 95d02efd789321670b7801d4fa33e4c52ac12416 [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"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000021#include "llvm/GlobalAlias.h"
Jay Foad562b84b2011-04-11 09:35:34 +000022#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000023#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000024#include "llvm/Analysis/InstructionSimplify.h"
Nick Lewyckyf7087ea2012-02-26 02:09:49 +000025#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000026#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000027#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000028#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000029#include "llvm/Support/ConstantRange.h"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000031#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000032#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000033#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000034using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000035using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000036
Chris Lattner81a0dc92011-02-09 17:15:04 +000037enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000038
Duncan Sandsa3c44a52010-12-22 09:40:51 +000039STATISTIC(NumExpand, "Number of expansions");
40STATISTIC(NumFactor , "Number of factorizations");
41STATISTIC(NumReassoc, "Number of reassociations");
42
Duncan Sands0aa85eb2012-03-13 11:42:19 +000043struct Query {
44 const TargetData *TD;
45 const TargetLibraryInfo *TLI;
46 const DominatorTree *DT;
47
48 Query(const TargetData *td, const TargetLibraryInfo *tli,
49 const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {};
50};
51
52static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
53static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000054 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000055static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000056 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000057static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
58static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sandsbd0fe562012-03-13 14:07:05 +000059static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000060
Duncan Sandsf56138d2011-07-26 15:03:53 +000061/// getFalse - For a boolean type, or a vector of boolean type, return false, or
62/// a vector with every element false, as appropriate for the type.
63static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000064 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000065 "Expected i1 type or a vector of i1!");
66 return Constant::getNullValue(Ty);
67}
68
69/// getTrue - For a boolean type, or a vector of boolean type, return true, or
70/// a vector with every element true, as appropriate for the type.
71static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000072 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000073 "Expected i1 type or a vector of i1!");
74 return Constant::getAllOnesValue(Ty);
75}
76
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000077/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
78static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
79 Value *RHS) {
80 CmpInst *Cmp = dyn_cast<CmpInst>(V);
81 if (!Cmp)
82 return false;
83 CmpInst::Predicate CPred = Cmp->getPredicate();
84 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
85 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
86 return true;
87 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
88 CRHS == LHS;
89}
90
Duncan Sands18450092010-11-16 12:16:38 +000091/// ValueDominatesPHI - Does the given value dominate the specified phi node?
92static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
93 Instruction *I = dyn_cast<Instruction>(V);
94 if (!I)
95 // Arguments and constants dominate all instructions.
96 return true;
97
Chandler Carruthff739c12012-03-21 10:58:47 +000098 // If we are processing instructions (and/or basic blocks) that have not been
99 // fully added to a function, the parent nodes may still be null. Simply
100 // return the conservative answer in these cases.
101 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
102 return false;
103
Duncan Sands18450092010-11-16 12:16:38 +0000104 // If we have a DominatorTree then do a precise test.
Eli Friedman5b8f0dd2012-03-13 01:06:07 +0000105 if (DT) {
106 if (!DT->isReachableFromEntry(P->getParent()))
107 return true;
108 if (!DT->isReachableFromEntry(I->getParent()))
109 return false;
110 return DT->dominates(I, P);
111 }
Duncan Sands18450092010-11-16 12:16:38 +0000112
113 // Otherwise, if the instruction is in the entry block, and is not an invoke,
114 // then it obviously dominates all phi nodes.
115 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
116 !isa<InvokeInst>(I))
117 return true;
118
119 return false;
120}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000121
Duncan Sands3421d902010-12-21 13:32:22 +0000122/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
123/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
124/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
125/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
126/// Returns the simplified value, or null if no simplification was performed.
127static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000128 unsigned OpcToExpand, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000129 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000130 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000131 // Recursion is always used, so bail out at once if we already hit the limit.
132 if (!MaxRecurse--)
133 return 0;
134
135 // Check whether the expression has the form "(A op' B) op C".
136 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
137 if (Op0->getOpcode() == OpcodeToExpand) {
138 // It does! Try turning it into "(A op C) op' (B op C)".
139 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
140 // Do "A op C" and "B op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000141 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
142 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000143 // They do! Return "L op' R" if it simplifies or is already available.
144 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000145 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
146 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000147 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000148 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000149 }
Duncan Sands3421d902010-12-21 13:32:22 +0000150 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000151 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000152 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000153 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000154 }
Duncan Sands3421d902010-12-21 13:32:22 +0000155 }
156 }
157
158 // Check whether the expression has the form "A op (B op' C)".
159 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
160 if (Op1->getOpcode() == OpcodeToExpand) {
161 // It does! Try turning it into "(A op B) op' (A op C)".
162 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
163 // Do "A op B" and "A op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000164 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
165 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000166 // They do! Return "L op' R" if it simplifies or is already available.
167 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000168 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
169 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000170 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000171 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000172 }
Duncan Sands3421d902010-12-21 13:32:22 +0000173 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000174 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000175 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000176 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000177 }
Duncan Sands3421d902010-12-21 13:32:22 +0000178 }
179 }
180
181 return 0;
182}
183
184/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
185/// using the operation OpCodeToExtract. For example, when Opcode is Add and
186/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
187/// Returns the simplified value, or null if no simplification was performed.
188static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000189 unsigned OpcToExtract, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000190 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000191 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000192 // Recursion is always used, so bail out at once if we already hit the limit.
193 if (!MaxRecurse--)
194 return 0;
195
196 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
197 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
198
199 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
200 !Op1 || Op1->getOpcode() != OpcodeToExtract)
201 return 0;
202
203 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000204 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
205 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000206
207 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
208 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
209 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000210 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
211 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000212 // Form "A op' (B op DD)" if it simplifies completely.
213 // Does "B op DD" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000214 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000215 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000216 // If V equals B then "A op' V" is just the LHS. If V equals DD then
217 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000218 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000219 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000220 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000221 }
Duncan Sands3421d902010-12-21 13:32:22 +0000222 // Otherwise return "A op' V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000223 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000224 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000225 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000226 }
Duncan Sands3421d902010-12-21 13:32:22 +0000227 }
228 }
229
230 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
231 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
232 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000233 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
234 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000235 // Form "(A op CC) op' B" if it simplifies completely..
236 // Does "A op CC" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000237 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000238 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000239 // If V equals A then "V op' B" is just the LHS. If V equals CC then
240 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000241 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000242 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000243 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000244 }
Duncan Sands3421d902010-12-21 13:32:22 +0000245 // Otherwise return "V op' B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000246 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000247 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000248 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000249 }
Duncan Sands3421d902010-12-21 13:32:22 +0000250 }
251 }
252
253 return 0;
254}
255
256/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
257/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000258static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000259 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000260 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000261 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
262
263 // Recursion is always used, so bail out at once if we already hit the limit.
264 if (!MaxRecurse--)
265 return 0;
266
267 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
268 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
269
270 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
271 if (Op0 && Op0->getOpcode() == Opcode) {
272 Value *A = Op0->getOperand(0);
273 Value *B = Op0->getOperand(1);
274 Value *C = RHS;
275
276 // Does "B op C" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000277 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000278 // It does! Return "A op V" if it simplifies or is already available.
279 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000280 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000281 // Otherwise return "A op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000282 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000283 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000284 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000285 }
Duncan Sands566edb02010-12-21 08:49:00 +0000286 }
287 }
288
289 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
290 if (Op1 && Op1->getOpcode() == Opcode) {
291 Value *A = LHS;
292 Value *B = Op1->getOperand(0);
293 Value *C = Op1->getOperand(1);
294
295 // Does "A op B" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000296 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000297 // It does! Return "V op C" if it simplifies or is already available.
298 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000299 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000300 // Otherwise return "V op C" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000301 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000302 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000303 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000304 }
Duncan Sands566edb02010-12-21 08:49:00 +0000305 }
306 }
307
308 // The remaining transforms require commutativity as well as associativity.
309 if (!Instruction::isCommutative(Opcode))
310 return 0;
311
312 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
313 if (Op0 && Op0->getOpcode() == Opcode) {
314 Value *A = Op0->getOperand(0);
315 Value *B = Op0->getOperand(1);
316 Value *C = RHS;
317
318 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000319 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000320 // It does! Return "V op B" if it simplifies or is already available.
321 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000322 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000323 // Otherwise return "V op B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000324 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000325 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000326 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000327 }
Duncan Sands566edb02010-12-21 08:49:00 +0000328 }
329 }
330
331 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
332 if (Op1 && Op1->getOpcode() == Opcode) {
333 Value *A = LHS;
334 Value *B = Op1->getOperand(0);
335 Value *C = Op1->getOperand(1);
336
337 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000338 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000339 // It does! Return "B op V" if it simplifies or is already available.
340 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000341 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000342 // Otherwise return "B op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000343 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000344 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000345 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000346 }
Duncan Sands566edb02010-12-21 08:49:00 +0000347 }
348 }
349
350 return 0;
351}
352
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000353/// ThreadBinOpOverSelect - In the case of a binary operation with a select
354/// instruction as an operand, try to simplify the binop by seeing whether
355/// evaluating it on both branches of the select results in the same value.
356/// Returns the common value if so, otherwise returns null.
357static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000358 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000359 // Recursion is always used, so bail out at once if we already hit the limit.
360 if (!MaxRecurse--)
361 return 0;
362
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000363 SelectInst *SI;
364 if (isa<SelectInst>(LHS)) {
365 SI = cast<SelectInst>(LHS);
366 } else {
367 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
368 SI = cast<SelectInst>(RHS);
369 }
370
371 // Evaluate the BinOp on the true and false branches of the select.
372 Value *TV;
373 Value *FV;
374 if (SI == LHS) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000375 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
376 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000377 } else {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000378 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
379 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000380 }
381
Duncan Sands7cf85e72011-01-01 16:12:09 +0000382 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000383 // If they both failed to simplify then return null.
384 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000385 return TV;
386
387 // If one branch simplified to undef, return the other one.
388 if (TV && isa<UndefValue>(TV))
389 return FV;
390 if (FV && isa<UndefValue>(FV))
391 return TV;
392
393 // If applying the operation did not change the true and false select values,
394 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000395 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000396 return SI;
397
398 // If one branch simplified and the other did not, and the simplified
399 // value is equal to the unsimplified one, return the simplified value.
400 // For example, select (cond, X, X & Z) & Z -> X & Z.
401 if ((FV && !TV) || (TV && !FV)) {
402 // Check that the simplified value has the form "X op Y" where "op" is the
403 // same as the original operation.
404 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
405 if (Simplified && Simplified->getOpcode() == Opcode) {
406 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
407 // We already know that "op" is the same as for the simplified value. See
408 // if the operands match too. If so, return the simplified value.
409 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
410 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
411 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000412 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
413 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000414 return Simplified;
415 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000416 Simplified->getOperand(1) == UnsimplifiedLHS &&
417 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000418 return Simplified;
419 }
420 }
421
422 return 0;
423}
424
425/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
426/// try to simplify the comparison by seeing whether both branches of the select
427/// result in the same value. Returns the common value if so, otherwise returns
428/// null.
429static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000430 Value *RHS, const Query &Q,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000431 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000432 // Recursion is always used, so bail out at once if we already hit the limit.
433 if (!MaxRecurse--)
434 return 0;
435
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000436 // Make sure the select is on the LHS.
437 if (!isa<SelectInst>(LHS)) {
438 std::swap(LHS, RHS);
439 Pred = CmpInst::getSwappedPredicate(Pred);
440 }
441 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
442 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000443 Value *Cond = SI->getCondition();
444 Value *TV = SI->getTrueValue();
445 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000446
Duncan Sands50ca4d32011-02-03 09:37:39 +0000447 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000448 // Does "cmp TV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000449 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000450 if (TCmp == Cond) {
451 // It not only simplified, it simplified to the select condition. Replace
452 // it with 'true'.
453 TCmp = getTrue(Cond->getType());
454 } else if (!TCmp) {
455 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
456 // condition then we can replace it with 'true'. Otherwise give up.
457 if (!isSameCompare(Cond, Pred, TV, RHS))
458 return 0;
459 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000460 }
461
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000462 // Does "cmp FV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000463 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000464 if (FCmp == Cond) {
465 // It not only simplified, it simplified to the select condition. Replace
466 // it with 'false'.
467 FCmp = getFalse(Cond->getType());
468 } else if (!FCmp) {
469 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
470 // condition then we can replace it with 'false'. Otherwise give up.
471 if (!isSameCompare(Cond, Pred, FV, RHS))
472 return 0;
473 FCmp = getFalse(Cond->getType());
474 }
475
476 // If both sides simplified to the same value, then use it as the result of
477 // the original comparison.
478 if (TCmp == FCmp)
479 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000480
481 // The remaining cases only make sense if the select condition has the same
482 // type as the result of the comparison, so bail out if this is not so.
483 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
484 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000485 // If the false value simplified to false, then the result of the compare
486 // is equal to "Cond && TCmp". This also catches the case when the false
487 // value simplified to false and the true value to true, returning "Cond".
488 if (match(FCmp, m_Zero()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000489 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000490 return V;
491 // If the true value simplified to true, then the result of the compare
492 // is equal to "Cond || FCmp".
493 if (match(TCmp, m_One()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000494 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000495 return V;
496 // Finally, if the false value simplified to true and the true value to
497 // false, then the result of the compare is equal to "!Cond".
498 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
499 if (Value *V =
500 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000501 Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000502 return V;
503
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000504 return 0;
505}
506
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000507/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
508/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
509/// it on the incoming phi values yields the same result for every value. If so
510/// returns the common value, otherwise returns null.
511static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000512 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000513 // Recursion is always used, so bail out at once if we already hit the limit.
514 if (!MaxRecurse--)
515 return 0;
516
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000517 PHINode *PI;
518 if (isa<PHINode>(LHS)) {
519 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000520 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000521 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000522 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000523 } else {
524 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
525 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000526 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000527 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000528 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000529 }
530
531 // Evaluate the BinOp on the incoming phi values.
532 Value *CommonValue = 0;
533 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000534 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000535 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000536 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000537 Value *V = PI == LHS ?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000538 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
539 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000540 // If the operation failed to simplify, or simplified to a different value
541 // to previously, then give up.
542 if (!V || (CommonValue && V != CommonValue))
543 return 0;
544 CommonValue = V;
545 }
546
547 return CommonValue;
548}
549
550/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
551/// try to simplify the comparison by seeing whether comparing with all of the
552/// incoming phi values yields the same result every time. If so returns the
553/// common result, otherwise returns null.
554static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000555 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000556 // Recursion is always used, so bail out at once if we already hit the limit.
557 if (!MaxRecurse--)
558 return 0;
559
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000560 // Make sure the phi is on the LHS.
561 if (!isa<PHINode>(LHS)) {
562 std::swap(LHS, RHS);
563 Pred = CmpInst::getSwappedPredicate(Pred);
564 }
565 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
566 PHINode *PI = cast<PHINode>(LHS);
567
Duncan Sands18450092010-11-16 12:16:38 +0000568 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000569 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000570 return 0;
571
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000572 // Evaluate the BinOp on the incoming phi values.
573 Value *CommonValue = 0;
574 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000575 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000576 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000577 if (Incoming == PI) continue;
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000578 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000579 // If the operation failed to simplify, or simplified to a different value
580 // to previously, then give up.
581 if (!V || (CommonValue && V != CommonValue))
582 return 0;
583 CommonValue = V;
584 }
585
586 return CommonValue;
587}
588
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000589/// SimplifyAddInst - Given operands for an Add, see if we can
590/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000591static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000592 const Query &Q, unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000593 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
594 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
595 Constant *Ops[] = { CLHS, CRHS };
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000596 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
597 Q.TD, Q.TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000598 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000599
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000600 // Canonicalize the constant to the RHS.
601 std::swap(Op0, Op1);
602 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000603
Duncan Sandsfea3b212010-12-15 14:07:39 +0000604 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000605 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000606 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000607
Duncan Sandsfea3b212010-12-15 14:07:39 +0000608 // X + 0 -> X
609 if (match(Op1, m_Zero()))
610 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000611
Duncan Sandsfea3b212010-12-15 14:07:39 +0000612 // X + (Y - X) -> Y
613 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000614 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000615 Value *Y = 0;
616 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
617 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000618 return Y;
619
620 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000621 if (match(Op0, m_Not(m_Specific(Op1))) ||
622 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000623 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000624
Duncan Sands82fdab32010-12-21 14:00:22 +0000625 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000626 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000627 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000628 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000629
Duncan Sands566edb02010-12-21 08:49:00 +0000630 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000631 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands566edb02010-12-21 08:49:00 +0000632 MaxRecurse))
633 return V;
634
Duncan Sands3421d902010-12-21 13:32:22 +0000635 // Mul distributes over Add. Try some generic simplifications based on this.
636 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000637 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000638 return V;
639
Duncan Sands87689cf2010-11-19 09:20:39 +0000640 // Threading Add over selects and phi nodes is pointless, so don't bother.
641 // Threading over the select in "A + select(cond, B, C)" means evaluating
642 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
643 // only if B and C are equal. If B and C are equal then (since we assume
644 // that operands have already been simplified) "select(cond, B, C)" should
645 // have been simplified to the common value of B and C already. Analysing
646 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
647 // for threading over phi nodes.
648
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000649 return 0;
650}
651
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000652Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000653 const TargetData *TD, const TargetLibraryInfo *TLI,
654 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000655 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
656 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000657}
658
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000659/// \brief Accumulate the constant integer offset a GEP represents.
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000660///
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000661/// Given a getelementptr instruction/constantexpr, accumulate the constant
662/// offset from the base pointer into the provided APInt 'Offset'. Returns true
663/// if the GEP has all-constant indices. Returns false if any non-constant
664/// index is encountered leaving the 'Offset' in an undefined state. The
665/// 'Offset' APInt must be the bitwidth of the target's pointer size.
666static bool accumulateGEPOffset(const TargetData &TD, GEPOperator *GEP,
667 APInt &Offset) {
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000668 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000669 assert(IntPtrWidth == Offset.getBitWidth());
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000670
671 gep_type_iterator GTI = gep_type_begin(GEP);
672 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
673 ++I, ++GTI) {
674 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000675 if (!OpC) return false;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000676 if (OpC->isZero()) continue;
677
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000678 // Handle a struct index, which adds its field offset to the pointer.
679 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000680 unsigned ElementIdx = OpC->getZExtValue();
681 const StructLayout *SL = TD.getStructLayout(STy);
Duncan Sandsf72e0ca2012-03-15 20:14:42 +0000682 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000683 continue;
684 }
685
Duncan Sandsf72e0ca2012-03-15 20:14:42 +0000686 APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()));
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000687 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000688 }
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000689 return true;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000690}
691
692/// \brief Compute the base pointer and cumulative constant offsets for V.
693///
694/// This strips all constant offsets off of V, leaving it the base pointer, and
695/// accumulates the total constant offset applied in the returned constant. It
696/// returns 0 if V is not a pointer, and returns the constant '0' if there are
697/// no constant offsets applied.
698static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
699 Value *&V) {
700 if (!V->getType()->isPointerTy())
701 return 0;
702
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000703 unsigned IntPtrWidth = TD.getPointerSizeInBits();
704 APInt Offset = APInt::getNullValue(IntPtrWidth);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000705
706 // Even though we don't look through PHI nodes, we could be called on an
707 // instruction in an unreachable block, which may be on a cycle.
708 SmallPtrSet<Value *, 4> Visited;
709 Visited.insert(V);
710 do {
711 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000712 if (!accumulateGEPOffset(TD, GEP, Offset))
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000713 break;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000714 V = GEP->getPointerOperand();
715 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
716 V = cast<Operator>(V)->getOperand(0);
717 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
718 if (GA->mayBeOverridden())
719 break;
720 V = GA->getAliasee();
721 } else {
722 break;
723 }
724 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
725 } while (Visited.insert(V));
726
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000727 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
728 return ConstantInt::get(IntPtrTy, Offset);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000729}
730
731/// \brief Compute the constant difference between two pointer values.
732/// If the difference is not a constant, returns zero.
733static Constant *computePointerDifference(const TargetData &TD,
734 Value *LHS, Value *RHS) {
735 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
736 if (!LHSOffset)
737 return 0;
738 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
739 if (!RHSOffset)
740 return 0;
741
742 // If LHS and RHS are not related via constant offsets to the same base
743 // value, there is nothing we can do here.
744 if (LHS != RHS)
745 return 0;
746
747 // Otherwise, the difference of LHS - RHS can be computed as:
748 // LHS - RHS
749 // = (LHSOffset + Base) - (RHSOffset + Base)
750 // = LHSOffset - RHSOffset
751 return ConstantExpr::getSub(LHSOffset, RHSOffset);
752}
753
Duncan Sandsfea3b212010-12-15 14:07:39 +0000754/// SimplifySubInst - Given operands for a Sub, see if we can
755/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000756static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000757 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000758 if (Constant *CLHS = dyn_cast<Constant>(Op0))
759 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
760 Constant *Ops[] = { CLHS, CRHS };
761 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000762 Ops, Q.TD, Q.TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000763 }
764
765 // X - undef -> undef
766 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000767 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000768 return UndefValue::get(Op0->getType());
769
770 // X - 0 -> X
771 if (match(Op1, m_Zero()))
772 return Op0;
773
774 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000775 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000776 return Constant::getNullValue(Op0->getType());
777
Duncan Sandsfe02c692011-01-18 09:24:58 +0000778 // (X*2) - X -> X
779 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000780 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000781 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
782 match(Op0, m_Shl(m_Specific(Op1), m_One())))
783 return Op1;
784
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000785 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
786 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
787 Value *Y = 0, *Z = Op1;
788 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
789 // See if "V === Y - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000790 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000791 // It does! Now see if "X + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000792 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000793 // It does, we successfully reassociated!
794 ++NumReassoc;
795 return W;
796 }
797 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000798 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000799 // It does! Now see if "Y + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000800 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000801 // It does, we successfully reassociated!
802 ++NumReassoc;
803 return W;
804 }
805 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000806
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000807 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
808 // For example, X - (X + 1) -> -1
809 X = Op0;
810 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
811 // See if "V === X - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000812 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000813 // It does! Now see if "V - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000814 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000815 // It does, we successfully reassociated!
816 ++NumReassoc;
817 return W;
818 }
819 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000820 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000821 // It does! Now see if "V - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000822 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000823 // It does, we successfully reassociated!
824 ++NumReassoc;
825 return W;
826 }
827 }
828
829 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
830 // For example, X - (X - Y) -> Y.
831 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000832 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
833 // See if "V === Z - X" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000834 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000835 // It does! Now see if "V + Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000836 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsc087e202011-01-14 15:26:10 +0000837 // It does, we successfully reassociated!
838 ++NumReassoc;
839 return W;
840 }
841
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000842 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
843 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
844 match(Op1, m_Trunc(m_Value(Y))))
845 if (X->getType() == Y->getType())
846 // See if "V === X - Y" simplifies.
847 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
848 // It does! Now see if "trunc V" simplifies.
849 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
850 // It does, return the simplified "trunc V".
851 return W;
852
853 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
854 if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
855 match(Op1, m_PtrToInt(m_Value(Y))))
856 if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
857 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
858
Duncan Sands3421d902010-12-21 13:32:22 +0000859 // Mul distributes over Sub. Try some generic simplifications based on this.
860 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000861 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000862 return V;
863
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000864 // i1 sub -> xor.
865 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000866 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000867 return V;
868
Duncan Sandsfea3b212010-12-15 14:07:39 +0000869 // Threading Sub over selects and phi nodes is pointless, so don't bother.
870 // Threading over the select in "A - select(cond, B, C)" means evaluating
871 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
872 // only if B and C are equal. If B and C are equal then (since we assume
873 // that operands have already been simplified) "select(cond, B, C)" should
874 // have been simplified to the common value of B and C already. Analysing
875 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
876 // for threading over phi nodes.
877
878 return 0;
879}
880
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000881Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000882 const TargetData *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000883 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000884 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
885 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000886}
887
Duncan Sands82fdab32010-12-21 14:00:22 +0000888/// SimplifyMulInst - Given operands for a Mul, see if we can
889/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000890static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
891 unsigned MaxRecurse) {
Duncan Sands82fdab32010-12-21 14:00:22 +0000892 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
893 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
894 Constant *Ops[] = { CLHS, CRHS };
895 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000896 Ops, Q.TD, Q.TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000897 }
898
899 // Canonicalize the constant to the RHS.
900 std::swap(Op0, Op1);
901 }
902
903 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000904 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000905 return Constant::getNullValue(Op0->getType());
906
907 // X * 0 -> 0
908 if (match(Op1, m_Zero()))
909 return Op1;
910
911 // X * 1 -> X
912 if (match(Op1, m_One()))
913 return Op0;
914
Duncan Sands1895e982011-01-30 18:03:50 +0000915 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000916 Value *X = 0;
917 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
918 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
919 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000920
Nick Lewycky54138802011-01-29 19:55:23 +0000921 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000922 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000923 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000924 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000925
926 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000927 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000928 MaxRecurse))
929 return V;
930
931 // Mul distributes over Add. Try some generic simplifications based on this.
932 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000933 Q, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +0000934 return V;
935
936 // If the operation is with the result of a select instruction, check whether
937 // operating on either branch of the select always yields the same value.
938 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000939 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000940 MaxRecurse))
941 return V;
942
943 // If the operation is with the result of a phi instruction, check whether
944 // operating on all incoming values of the phi always yields the same value.
945 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000946 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000947 MaxRecurse))
948 return V;
949
950 return 0;
951}
952
953Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000954 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000955 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000956 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +0000957}
958
Duncan Sands593faa52011-01-28 16:51:11 +0000959/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
960/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000961static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000962 const Query &Q, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +0000963 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
964 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
965 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000966 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sands593faa52011-01-28 16:51:11 +0000967 }
968 }
969
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000970 bool isSigned = Opcode == Instruction::SDiv;
971
Duncan Sands593faa52011-01-28 16:51:11 +0000972 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000973 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000974 return Op1;
975
976 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000977 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000978 return Constant::getNullValue(Op0->getType());
979
980 // 0 / X -> 0, we don't need to preserve faults!
981 if (match(Op0, m_Zero()))
982 return Op0;
983
984 // X / 1 -> X
985 if (match(Op1, m_One()))
986 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000987
988 if (Op0->getType()->isIntegerTy(1))
989 // It can't be division by zero, hence it must be division by one.
990 return Op0;
991
992 // X / X -> 1
993 if (Op0 == Op1)
994 return ConstantInt::get(Op0->getType(), 1);
995
996 // (X * Y) / Y -> X if the multiplication does not overflow.
997 Value *X = 0, *Y = 0;
998 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
999 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +00001000 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +00001001 // If the Mul knows it does not overflow, then we are good to go.
1002 if ((isSigned && Mul->hasNoSignedWrap()) ||
1003 (!isSigned && Mul->hasNoUnsignedWrap()))
1004 return X;
Duncan Sands593faa52011-01-28 16:51:11 +00001005 // If X has the form X = A / Y then X * Y cannot overflow.
1006 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1007 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1008 return X;
1009 }
1010
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001011 // (X rem Y) / Y -> 0
1012 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1013 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1014 return Constant::getNullValue(Op0->getType());
1015
1016 // If the operation is with the result of a select instruction, check whether
1017 // operating on either branch of the select always yields the same value.
1018 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001019 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001020 return V;
1021
1022 // If the operation is with the result of a phi instruction, check whether
1023 // operating on all incoming values of the phi always yields the same value.
1024 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001025 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001026 return V;
1027
Duncan Sands593faa52011-01-28 16:51:11 +00001028 return 0;
1029}
1030
1031/// SimplifySDivInst - Given operands for an SDiv, see if we can
1032/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001033static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1034 unsigned MaxRecurse) {
1035 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001036 return V;
1037
Duncan Sands593faa52011-01-28 16:51:11 +00001038 return 0;
1039}
1040
1041Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001042 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001043 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001044 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001045}
1046
1047/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1048/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001049static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1050 unsigned MaxRecurse) {
1051 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001052 return V;
1053
Duncan Sands593faa52011-01-28 16:51:11 +00001054 return 0;
1055}
1056
1057Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001058 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001059 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001060 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001061}
1062
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001063static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1064 unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001065 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001066 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001067 return Op0;
1068
1069 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001070 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001071 return Op1;
1072
1073 return 0;
1074}
1075
1076Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001077 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001078 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001079 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001080}
1081
Duncan Sandsf24ed772011-05-02 16:27:02 +00001082/// SimplifyRem - Given operands for an SRem or URem, see if we can
1083/// fold the result. If not, this returns null.
1084static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001085 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001086 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1087 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1088 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001089 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001090 }
1091 }
1092
Duncan Sandsf24ed772011-05-02 16:27:02 +00001093 // X % undef -> undef
1094 if (match(Op1, m_Undef()))
1095 return Op1;
1096
1097 // undef % X -> 0
1098 if (match(Op0, m_Undef()))
1099 return Constant::getNullValue(Op0->getType());
1100
1101 // 0 % X -> 0, we don't need to preserve faults!
1102 if (match(Op0, m_Zero()))
1103 return Op0;
1104
1105 // X % 0 -> undef, we don't need to preserve faults!
1106 if (match(Op1, m_Zero()))
1107 return UndefValue::get(Op0->getType());
1108
1109 // X % 1 -> 0
1110 if (match(Op1, m_One()))
1111 return Constant::getNullValue(Op0->getType());
1112
1113 if (Op0->getType()->isIntegerTy(1))
1114 // It can't be remainder by zero, hence it must be remainder by one.
1115 return Constant::getNullValue(Op0->getType());
1116
1117 // X % X -> 0
1118 if (Op0 == Op1)
1119 return Constant::getNullValue(Op0->getType());
1120
1121 // If the operation is with the result of a select instruction, check whether
1122 // operating on either branch of the select always yields the same value.
1123 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001124 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001125 return V;
1126
1127 // If the operation is with the result of a phi instruction, check whether
1128 // operating on all incoming values of the phi always yields the same value.
1129 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001130 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001131 return V;
1132
1133 return 0;
1134}
1135
1136/// SimplifySRemInst - Given operands for an SRem, see if we can
1137/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001138static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1139 unsigned MaxRecurse) {
1140 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001141 return V;
1142
1143 return 0;
1144}
1145
1146Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001147 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001148 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001149 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001150}
1151
1152/// SimplifyURemInst - Given operands for a URem, see if we can
1153/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001154static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001155 unsigned MaxRecurse) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001156 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001157 return V;
1158
1159 return 0;
1160}
1161
1162Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001163 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001164 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001165 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001166}
1167
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001168static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +00001169 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001170 // undef % X -> undef (the undef could be a snan).
1171 if (match(Op0, m_Undef()))
1172 return Op0;
1173
1174 // X % undef -> undef
1175 if (match(Op1, m_Undef()))
1176 return Op1;
1177
1178 return 0;
1179}
1180
1181Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001182 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001183 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001184 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001185}
1186
Duncan Sandscf80bc12011-01-14 14:44:12 +00001187/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001188/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001189static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001190 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001191 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1192 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1193 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001194 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001195 }
1196 }
1197
Duncan Sandscf80bc12011-01-14 14:44:12 +00001198 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001199 if (match(Op0, m_Zero()))
1200 return Op0;
1201
Duncan Sandscf80bc12011-01-14 14:44:12 +00001202 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001203 if (match(Op1, m_Zero()))
1204 return Op0;
1205
Duncan Sandscf80bc12011-01-14 14:44:12 +00001206 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001207 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001208 return Op1;
1209
1210 // Shifting by the bitwidth or more is undefined.
1211 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1212 if (CI->getValue().getLimitedValue() >=
1213 Op0->getType()->getScalarSizeInBits())
1214 return UndefValue::get(Op0->getType());
1215
Duncan Sandscf80bc12011-01-14 14:44:12 +00001216 // If the operation is with the result of a select instruction, check whether
1217 // operating on either branch of the select always yields the same value.
1218 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001219 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001220 return V;
1221
1222 // If the operation is with the result of a phi instruction, check whether
1223 // operating on all incoming values of the phi always yields the same value.
1224 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001225 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001226 return V;
1227
1228 return 0;
1229}
1230
1231/// SimplifyShlInst - Given operands for an Shl, see if we can
1232/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001233static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001234 const Query &Q, unsigned MaxRecurse) {
1235 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001236 return V;
1237
1238 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001239 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001240 return Constant::getNullValue(Op0->getType());
1241
Chris Lattner81a0dc92011-02-09 17:15:04 +00001242 // (X >> A) << A -> X
1243 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001244 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001245 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001246 return 0;
1247}
1248
Chris Lattner81a0dc92011-02-09 17:15:04 +00001249Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001250 const TargetData *TD, const TargetLibraryInfo *TLI,
1251 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001252 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1253 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001254}
1255
1256/// SimplifyLShrInst - Given operands for an LShr, see if we can
1257/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001258static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001259 const Query &Q, unsigned MaxRecurse) {
1260 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001261 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001262
1263 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001264 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001265 return Constant::getNullValue(Op0->getType());
1266
Chris Lattner81a0dc92011-02-09 17:15:04 +00001267 // (X << A) >> A -> X
1268 Value *X;
1269 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1270 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1271 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001272
Duncan Sandsc43cee32011-01-14 00:37:45 +00001273 return 0;
1274}
1275
Chris Lattner81a0dc92011-02-09 17:15:04 +00001276Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001277 const TargetData *TD,
1278 const TargetLibraryInfo *TLI,
1279 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001280 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1281 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001282}
1283
1284/// SimplifyAShrInst - Given operands for an AShr, see if we can
1285/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001286static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001287 const Query &Q, unsigned MaxRecurse) {
1288 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001289 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001290
1291 // all ones >>a X -> all ones
1292 if (match(Op0, m_AllOnes()))
1293 return Op0;
1294
1295 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001296 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001297 return Constant::getAllOnesValue(Op0->getType());
1298
Chris Lattner81a0dc92011-02-09 17:15:04 +00001299 // (X << A) >> A -> X
1300 Value *X;
1301 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1302 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1303 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001304
Duncan Sandsc43cee32011-01-14 00:37:45 +00001305 return 0;
1306}
1307
Chris Lattner81a0dc92011-02-09 17:15:04 +00001308Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001309 const TargetData *TD,
1310 const TargetLibraryInfo *TLI,
1311 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001312 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1313 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001314}
1315
Chris Lattnerd06094f2009-11-10 00:55:12 +00001316/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001317/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001318static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001319 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001320 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1321 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1322 Constant *Ops[] = { CLHS, CRHS };
1323 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001324 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001325 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001326
Chris Lattnerd06094f2009-11-10 00:55:12 +00001327 // Canonicalize the constant to the RHS.
1328 std::swap(Op0, Op1);
1329 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001330
Chris Lattnerd06094f2009-11-10 00:55:12 +00001331 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001332 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001333 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001334
Chris Lattnerd06094f2009-11-10 00:55:12 +00001335 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001336 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001337 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001338
Duncan Sands2b749872010-11-17 18:52:15 +00001339 // X & 0 = 0
1340 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001341 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001342
Duncan Sands2b749872010-11-17 18:52:15 +00001343 // X & -1 = X
1344 if (match(Op1, m_AllOnes()))
1345 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001346
Chris Lattnerd06094f2009-11-10 00:55:12 +00001347 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001348 if (match(Op0, m_Not(m_Specific(Op1))) ||
1349 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001350 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001351
Chris Lattnerd06094f2009-11-10 00:55:12 +00001352 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001353 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001354 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001355 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001356 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001357
Chris Lattnerd06094f2009-11-10 00:55:12 +00001358 // A & (A | ?) = A
1359 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001360 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001361 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001362
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001363 // A & (-A) = A if A is a power of two or zero.
1364 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1365 match(Op1, m_Neg(m_Specific(Op0)))) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001366 if (isPowerOfTwo(Op0, Q.TD, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001367 return Op0;
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001368 if (isPowerOfTwo(Op1, Q.TD, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001369 return Op1;
1370 }
1371
Duncan Sands566edb02010-12-21 08:49:00 +00001372 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001373 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1374 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001375 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001376
Duncan Sands3421d902010-12-21 13:32:22 +00001377 // And distributes over Or. Try some generic simplifications based on this.
1378 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001379 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001380 return V;
1381
1382 // And distributes over Xor. Try some generic simplifications based on this.
1383 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001384 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001385 return V;
1386
1387 // Or distributes over And. Try some generic simplifications based on this.
1388 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001389 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001390 return V;
1391
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001392 // If the operation is with the result of a select instruction, check whether
1393 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001394 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001395 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1396 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001397 return V;
1398
1399 // If the operation is with the result of a phi instruction, check whether
1400 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001401 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001402 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001403 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001404 return V;
1405
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001406 return 0;
1407}
1408
Duncan Sands18450092010-11-16 12:16:38 +00001409Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001410 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001411 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001412 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001413}
1414
Chris Lattnerd06094f2009-11-10 00:55:12 +00001415/// SimplifyOrInst - Given operands for an Or, see if we can
1416/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001417static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1418 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001419 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1420 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1421 Constant *Ops[] = { CLHS, CRHS };
1422 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001423 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001424 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001425
Chris Lattnerd06094f2009-11-10 00:55:12 +00001426 // Canonicalize the constant to the RHS.
1427 std::swap(Op0, Op1);
1428 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001429
Chris Lattnerd06094f2009-11-10 00:55:12 +00001430 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001431 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001432 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001433
Chris Lattnerd06094f2009-11-10 00:55:12 +00001434 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001435 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001436 return Op0;
1437
Duncan Sands2b749872010-11-17 18:52:15 +00001438 // X | 0 = X
1439 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001440 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001441
Duncan Sands2b749872010-11-17 18:52:15 +00001442 // X | -1 = -1
1443 if (match(Op1, m_AllOnes()))
1444 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001445
Chris Lattnerd06094f2009-11-10 00:55:12 +00001446 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001447 if (match(Op0, m_Not(m_Specific(Op1))) ||
1448 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001449 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001450
Chris Lattnerd06094f2009-11-10 00:55:12 +00001451 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001452 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001453 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001454 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001455 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001456
Chris Lattnerd06094f2009-11-10 00:55:12 +00001457 // A | (A & ?) = A
1458 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001459 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001460 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001461
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001462 // ~(A & ?) | A = -1
1463 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1464 (A == Op1 || B == Op1))
1465 return Constant::getAllOnesValue(Op1->getType());
1466
1467 // A | ~(A & ?) = -1
1468 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1469 (A == Op0 || B == Op0))
1470 return Constant::getAllOnesValue(Op0->getType());
1471
Duncan Sands566edb02010-12-21 08:49:00 +00001472 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001473 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1474 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001475 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001476
Duncan Sands3421d902010-12-21 13:32:22 +00001477 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001478 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1479 MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001480 return V;
1481
1482 // And distributes over Or. Try some generic simplifications based on this.
1483 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001484 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001485 return V;
1486
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001487 // If the operation is with the result of a select instruction, check whether
1488 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001489 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001490 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001491 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001492 return V;
1493
1494 // If the operation is with the result of a phi instruction, check whether
1495 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001496 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001497 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001498 return V;
1499
Chris Lattnerd06094f2009-11-10 00:55:12 +00001500 return 0;
1501}
1502
Duncan Sands18450092010-11-16 12:16:38 +00001503Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001504 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001505 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001506 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001507}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001508
Duncan Sands2b749872010-11-17 18:52:15 +00001509/// SimplifyXorInst - Given operands for a Xor, see if we can
1510/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001511static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1512 unsigned MaxRecurse) {
Duncan Sands2b749872010-11-17 18:52:15 +00001513 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1514 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1515 Constant *Ops[] = { CLHS, CRHS };
1516 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001517 Ops, Q.TD, Q.TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001518 }
1519
1520 // Canonicalize the constant to the RHS.
1521 std::swap(Op0, Op1);
1522 }
1523
1524 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001525 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001526 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001527
1528 // A ^ 0 = A
1529 if (match(Op1, m_Zero()))
1530 return Op0;
1531
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001532 // A ^ A = 0
1533 if (Op0 == Op1)
1534 return Constant::getNullValue(Op0->getType());
1535
Duncan Sands2b749872010-11-17 18:52:15 +00001536 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001537 if (match(Op0, m_Not(m_Specific(Op1))) ||
1538 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001539 return Constant::getAllOnesValue(Op0->getType());
1540
Duncan Sands566edb02010-12-21 08:49:00 +00001541 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001542 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1543 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001544 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001545
Duncan Sands3421d902010-12-21 13:32:22 +00001546 // And distributes over Xor. Try some generic simplifications based on this.
1547 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001548 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001549 return V;
1550
Duncan Sands87689cf2010-11-19 09:20:39 +00001551 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1552 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1553 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1554 // only if B and C are equal. If B and C are equal then (since we assume
1555 // that operands have already been simplified) "select(cond, B, C)" should
1556 // have been simplified to the common value of B and C already. Analysing
1557 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1558 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001559
1560 return 0;
1561}
1562
1563Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001564 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001565 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001566 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001567}
1568
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001569static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001570 return CmpInst::makeCmpResultType(Op->getType());
1571}
1572
Duncan Sandse864b5b2011-05-07 16:56:49 +00001573/// ExtractEquivalentCondition - Rummage around inside V looking for something
1574/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1575/// otherwise return null. Helper function for analyzing max/min idioms.
1576static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1577 Value *LHS, Value *RHS) {
1578 SelectInst *SI = dyn_cast<SelectInst>(V);
1579 if (!SI)
1580 return 0;
1581 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1582 if (!Cmp)
1583 return 0;
1584 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1585 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1586 return Cmp;
1587 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1588 LHS == CmpRHS && RHS == CmpLHS)
1589 return Cmp;
1590 return 0;
1591}
1592
Chris Lattner009e2652012-02-24 19:01:58 +00001593
Chris Lattner9dbb4292009-11-09 23:28:39 +00001594/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1595/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001596static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001597 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001598 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001599 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001600
Chris Lattnerd06094f2009-11-10 00:55:12 +00001601 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001602 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001603 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001604
1605 // If we have a constant, make sure it is on the RHS.
1606 std::swap(LHS, RHS);
1607 Pred = CmpInst::getSwappedPredicate(Pred);
1608 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001609
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001610 Type *ITy = GetCompareTy(LHS); // The return type.
1611 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001612
Chris Lattner210c5d42009-11-09 23:55:12 +00001613 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001614 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1615 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001616 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001617 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001618
Duncan Sands6dc91252011-01-13 08:56:29 +00001619 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001620 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001621 switch (Pred) {
1622 default: break;
1623 case ICmpInst::ICMP_EQ:
1624 // X == 1 -> X
1625 if (match(RHS, m_One()))
1626 return LHS;
1627 break;
1628 case ICmpInst::ICMP_NE:
1629 // X != 0 -> X
1630 if (match(RHS, m_Zero()))
1631 return LHS;
1632 break;
1633 case ICmpInst::ICMP_UGT:
1634 // X >u 0 -> X
1635 if (match(RHS, m_Zero()))
1636 return LHS;
1637 break;
1638 case ICmpInst::ICMP_UGE:
1639 // X >=u 1 -> X
1640 if (match(RHS, m_One()))
1641 return LHS;
1642 break;
1643 case ICmpInst::ICMP_SLT:
1644 // X <s 0 -> X
1645 if (match(RHS, m_Zero()))
1646 return LHS;
1647 break;
1648 case ICmpInst::ICMP_SLE:
1649 // X <=s -1 -> X
1650 if (match(RHS, m_One()))
1651 return LHS;
1652 break;
1653 }
1654 }
1655
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001656 // icmp <object*>, <object*/null> - Different identified objects have
1657 // different addresses (unless null), and what's more the address of an
1658 // identified local is never equal to another argument (again, barring null).
1659 // Note that generalizing to the case where LHS is a global variable address
1660 // or null is pointless, since if both LHS and RHS are constants then we
1661 // already constant folded the compare, and if only one of them is then we
1662 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001663 Value *LHSPtr = LHS->stripPointerCasts();
1664 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001665 if (LHSPtr == RHSPtr)
1666 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001667
Chris Lattnerb053fc12012-02-20 00:42:49 +00001668 // Be more aggressive about stripping pointer adjustments when checking a
1669 // comparison of an alloca address to another object. We can rip off all
1670 // inbounds GEP operations, even if they are variable.
Chandler Carruth84dfc322012-03-10 08:39:09 +00001671 LHSPtr = LHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001672 if (llvm::isIdentifiedObject(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001673 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001674 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1675 // If both sides are different identified objects, they aren't equal
1676 // unless they're null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001677 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001678 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001679 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001680
1681 // A local identified object (alloca or noalias call) can't equal any
1682 // incoming argument, unless they're both null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001683 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001684 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001685 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001686 }
1687
1688 // Assume that the constant null is on the right.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001689 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001690 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001691 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001692 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001693 return ConstantInt::get(ITy, true);
1694 }
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001695 } else if (isa<Argument>(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001696 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001697 // An alloca can't be equal to an argument.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001698 if (isa<AllocaInst>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001699 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001700 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001701 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001702 return ConstantInt::get(ITy, true);
1703 }
Chris Lattnerb053fc12012-02-20 00:42:49 +00001704 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001705
1706 // If we are comparing with zero then try hard since this is a common case.
1707 if (match(RHS, m_Zero())) {
1708 bool LHSKnownNonNegative, LHSKnownNegative;
1709 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001710 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001711 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001712 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001713 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001714 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001715 case ICmpInst::ICMP_EQ:
1716 case ICmpInst::ICMP_ULE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001717 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001718 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001719 break;
1720 case ICmpInst::ICMP_NE:
1721 case ICmpInst::ICMP_UGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001722 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001723 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001724 break;
1725 case ICmpInst::ICMP_SLT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001726 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001727 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001728 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001729 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001730 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001731 break;
1732 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001733 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001734 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001735 return getTrue(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001736 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001737 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001738 break;
1739 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001740 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001741 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001742 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001743 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001744 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001745 break;
1746 case ICmpInst::ICMP_SGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001747 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001748 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001749 return getFalse(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001750 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001751 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001752 break;
1753 }
1754 }
1755
1756 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001757 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001758 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1759 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1760 if (RHS_CR.isEmptySet())
1761 return ConstantInt::getFalse(CI->getContext());
1762 if (RHS_CR.isFullSet())
1763 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001764
Nick Lewycky3a73e342011-03-04 07:00:57 +00001765 // Many binary operators with constant RHS have easy to compute constant
1766 // range. Use them to check whether the comparison is a tautology.
1767 uint32_t Width = CI->getBitWidth();
1768 APInt Lower = APInt(Width, 0);
1769 APInt Upper = APInt(Width, 0);
1770 ConstantInt *CI2;
1771 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1772 // 'urem x, CI2' produces [0, CI2).
1773 Upper = CI2->getValue();
1774 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1775 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1776 Upper = CI2->getValue().abs();
1777 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001778 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1779 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001780 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001781 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1782 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1783 APInt NegOne = APInt::getAllOnesValue(Width);
1784 if (!CI2->isZero())
1785 Upper = NegOne.udiv(CI2->getValue()) + 1;
1786 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1787 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1788 APInt IntMin = APInt::getSignedMinValue(Width);
1789 APInt IntMax = APInt::getSignedMaxValue(Width);
1790 APInt Val = CI2->getValue().abs();
1791 if (!Val.isMinValue()) {
1792 Lower = IntMin.sdiv(Val);
1793 Upper = IntMax.sdiv(Val) + 1;
1794 }
1795 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1796 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1797 APInt NegOne = APInt::getAllOnesValue(Width);
1798 if (CI2->getValue().ult(Width))
1799 Upper = NegOne.lshr(CI2->getValue()) + 1;
1800 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1801 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1802 APInt IntMin = APInt::getSignedMinValue(Width);
1803 APInt IntMax = APInt::getSignedMaxValue(Width);
1804 if (CI2->getValue().ult(Width)) {
1805 Lower = IntMin.ashr(CI2->getValue());
1806 Upper = IntMax.ashr(CI2->getValue()) + 1;
1807 }
1808 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1809 // 'or x, CI2' produces [CI2, UINT_MAX].
1810 Lower = CI2->getValue();
1811 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1812 // 'and x, CI2' produces [0, CI2].
1813 Upper = CI2->getValue() + 1;
1814 }
1815 if (Lower != Upper) {
1816 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1817 if (RHS_CR.contains(LHS_CR))
1818 return ConstantInt::getTrue(RHS->getContext());
1819 if (RHS_CR.inverse().contains(LHS_CR))
1820 return ConstantInt::getFalse(RHS->getContext());
1821 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001822 }
1823
Duncan Sands9d32f602011-01-20 13:21:55 +00001824 // Compare of cast, for example (zext X) != 0 -> X != 0
1825 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1826 Instruction *LI = cast<CastInst>(LHS);
1827 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001828 Type *SrcTy = SrcOp->getType();
1829 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001830
1831 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1832 // if the integer type is the same size as the pointer type.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001833 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
1834 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands9d32f602011-01-20 13:21:55 +00001835 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1836 // Transfer the cast to the constant.
1837 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1838 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001839 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001840 return V;
1841 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1842 if (RI->getOperand(0)->getType() == SrcTy)
1843 // Compare without the cast.
1844 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001845 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001846 return V;
1847 }
1848 }
1849
1850 if (isa<ZExtInst>(LHS)) {
1851 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1852 // same type.
1853 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1854 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1855 // Compare X and Y. Note that signed predicates become unsigned.
1856 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001857 SrcOp, RI->getOperand(0), Q,
Duncan Sands9d32f602011-01-20 13:21:55 +00001858 MaxRecurse-1))
1859 return V;
1860 }
1861 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1862 // too. If not, then try to deduce the result of the comparison.
1863 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1864 // Compute the constant that would happen if we truncated to SrcTy then
1865 // reextended to DstTy.
1866 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1867 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1868
1869 // If the re-extended constant didn't change then this is effectively
1870 // also a case of comparing two zero-extended values.
1871 if (RExt == CI && MaxRecurse)
1872 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001873 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001874 return V;
1875
1876 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1877 // there. Use this to work out the result of the comparison.
1878 if (RExt != CI) {
1879 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001880 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001881 // LHS <u RHS.
1882 case ICmpInst::ICMP_EQ:
1883 case ICmpInst::ICMP_UGT:
1884 case ICmpInst::ICMP_UGE:
1885 return ConstantInt::getFalse(CI->getContext());
1886
1887 case ICmpInst::ICMP_NE:
1888 case ICmpInst::ICMP_ULT:
1889 case ICmpInst::ICMP_ULE:
1890 return ConstantInt::getTrue(CI->getContext());
1891
1892 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1893 // is non-negative then LHS <s RHS.
1894 case ICmpInst::ICMP_SGT:
1895 case ICmpInst::ICMP_SGE:
1896 return CI->getValue().isNegative() ?
1897 ConstantInt::getTrue(CI->getContext()) :
1898 ConstantInt::getFalse(CI->getContext());
1899
1900 case ICmpInst::ICMP_SLT:
1901 case ICmpInst::ICMP_SLE:
1902 return CI->getValue().isNegative() ?
1903 ConstantInt::getFalse(CI->getContext()) :
1904 ConstantInt::getTrue(CI->getContext());
1905 }
1906 }
1907 }
1908 }
1909
1910 if (isa<SExtInst>(LHS)) {
1911 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1912 // same type.
1913 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1914 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1915 // Compare X and Y. Note that the predicate does not change.
1916 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001917 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001918 return V;
1919 }
1920 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1921 // too. If not, then try to deduce the result of the comparison.
1922 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1923 // Compute the constant that would happen if we truncated to SrcTy then
1924 // reextended to DstTy.
1925 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1926 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1927
1928 // If the re-extended constant didn't change then this is effectively
1929 // also a case of comparing two sign-extended values.
1930 if (RExt == CI && MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001931 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001932 return V;
1933
1934 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1935 // bits there. Use this to work out the result of the comparison.
1936 if (RExt != CI) {
1937 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001938 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001939 case ICmpInst::ICMP_EQ:
1940 return ConstantInt::getFalse(CI->getContext());
1941 case ICmpInst::ICMP_NE:
1942 return ConstantInt::getTrue(CI->getContext());
1943
1944 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1945 // LHS >s RHS.
1946 case ICmpInst::ICMP_SGT:
1947 case ICmpInst::ICMP_SGE:
1948 return CI->getValue().isNegative() ?
1949 ConstantInt::getTrue(CI->getContext()) :
1950 ConstantInt::getFalse(CI->getContext());
1951 case ICmpInst::ICMP_SLT:
1952 case ICmpInst::ICMP_SLE:
1953 return CI->getValue().isNegative() ?
1954 ConstantInt::getFalse(CI->getContext()) :
1955 ConstantInt::getTrue(CI->getContext());
1956
1957 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1958 // LHS >u RHS.
1959 case ICmpInst::ICMP_UGT:
1960 case ICmpInst::ICMP_UGE:
1961 // Comparison is true iff the LHS <s 0.
1962 if (MaxRecurse)
1963 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1964 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001965 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001966 return V;
1967 break;
1968 case ICmpInst::ICMP_ULT:
1969 case ICmpInst::ICMP_ULE:
1970 // Comparison is true iff the LHS >=s 0.
1971 if (MaxRecurse)
1972 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1973 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001974 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001975 return V;
1976 break;
1977 }
1978 }
1979 }
1980 }
1981 }
1982
Duncan Sands52fb8462011-02-13 17:15:40 +00001983 // Special logic for binary operators.
1984 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1985 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1986 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001987 // Analyze the case when either LHS or RHS is an add instruction.
1988 Value *A = 0, *B = 0, *C = 0, *D = 0;
1989 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1990 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1991 if (LBO && LBO->getOpcode() == Instruction::Add) {
1992 A = LBO->getOperand(0); B = LBO->getOperand(1);
1993 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1994 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1995 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1996 }
1997 if (RBO && RBO->getOpcode() == Instruction::Add) {
1998 C = RBO->getOperand(0); D = RBO->getOperand(1);
1999 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2000 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2001 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2002 }
2003
2004 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2005 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2006 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2007 Constant::getNullValue(RHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002008 Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002009 return V;
2010
2011 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2012 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2013 if (Value *V = SimplifyICmpInst(Pred,
2014 Constant::getNullValue(LHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002015 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002016 return V;
2017
2018 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2019 if (A && C && (A == C || A == D || B == C || B == D) &&
2020 NoLHSWrapProblem && NoRHSWrapProblem) {
2021 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2022 Value *Y = (A == C || A == D) ? B : A;
2023 Value *Z = (C == A || C == B) ? D : C;
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002024 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002025 return V;
2026 }
2027 }
2028
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002029 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002030 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002031 switch (Pred) {
2032 default:
2033 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002034 case ICmpInst::ICMP_SGT:
2035 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002036 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002037 if (!KnownNonNegative)
2038 break;
2039 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002040 case ICmpInst::ICMP_EQ:
2041 case ICmpInst::ICMP_UGT:
2042 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002043 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002044 case ICmpInst::ICMP_SLT:
2045 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002046 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002047 if (!KnownNonNegative)
2048 break;
2049 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002050 case ICmpInst::ICMP_NE:
2051 case ICmpInst::ICMP_ULT:
2052 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002053 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002054 }
2055 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002056 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2057 bool KnownNonNegative, KnownNegative;
2058 switch (Pred) {
2059 default:
2060 break;
2061 case ICmpInst::ICMP_SGT:
2062 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002063 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002064 if (!KnownNonNegative)
2065 break;
2066 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002067 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002068 case ICmpInst::ICMP_UGT:
2069 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002070 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002071 case ICmpInst::ICMP_SLT:
2072 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002073 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002074 if (!KnownNonNegative)
2075 break;
2076 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002077 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002078 case ICmpInst::ICMP_ULT:
2079 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002080 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002081 }
2082 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002083
Duncan Sandsc65c7472011-10-28 18:17:44 +00002084 // x udiv y <=u x.
2085 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2086 // icmp pred (X /u Y), X
2087 if (Pred == ICmpInst::ICMP_UGT)
2088 return getFalse(ITy);
2089 if (Pred == ICmpInst::ICMP_ULE)
2090 return getTrue(ITy);
2091 }
2092
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002093 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2094 LBO->getOperand(1) == RBO->getOperand(1)) {
2095 switch (LBO->getOpcode()) {
2096 default: break;
2097 case Instruction::UDiv:
2098 case Instruction::LShr:
2099 if (ICmpInst::isSigned(Pred))
2100 break;
2101 // fall-through
2102 case Instruction::SDiv:
2103 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002104 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002105 break;
2106 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002107 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002108 return V;
2109 break;
2110 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002111 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002112 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2113 if (!NUW && !NSW)
2114 break;
2115 if (!NSW && ICmpInst::isSigned(Pred))
2116 break;
2117 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002118 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002119 return V;
2120 break;
2121 }
2122 }
2123 }
2124
Duncan Sandsad206812011-05-03 19:53:10 +00002125 // Simplify comparisons involving max/min.
2126 Value *A, *B;
2127 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2128 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2129
Duncan Sands8140ad32011-05-04 16:05:05 +00002130 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002131 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2132 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2133 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2134 // We analyze this as smax(A, B) pred A.
2135 P = Pred;
2136 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2137 (A == LHS || B == LHS)) {
2138 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2139 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2140 // We analyze this as smax(A, B) swapped-pred A.
2141 P = CmpInst::getSwappedPredicate(Pred);
2142 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2143 (A == RHS || B == RHS)) {
2144 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2145 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2146 // We analyze this as smax(-A, -B) swapped-pred -A.
2147 // Note that we do not need to actually form -A or -B thanks to EqP.
2148 P = CmpInst::getSwappedPredicate(Pred);
2149 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2150 (A == LHS || B == LHS)) {
2151 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2152 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2153 // We analyze this as smax(-A, -B) pred -A.
2154 // Note that we do not need to actually form -A or -B thanks to EqP.
2155 P = Pred;
2156 }
2157 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2158 // Cases correspond to "max(A, B) p A".
2159 switch (P) {
2160 default:
2161 break;
2162 case CmpInst::ICMP_EQ:
2163 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002164 // Equivalent to "A EqP B". This may be the same as the condition tested
2165 // in the max/min; if so, we can just return that.
2166 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2167 return V;
2168 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2169 return V;
2170 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002171 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002172 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002173 return V;
2174 break;
2175 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002176 case CmpInst::ICMP_SGT: {
2177 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2178 // Equivalent to "A InvEqP B". This may be the same as the condition
2179 // tested in the max/min; if so, we can just return that.
2180 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2181 return V;
2182 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2183 return V;
2184 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002185 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002186 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002187 return V;
2188 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002189 }
Duncan Sandsad206812011-05-03 19:53:10 +00002190 case CmpInst::ICMP_SGE:
2191 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002192 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002193 case CmpInst::ICMP_SLT:
2194 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002195 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002196 }
2197 }
2198
Duncan Sands8140ad32011-05-04 16:05:05 +00002199 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002200 P = CmpInst::BAD_ICMP_PREDICATE;
2201 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2202 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2203 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2204 // We analyze this as umax(A, B) pred A.
2205 P = Pred;
2206 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2207 (A == LHS || B == LHS)) {
2208 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2209 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2210 // We analyze this as umax(A, B) swapped-pred A.
2211 P = CmpInst::getSwappedPredicate(Pred);
2212 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2213 (A == RHS || B == RHS)) {
2214 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2215 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2216 // We analyze this as umax(-A, -B) swapped-pred -A.
2217 // Note that we do not need to actually form -A or -B thanks to EqP.
2218 P = CmpInst::getSwappedPredicate(Pred);
2219 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2220 (A == LHS || B == LHS)) {
2221 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2222 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2223 // We analyze this as umax(-A, -B) pred -A.
2224 // Note that we do not need to actually form -A or -B thanks to EqP.
2225 P = Pred;
2226 }
2227 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2228 // Cases correspond to "max(A, B) p A".
2229 switch (P) {
2230 default:
2231 break;
2232 case CmpInst::ICMP_EQ:
2233 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002234 // Equivalent to "A EqP B". This may be the same as the condition tested
2235 // in the max/min; if so, we can just return that.
2236 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2237 return V;
2238 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2239 return V;
2240 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002241 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002242 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002243 return V;
2244 break;
2245 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002246 case CmpInst::ICMP_UGT: {
2247 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2248 // Equivalent to "A InvEqP B". This may be the same as the condition
2249 // tested in the max/min; if so, we can just return that.
2250 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2251 return V;
2252 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2253 return V;
2254 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002255 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002256 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002257 return V;
2258 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002259 }
Duncan Sandsad206812011-05-03 19:53:10 +00002260 case CmpInst::ICMP_UGE:
2261 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002262 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002263 case CmpInst::ICMP_ULT:
2264 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002265 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002266 }
2267 }
2268
Duncan Sands8140ad32011-05-04 16:05:05 +00002269 // Variants on "max(x,y) >= min(x,z)".
2270 Value *C, *D;
2271 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2272 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2273 (A == C || A == D || B == C || B == D)) {
2274 // max(x, ?) pred min(x, ?).
2275 if (Pred == CmpInst::ICMP_SGE)
2276 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002277 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002278 if (Pred == CmpInst::ICMP_SLT)
2279 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002280 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002281 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2282 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2283 (A == C || A == D || B == C || B == D)) {
2284 // min(x, ?) pred max(x, ?).
2285 if (Pred == CmpInst::ICMP_SLE)
2286 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002287 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002288 if (Pred == CmpInst::ICMP_SGT)
2289 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002290 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002291 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2292 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2293 (A == C || A == D || B == C || B == D)) {
2294 // max(x, ?) pred min(x, ?).
2295 if (Pred == CmpInst::ICMP_UGE)
2296 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002297 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002298 if (Pred == CmpInst::ICMP_ULT)
2299 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002300 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002301 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2302 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2303 (A == C || A == D || B == C || B == D)) {
2304 // min(x, ?) pred max(x, ?).
2305 if (Pred == CmpInst::ICMP_ULE)
2306 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002307 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002308 if (Pred == CmpInst::ICMP_UGT)
2309 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002310 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002311 }
2312
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002313 // Simplify comparisons of GEPs.
2314 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2315 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2316 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2317 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2318 (ICmpInst::isEquality(Pred) ||
2319 (GLHS->isInBounds() && GRHS->isInBounds() &&
2320 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2321 // The bases are equal and the indices are constant. Build a constant
2322 // expression GEP with the same indices and a null base pointer to see
2323 // what constant folding can make out of it.
2324 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2325 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2326 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2327
2328 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2329 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2330 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2331 }
2332 }
2333 }
2334
Duncan Sands1ac7c992010-11-07 16:12:23 +00002335 // If the comparison is with the result of a select instruction, check whether
2336 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002337 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002338 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002339 return V;
2340
2341 // If the comparison is with the result of a phi instruction, check whether
2342 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002343 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002344 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002345 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002346
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002347 return 0;
2348}
2349
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002350Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002351 const TargetData *TD,
2352 const TargetLibraryInfo *TLI,
2353 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002354 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2355 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002356}
2357
Chris Lattner9dbb4292009-11-09 23:28:39 +00002358/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2359/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002360static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002361 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002362 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2363 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2364
Chris Lattnerd06094f2009-11-10 00:55:12 +00002365 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002366 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002367 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002368
Chris Lattnerd06094f2009-11-10 00:55:12 +00002369 // If we have a constant, make sure it is on the RHS.
2370 std::swap(LHS, RHS);
2371 Pred = CmpInst::getSwappedPredicate(Pred);
2372 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002373
Chris Lattner210c5d42009-11-09 23:55:12 +00002374 // Fold trivial predicates.
2375 if (Pred == FCmpInst::FCMP_FALSE)
2376 return ConstantInt::get(GetCompareTy(LHS), 0);
2377 if (Pred == FCmpInst::FCMP_TRUE)
2378 return ConstantInt::get(GetCompareTy(LHS), 1);
2379
Chris Lattner210c5d42009-11-09 23:55:12 +00002380 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2381 return UndefValue::get(GetCompareTy(LHS));
2382
2383 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002384 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002385 if (CmpInst::isTrueWhenEqual(Pred))
2386 return ConstantInt::get(GetCompareTy(LHS), 1);
2387 if (CmpInst::isFalseWhenEqual(Pred))
2388 return ConstantInt::get(GetCompareTy(LHS), 0);
2389 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002390
Chris Lattner210c5d42009-11-09 23:55:12 +00002391 // Handle fcmp with constant RHS
2392 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2393 // If the constant is a nan, see if we can fold the comparison based on it.
2394 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2395 if (CFP->getValueAPF().isNaN()) {
2396 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2397 return ConstantInt::getFalse(CFP->getContext());
2398 assert(FCmpInst::isUnordered(Pred) &&
2399 "Comparison must be either ordered or unordered!");
2400 // True if unordered.
2401 return ConstantInt::getTrue(CFP->getContext());
2402 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002403 // Check whether the constant is an infinity.
2404 if (CFP->getValueAPF().isInfinity()) {
2405 if (CFP->getValueAPF().isNegative()) {
2406 switch (Pred) {
2407 case FCmpInst::FCMP_OLT:
2408 // No value is ordered and less than negative infinity.
2409 return ConstantInt::getFalse(CFP->getContext());
2410 case FCmpInst::FCMP_UGE:
2411 // All values are unordered with or at least negative infinity.
2412 return ConstantInt::getTrue(CFP->getContext());
2413 default:
2414 break;
2415 }
2416 } else {
2417 switch (Pred) {
2418 case FCmpInst::FCMP_OGT:
2419 // No value is ordered and greater than infinity.
2420 return ConstantInt::getFalse(CFP->getContext());
2421 case FCmpInst::FCMP_ULE:
2422 // All values are unordered with and at most infinity.
2423 return ConstantInt::getTrue(CFP->getContext());
2424 default:
2425 break;
2426 }
2427 }
2428 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002429 }
2430 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002431
Duncan Sands92826de2010-11-07 16:46:25 +00002432 // If the comparison is with the result of a select instruction, check whether
2433 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002434 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002435 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002436 return V;
2437
2438 // If the comparison is with the result of a phi instruction, check whether
2439 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002440 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002441 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002442 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002443
Chris Lattner9dbb4292009-11-09 23:28:39 +00002444 return 0;
2445}
2446
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002447Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002448 const TargetData *TD,
2449 const TargetLibraryInfo *TLI,
2450 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002451 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2452 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002453}
2454
Chris Lattner04754262010-04-20 05:32:14 +00002455/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2456/// the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002457static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2458 Value *FalseVal, const Query &Q,
2459 unsigned MaxRecurse) {
Chris Lattner04754262010-04-20 05:32:14 +00002460 // select true, X, Y -> X
2461 // select false, X, Y -> Y
2462 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2463 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002464
Chris Lattner04754262010-04-20 05:32:14 +00002465 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002466 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002467 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002468
Chris Lattner04754262010-04-20 05:32:14 +00002469 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2470 if (isa<Constant>(TrueVal))
2471 return TrueVal;
2472 return FalseVal;
2473 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002474 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2475 return FalseVal;
2476 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2477 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002478
Chris Lattner04754262010-04-20 05:32:14 +00002479 return 0;
2480}
2481
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002482Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2483 const TargetData *TD,
2484 const TargetLibraryInfo *TLI,
2485 const DominatorTree *DT) {
2486 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2487 RecursionLimit);
2488}
2489
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002490/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2491/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002492static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002493 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002494 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2495 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2496 if (!PtrTy)
2497 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002498
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002499 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002500 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002501 return Ops[0];
2502
Duncan Sands85bbff62010-11-22 13:42:49 +00002503 if (isa<UndefValue>(Ops[0])) {
2504 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002505 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002506 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002507 return UndefValue::get(GEPTy);
2508 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002509
Jay Foadb9b54eb2011-07-19 15:07:52 +00002510 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002511 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002512 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2513 if (C->isZero())
2514 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002515 // getelementptr P, N -> P if P points to a type of zero size.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002516 if (Q.TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002517 Type *Ty = PtrTy->getElementType();
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002518 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002519 return Ops[0];
2520 }
2521 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002522
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002523 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002524 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002525 if (!isa<Constant>(Ops[i]))
2526 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002527
Jay Foaddab3d292011-07-21 14:31:17 +00002528 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002529}
2530
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002531Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2532 const TargetLibraryInfo *TLI,
2533 const DominatorTree *DT) {
2534 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2535}
2536
Duncan Sandsdabc2802011-09-05 06:52:48 +00002537/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2538/// can fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002539static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2540 ArrayRef<unsigned> Idxs, const Query &Q,
2541 unsigned) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002542 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2543 if (Constant *CVal = dyn_cast<Constant>(Val))
2544 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2545
2546 // insertvalue x, undef, n -> x
2547 if (match(Val, m_Undef()))
2548 return Agg;
2549
2550 // insertvalue x, (extractvalue y, n), n
2551 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002552 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2553 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002554 // insertvalue undef, (extractvalue y, n), n -> y
2555 if (match(Agg, m_Undef()))
2556 return EV->getAggregateOperand();
2557
2558 // insertvalue y, (extractvalue y, n), n -> y
2559 if (Agg == EV->getAggregateOperand())
2560 return Agg;
2561 }
2562
2563 return 0;
2564}
2565
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002566Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2567 ArrayRef<unsigned> Idxs,
2568 const TargetData *TD,
2569 const TargetLibraryInfo *TLI,
2570 const DominatorTree *DT) {
2571 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2572 RecursionLimit);
2573}
2574
Duncan Sandsff103412010-11-17 04:30:22 +00002575/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002576static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sandsff103412010-11-17 04:30:22 +00002577 // If all of the PHI's incoming values are the same then replace the PHI node
2578 // with the common value.
2579 Value *CommonValue = 0;
2580 bool HasUndefInput = false;
2581 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2582 Value *Incoming = PN->getIncomingValue(i);
2583 // If the incoming value is the phi node itself, it can safely be skipped.
2584 if (Incoming == PN) continue;
2585 if (isa<UndefValue>(Incoming)) {
2586 // Remember that we saw an undef value, but otherwise ignore them.
2587 HasUndefInput = true;
2588 continue;
2589 }
2590 if (CommonValue && Incoming != CommonValue)
2591 return 0; // Not the same, bail out.
2592 CommonValue = Incoming;
2593 }
2594
2595 // If CommonValue is null then all of the incoming values were either undef or
2596 // equal to the phi node itself.
2597 if (!CommonValue)
2598 return UndefValue::get(PN->getType());
2599
2600 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2601 // instruction, we cannot return X as the result of the PHI node unless it
2602 // dominates the PHI block.
2603 if (HasUndefInput)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002604 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
Duncan Sandsff103412010-11-17 04:30:22 +00002605
2606 return CommonValue;
2607}
2608
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002609static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2610 if (Constant *C = dyn_cast<Constant>(Op))
2611 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2612
2613 return 0;
2614}
2615
2616Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const TargetData *TD,
2617 const TargetLibraryInfo *TLI,
2618 const DominatorTree *DT) {
2619 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2620}
2621
Chris Lattnerd06094f2009-11-10 00:55:12 +00002622//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002623
Chris Lattnerd06094f2009-11-10 00:55:12 +00002624/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2625/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002626static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002627 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002628 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002629 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002630 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002631 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002632 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002633 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002634 Q, MaxRecurse);
2635 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2636 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2637 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2638 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2639 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2640 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2641 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002642 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002643 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002644 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002645 case Instruction::LShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002646 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002647 case Instruction::AShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002648 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2649 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2650 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2651 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002652 default:
2653 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2654 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2655 Constant *COps[] = {CLHS, CRHS};
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002656 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2657 Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002658 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002659
Duncan Sands566edb02010-12-21 08:49:00 +00002660 // If the operation is associative, try some generic simplifications.
2661 if (Instruction::isAssociative(Opcode))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002662 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00002663 return V;
2664
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002665 // If the operation is with the result of a select instruction check whether
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002666 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002667 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002668 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002669 return V;
2670
2671 // If the operation is with the result of a phi instruction, check whether
2672 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002673 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002674 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002675 return V;
2676
Chris Lattnerd06094f2009-11-10 00:55:12 +00002677 return 0;
2678 }
2679}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002680
Duncan Sands12a86f52010-11-14 11:23:23 +00002681Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002682 const TargetData *TD, const TargetLibraryInfo *TLI,
2683 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002684 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002685}
2686
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002687/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2688/// fold the result.
2689static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002690 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002691 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002692 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2693 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002694}
2695
2696Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002697 const TargetData *TD, const TargetLibraryInfo *TLI,
2698 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002699 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2700 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002701}
Chris Lattnere3453782009-11-10 01:08:51 +00002702
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002703static Value *SimplifyCallInst(CallInst *CI, const Query &) {
Dan Gohman71d05032011-11-04 18:32:42 +00002704 // call undef -> undef
2705 if (isa<UndefValue>(CI->getCalledValue()))
2706 return UndefValue::get(CI->getType());
2707
2708 return 0;
2709}
2710
Chris Lattnere3453782009-11-10 01:08:51 +00002711/// SimplifyInstruction - See if we can compute a simplified version of this
2712/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002713Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002714 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002715 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002716 Value *Result;
2717
Chris Lattnere3453782009-11-10 01:08:51 +00002718 switch (I->getOpcode()) {
2719 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002720 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002721 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002722 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002723 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2724 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2725 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002726 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002727 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002728 case Instruction::Sub:
2729 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2730 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2731 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002732 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002733 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002734 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002735 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002736 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002737 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002738 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002739 break;
2740 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002741 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002742 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002743 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002744 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002745 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002746 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002747 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002748 break;
2749 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002750 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002751 break;
2752 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002753 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002754 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002755 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002756 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2757 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2758 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002759 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002760 break;
2761 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002762 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2763 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002764 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002765 break;
2766 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002767 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2768 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002769 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002770 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002771 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002772 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002773 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002774 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002775 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002776 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002777 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002778 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002779 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002780 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002781 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002782 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002783 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002784 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002785 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002786 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002787 break;
Chris Lattner04754262010-04-20 05:32:14 +00002788 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002789 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002790 I->getOperand(2), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002791 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002792 case Instruction::GetElementPtr: {
2793 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002794 Result = SimplifyGEPInst(Ops, TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002795 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002796 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002797 case Instruction::InsertValue: {
2798 InsertValueInst *IV = cast<InsertValueInst>(I);
2799 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2800 IV->getInsertedValueOperand(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002801 IV->getIndices(), TD, TLI, DT);
Duncan Sandsdabc2802011-09-05 06:52:48 +00002802 break;
2803 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002804 case Instruction::PHI:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002805 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
Duncan Sandsd261dc62010-11-17 08:35:29 +00002806 break;
Dan Gohman71d05032011-11-04 18:32:42 +00002807 case Instruction::Call:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002808 Result = SimplifyCallInst(cast<CallInst>(I), Query (TD, TLI, DT));
Dan Gohman71d05032011-11-04 18:32:42 +00002809 break;
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002810 case Instruction::Trunc:
2811 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
2812 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002813 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002814
2815 /// If called on unreachable code, the above logic may report that the
2816 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002817 /// detecting that case here, returning a safe value instead.
2818 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002819}
2820
Chandler Carruth6b980542012-03-24 21:11:24 +00002821/// \brief Implementation of recursive simplification through an instructions
2822/// uses.
Chris Lattner40d8c282009-11-10 22:26:15 +00002823///
Chandler Carruth6b980542012-03-24 21:11:24 +00002824/// This is the common implementation of the recursive simplification routines.
2825/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
2826/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
2827/// instructions to process and attempt to simplify it using
2828/// InstructionSimplify.
2829///
2830/// This routine returns 'true' only when *it* simplifies something. The passed
2831/// in simplified value does not count toward this.
2832static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
2833 const TargetData *TD,
2834 const TargetLibraryInfo *TLI,
2835 const DominatorTree *DT) {
2836 bool Simplified = false;
2837 SmallVector<Instruction *, 8> Worklist;
Duncan Sands12a86f52010-11-14 11:23:23 +00002838
Chandler Carruth6b980542012-03-24 21:11:24 +00002839 // If we have an explicit value to collapse to, do that round of the
2840 // simplification loop by hand initially.
2841 if (SimpleV) {
2842 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2843 ++UI)
2844 Worklist.push_back(cast<Instruction>(*UI));
Duncan Sands12a86f52010-11-14 11:23:23 +00002845
Chandler Carruth6b980542012-03-24 21:11:24 +00002846 // Replace the instruction with its simplified value.
2847 I->replaceAllUsesWith(SimpleV);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002848
Chandler Carruth6b980542012-03-24 21:11:24 +00002849 // Gracefully handle edge cases where the instruction is not wired into any
2850 // parent block.
2851 if (I->getParent())
2852 I->eraseFromParent();
2853 } else {
2854 Worklist.push_back(I);
Chris Lattner40d8c282009-11-10 22:26:15 +00002855 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002856
Chandler Carruth6b980542012-03-24 21:11:24 +00002857 while (!Worklist.empty()) {
2858 I = Worklist.pop_back_val();
Duncan Sands12a86f52010-11-14 11:23:23 +00002859
Chandler Carruth6b980542012-03-24 21:11:24 +00002860 // See if this instruction simplifies.
2861 SimpleV = SimplifyInstruction(I, TD, TLI, DT);
2862 if (!SimpleV)
2863 continue;
2864
2865 Simplified = true;
2866
2867 // Stash away all the uses of the old instruction so we can check them for
2868 // recursive simplifications after a RAUW. This is cheaper than checking all
2869 // uses of To on the recursive step in most cases.
2870 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2871 ++UI)
2872 Worklist.push_back(cast<Instruction>(*UI));
2873
2874 // Replace the instruction with its simplified value.
2875 I->replaceAllUsesWith(SimpleV);
2876
2877 // Gracefully handle edge cases where the instruction is not wired into any
2878 // parent block.
2879 if (I->getParent())
2880 I->eraseFromParent();
2881 }
2882 return Simplified;
2883}
2884
2885bool llvm::recursivelySimplifyInstruction(Instruction *I,
2886 const TargetData *TD,
2887 const TargetLibraryInfo *TLI,
2888 const DominatorTree *DT) {
2889 return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
2890}
2891
2892bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
2893 const TargetData *TD,
2894 const TargetLibraryInfo *TLI,
2895 const DominatorTree *DT) {
2896 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
2897 assert(SimpleV && "Must provide a simplified value.");
2898 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);
Chris Lattner40d8c282009-11-10 22:26:15 +00002899}