blob: 6ac1ae8d5ed1783a66b035fcb5061f47f1c9b709 [file] [log] [blame]
Chris Lattner084a1b52009-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 Sandsa0219882010-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 Sandsed6d6c32010-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 Lattner084a1b52009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
20#include "llvm/Analysis/InstructionSimplify.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SetVector.h"
22#include "llvm/ADT/Statistic.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000023#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000025#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000026#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000028#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalAlias.h"
31#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000032#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000033#include "llvm/IR/ValueHandle.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000034using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000035using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000036
Chandler Carruthf1221bd2014-04-22 02:48:03 +000037#define DEBUG_TYPE "instsimplify"
38
Chris Lattner9e4aa022011-02-09 17:15:04 +000039enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000040
Duncan Sands3547d2e2010-12-22 09:40:51 +000041STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000042STATISTIC(NumReassoc, "Number of reassociations");
43
Duncan Sandsb8cee002012-03-13 11:42:19 +000044struct Query {
Rafael Espindola37dc9e12014-02-21 00:06:31 +000045 const DataLayout *DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000046 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
48
Rafael Espindola37dc9e12014-02-21 00:06:31 +000049 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
50 const DominatorTree *dt) : DL(DL), TLI(tli), DT(dt) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000051};
52
53static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000055 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000056static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000057 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000058static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sands395ac42d2012-03-13 14:07:05 +000060static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000061
Duncan Sandsc1c92712011-07-26 15:03:53 +000062/// getFalse - For a boolean type, or a vector of boolean type, return false, or
63/// a vector with every element false, as appropriate for the type.
64static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000065 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000066 "Expected i1 type or a vector of i1!");
67 return Constant::getNullValue(Ty);
68}
69
70/// getTrue - For a boolean type, or a vector of boolean type, return true, or
71/// a vector with every element true, as appropriate for the type.
72static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000073 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000074 "Expected i1 type or a vector of i1!");
75 return Constant::getAllOnesValue(Ty);
76}
77
Duncan Sands3d5692a2011-10-30 19:56:36 +000078/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
80 Value *RHS) {
81 CmpInst *Cmp = dyn_cast<CmpInst>(V);
82 if (!Cmp)
83 return false;
84 CmpInst::Predicate CPred = Cmp->getPredicate();
85 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
87 return true;
88 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89 CRHS == LHS;
90}
91
Duncan Sands5ffc2982010-11-16 12:16:38 +000092/// ValueDominatesPHI - Does the given value dominate the specified phi node?
93static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94 Instruction *I = dyn_cast<Instruction>(V);
95 if (!I)
96 // Arguments and constants dominate all instructions.
97 return true;
98
Chandler Carruth3ffccb32012-03-21 10:58:47 +000099 // If we are processing instructions (and/or basic blocks) that have not been
100 // fully added to a function, the parent nodes may still be null. Simply
101 // return the conservative answer in these cases.
102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
103 return false;
104
Duncan Sands5ffc2982010-11-16 12:16:38 +0000105 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000106 if (DT) {
107 if (!DT->isReachableFromEntry(P->getParent()))
108 return true;
109 if (!DT->isReachableFromEntry(I->getParent()))
110 return false;
111 return DT->dominates(I, P);
112 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000113
114 // Otherwise, if the instruction is in the entry block, and is not an invoke,
115 // then it obviously dominates all phi nodes.
116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
117 !isa<InvokeInst>(I))
118 return true;
119
120 return false;
121}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000122
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000123/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
125/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127/// Returns the simplified value, or null if no simplification was performed.
128static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000129 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000130 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000132 // Recursion is always used, so bail out at once if we already hit the limit.
133 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000134 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000135
136 // Check whether the expression has the form "(A op' B) op C".
137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138 if (Op0->getOpcode() == OpcodeToExpand) {
139 // It does! Try turning it into "(A op C) op' (B op C)".
140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000144 // They do! Return "L op' R" if it simplifies or is already available.
145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000148 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000149 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000150 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000151 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000153 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000154 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000155 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000156 }
157 }
158
159 // Check whether the expression has the form "A op (B op' C)".
160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161 if (Op1->getOpcode() == OpcodeToExpand) {
162 // It does! Try turning it into "(A op B) op' (A op C)".
163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000167 // They do! Return "L op' R" if it simplifies or is already available.
168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000171 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000172 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000173 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000174 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000176 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000177 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000178 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000179 }
180 }
181
Craig Topper9f008862014-04-15 04:59:12 +0000182 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000183}
184
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000185/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
186/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000187static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000188 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000189 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000190 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
191
192 // Recursion is always used, so bail out at once if we already hit the limit.
193 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000194 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000195
196 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
197 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
198
199 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
200 if (Op0 && Op0->getOpcode() == Opcode) {
201 Value *A = Op0->getOperand(0);
202 Value *B = Op0->getOperand(1);
203 Value *C = RHS;
204
205 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000206 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000207 // It does! Return "A op V" if it simplifies or is already available.
208 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000209 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000210 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000211 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000212 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000213 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000214 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000215 }
216 }
217
218 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
219 if (Op1 && Op1->getOpcode() == Opcode) {
220 Value *A = LHS;
221 Value *B = Op1->getOperand(0);
222 Value *C = Op1->getOperand(1);
223
224 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000225 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 // It does! Return "V op C" if it simplifies or is already available.
227 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000228 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000229 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000230 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000231 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000232 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000233 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000234 }
235 }
236
237 // The remaining transforms require commutativity as well as associativity.
238 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000239 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000240
241 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
242 if (Op0 && Op0->getOpcode() == Opcode) {
243 Value *A = Op0->getOperand(0);
244 Value *B = Op0->getOperand(1);
245 Value *C = RHS;
246
247 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000248 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000249 // It does! Return "V op B" if it simplifies or is already available.
250 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000251 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000252 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000253 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000254 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000255 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000256 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000257 }
258 }
259
260 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
261 if (Op1 && Op1->getOpcode() == Opcode) {
262 Value *A = LHS;
263 Value *B = Op1->getOperand(0);
264 Value *C = Op1->getOperand(1);
265
266 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000267 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 // It does! Return "B op V" if it simplifies or is already available.
269 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000270 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000271 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000272 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000273 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000274 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000275 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000276 }
277 }
278
Craig Topper9f008862014-04-15 04:59:12 +0000279 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000280}
281
Duncan Sandsb0579e92010-11-10 13:00:08 +0000282/// ThreadBinOpOverSelect - In the case of a binary operation with a select
283/// instruction as an operand, try to simplify the binop by seeing whether
284/// evaluating it on both branches of the select results in the same value.
285/// Returns the common value if so, otherwise returns null.
286static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000287 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000288 // Recursion is always used, so bail out at once if we already hit the limit.
289 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000290 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000291
Duncan Sandsb0579e92010-11-10 13:00:08 +0000292 SelectInst *SI;
293 if (isa<SelectInst>(LHS)) {
294 SI = cast<SelectInst>(LHS);
295 } else {
296 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
297 SI = cast<SelectInst>(RHS);
298 }
299
300 // Evaluate the BinOp on the true and false branches of the select.
301 Value *TV;
302 Value *FV;
303 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000304 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
305 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000306 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000307 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
308 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000309 }
310
Duncan Sandse3c53952011-01-01 16:12:09 +0000311 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000312 // If they both failed to simplify then return null.
313 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000314 return TV;
315
316 // If one branch simplified to undef, return the other one.
317 if (TV && isa<UndefValue>(TV))
318 return FV;
319 if (FV && isa<UndefValue>(FV))
320 return TV;
321
322 // If applying the operation did not change the true and false select values,
323 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000324 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000325 return SI;
326
327 // If one branch simplified and the other did not, and the simplified
328 // value is equal to the unsimplified one, return the simplified value.
329 // For example, select (cond, X, X & Z) & Z -> X & Z.
330 if ((FV && !TV) || (TV && !FV)) {
331 // Check that the simplified value has the form "X op Y" where "op" is the
332 // same as the original operation.
333 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
334 if (Simplified && Simplified->getOpcode() == Opcode) {
335 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
336 // We already know that "op" is the same as for the simplified value. See
337 // if the operands match too. If so, return the simplified value.
338 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
339 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
340 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000341 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
342 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000343 return Simplified;
344 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000345 Simplified->getOperand(1) == UnsimplifiedLHS &&
346 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000347 return Simplified;
348 }
349 }
350
Craig Topper9f008862014-04-15 04:59:12 +0000351 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000352}
353
354/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
355/// try to simplify the comparison by seeing whether both branches of the select
356/// result in the same value. Returns the common value if so, otherwise returns
357/// null.
358static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000359 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000360 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000361 // Recursion is always used, so bail out at once if we already hit the limit.
362 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000363 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000364
Duncan Sandsb0579e92010-11-10 13:00:08 +0000365 // Make sure the select is on the LHS.
366 if (!isa<SelectInst>(LHS)) {
367 std::swap(LHS, RHS);
368 Pred = CmpInst::getSwappedPredicate(Pred);
369 }
370 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
371 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000372 Value *Cond = SI->getCondition();
373 Value *TV = SI->getTrueValue();
374 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000375
Duncan Sands06504022011-02-03 09:37:39 +0000376 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000377 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000378 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000379 if (TCmp == Cond) {
380 // It not only simplified, it simplified to the select condition. Replace
381 // it with 'true'.
382 TCmp = getTrue(Cond->getType());
383 } else if (!TCmp) {
384 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
385 // condition then we can replace it with 'true'. Otherwise give up.
386 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000387 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000388 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000389 }
390
Duncan Sands3d5692a2011-10-30 19:56:36 +0000391 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000392 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000393 if (FCmp == Cond) {
394 // It not only simplified, it simplified to the select condition. Replace
395 // it with 'false'.
396 FCmp = getFalse(Cond->getType());
397 } else if (!FCmp) {
398 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
399 // condition then we can replace it with 'false'. Otherwise give up.
400 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000401 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000402 FCmp = getFalse(Cond->getType());
403 }
404
405 // If both sides simplified to the same value, then use it as the result of
406 // the original comparison.
407 if (TCmp == FCmp)
408 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000409
410 // The remaining cases only make sense if the select condition has the same
411 // type as the result of the comparison, so bail out if this is not so.
412 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000413 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000414 // If the false value simplified to false, then the result of the compare
415 // is equal to "Cond && TCmp". This also catches the case when the false
416 // value simplified to false and the true value to true, returning "Cond".
417 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000418 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000419 return V;
420 // If the true value simplified to true, then the result of the compare
421 // is equal to "Cond || FCmp".
422 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000423 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000424 return V;
425 // Finally, if the false value simplified to true and the true value to
426 // false, then the result of the compare is equal to "!Cond".
427 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
428 if (Value *V =
429 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000430 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000431 return V;
432
Craig Topper9f008862014-04-15 04:59:12 +0000433 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000434}
435
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000436/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
437/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
438/// it on the incoming phi values yields the same result for every value. If so
439/// returns the common value, otherwise returns null.
440static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000441 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000442 // Recursion is always used, so bail out at once if we already hit the limit.
443 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000444 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000445
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000446 PHINode *PI;
447 if (isa<PHINode>(LHS)) {
448 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000449 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000450 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000451 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000452 } else {
453 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
454 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000455 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000456 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000457 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000458 }
459
460 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000461 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000462 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000463 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000464 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000465 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000466 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000467 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
468 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000469 // If the operation failed to simplify, or simplified to a different value
470 // to previously, then give up.
471 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000472 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000473 CommonValue = V;
474 }
475
476 return CommonValue;
477}
478
479/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
480/// try to simplify the comparison by seeing whether comparing with all of the
481/// incoming phi values yields the same result every time. If so returns the
482/// common result, otherwise returns null.
483static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000484 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000485 // Recursion is always used, so bail out at once if we already hit the limit.
486 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000487 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000488
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000489 // Make sure the phi is on the LHS.
490 if (!isa<PHINode>(LHS)) {
491 std::swap(LHS, RHS);
492 Pred = CmpInst::getSwappedPredicate(Pred);
493 }
494 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
495 PHINode *PI = cast<PHINode>(LHS);
496
Duncan Sands5ffc2982010-11-16 12:16:38 +0000497 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000498 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000499 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000500
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000501 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000502 Value *CommonValue = nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000503 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000504 Value *Incoming = PI->getIncomingValue(i);
Duncan Sands7412f6e2010-11-17 04:30:22 +0000505 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000506 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000507 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000508 // If the operation failed to simplify, or simplified to a different value
509 // to previously, then give up.
510 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000511 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000512 CommonValue = V;
513 }
514
515 return CommonValue;
516}
517
Chris Lattner3d9823b2009-11-27 17:42:22 +0000518/// SimplifyAddInst - Given operands for an Add, see if we can
519/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000520static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000521 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000522 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
523 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
524 Constant *Ops[] = { CLHS, CRHS };
Duncan Sandsb8cee002012-03-13 11:42:19 +0000525 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000526 Q.DL, Q.TLI);
Chris Lattner3d9823b2009-11-27 17:42:22 +0000527 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000528
Chris Lattner3d9823b2009-11-27 17:42:22 +0000529 // Canonicalize the constant to the RHS.
530 std::swap(Op0, Op1);
531 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000532
Duncan Sands0a2c41682010-12-15 14:07:39 +0000533 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000534 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000535 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000536
Duncan Sands0a2c41682010-12-15 14:07:39 +0000537 // X + 0 -> X
538 if (match(Op1, m_Zero()))
539 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000540
Duncan Sands0a2c41682010-12-15 14:07:39 +0000541 // X + (Y - X) -> Y
542 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000543 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000544 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000545 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
546 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000547 return Y;
548
549 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000550 if (match(Op0, m_Not(m_Specific(Op1))) ||
551 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000552 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000553
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000554 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000555 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000556 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000557 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000558
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000559 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000560 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000561 MaxRecurse))
562 return V;
563
Duncan Sandsb238de02010-11-19 09:20:39 +0000564 // Threading Add over selects and phi nodes is pointless, so don't bother.
565 // Threading over the select in "A + select(cond, B, C)" means evaluating
566 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
567 // only if B and C are equal. If B and C are equal then (since we assume
568 // that operands have already been simplified) "select(cond, B, C)" should
569 // have been simplified to the common value of B and C already. Analysing
570 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
571 // for threading over phi nodes.
572
Craig Topper9f008862014-04-15 04:59:12 +0000573 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000574}
575
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000576Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000577 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000578 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000579 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000580 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000581}
582
Chandler Carrutha0796552012-03-12 11:19:31 +0000583/// \brief Compute the base pointer and cumulative constant offsets for V.
584///
585/// This strips all constant offsets off of V, leaving it the base pointer, and
586/// accumulates the total constant offset applied in the returned constant. It
587/// returns 0 if V is not a pointer, and returns the constant '0' if there are
588/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000589///
590/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
591/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
592/// folding.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000593static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000594 Value *&V,
595 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000596 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000597
Dan Gohman18c77a12013-01-31 02:50:36 +0000598 // Without DataLayout, just be conservative for now. Theoretically, more could
599 // be done in this case.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000600 if (!DL)
Dan Gohman18c77a12013-01-31 02:50:36 +0000601 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
602
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000603 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000604 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000605
606 // Even though we don't look through PHI nodes, we could be called on an
607 // instruction in an unreachable block, which may be on a cycle.
608 SmallPtrSet<Value *, 4> Visited;
609 Visited.insert(V);
610 do {
611 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000612 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000613 !GEP->accumulateConstantOffset(*DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000614 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000615 V = GEP->getPointerOperand();
616 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000617 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000618 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
619 if (GA->mayBeOverridden())
620 break;
621 V = GA->getAliasee();
622 } else {
623 break;
624 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000625 assert(V->getType()->getScalarType()->isPointerTy() &&
626 "Unexpected operand type!");
Chandler Carrutha0796552012-03-12 11:19:31 +0000627 } while (Visited.insert(V));
628
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000629 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
630 if (V->getType()->isVectorTy())
631 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
632 OffsetIntPtr);
633 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000634}
635
636/// \brief Compute the constant difference between two pointer values.
637/// If the difference is not a constant, returns zero.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000638static Constant *computePointerDifference(const DataLayout *DL,
Chandler Carrutha0796552012-03-12 11:19:31 +0000639 Value *LHS, Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000640 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
641 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000642
643 // If LHS and RHS are not related via constant offsets to the same base
644 // value, there is nothing we can do here.
645 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000646 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000647
648 // Otherwise, the difference of LHS - RHS can be computed as:
649 // LHS - RHS
650 // = (LHSOffset + Base) - (RHSOffset + Base)
651 // = LHSOffset - RHSOffset
652 return ConstantExpr::getSub(LHSOffset, RHSOffset);
653}
654
Duncan Sands0a2c41682010-12-15 14:07:39 +0000655/// SimplifySubInst - Given operands for a Sub, see if we can
656/// fold the result. If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000657static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000658 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000659 if (Constant *CLHS = dyn_cast<Constant>(Op0))
660 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
661 Constant *Ops[] = { CLHS, CRHS };
662 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000663 Ops, Q.DL, Q.TLI);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000664 }
665
666 // X - undef -> undef
667 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000668 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000669 return UndefValue::get(Op0->getType());
670
671 // X - 0 -> X
672 if (match(Op1, m_Zero()))
673 return Op0;
674
675 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000676 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000677 return Constant::getNullValue(Op0->getType());
678
Duncan Sands99589d02011-01-18 11:50:19 +0000679 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
680 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000681 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000682 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
683 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000684 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000685 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000686 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000687 // It does, we successfully reassociated!
688 ++NumReassoc;
689 return W;
690 }
691 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000692 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000693 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000694 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000695 // It does, we successfully reassociated!
696 ++NumReassoc;
697 return W;
698 }
699 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000700
Duncan Sands99589d02011-01-18 11:50:19 +0000701 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
702 // For example, X - (X + 1) -> -1
703 X = Op0;
704 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
705 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000706 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000707 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000708 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000709 // It does, we successfully reassociated!
710 ++NumReassoc;
711 return W;
712 }
713 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000714 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000715 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000716 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000717 // It does, we successfully reassociated!
718 ++NumReassoc;
719 return W;
720 }
721 }
722
723 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
724 // For example, X - (X - Y) -> Y.
725 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000726 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
727 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000728 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000729 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000730 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000731 // It does, we successfully reassociated!
732 ++NumReassoc;
733 return W;
734 }
735
Duncan Sands395ac42d2012-03-13 14:07:05 +0000736 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
737 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
738 match(Op1, m_Trunc(m_Value(Y))))
739 if (X->getType() == Y->getType())
740 // See if "V === X - Y" simplifies.
741 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
742 // It does! Now see if "trunc V" simplifies.
743 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
744 // It does, return the simplified "trunc V".
745 return W;
746
747 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000748 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000749 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000750 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000751 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
752
Duncan Sands99589d02011-01-18 11:50:19 +0000753 // i1 sub -> xor.
754 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000755 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000756 return V;
757
Duncan Sands0a2c41682010-12-15 14:07:39 +0000758 // Threading Sub over selects and phi nodes is pointless, so don't bother.
759 // Threading over the select in "A - select(cond, B, C)" means evaluating
760 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
761 // only if B and C are equal. If B and C are equal then (since we assume
762 // that operands have already been simplified) "select(cond, B, C)" should
763 // have been simplified to the common value of B and C already. Analysing
764 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
765 // for threading over phi nodes.
766
Craig Topper9f008862014-04-15 04:59:12 +0000767 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000768}
769
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000770Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000771 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000772 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000773 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000774 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000775}
776
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000777/// Given operands for an FAdd, see if we can fold the result. If not, this
778/// returns null.
779static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
780 const Query &Q, unsigned MaxRecurse) {
781 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
782 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
783 Constant *Ops[] = { CLHS, CRHS };
784 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000785 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000786 }
787
788 // Canonicalize the constant to the RHS.
789 std::swap(Op0, Op1);
790 }
791
792 // fadd X, -0 ==> X
793 if (match(Op1, m_NegZero()))
794 return Op0;
795
796 // fadd X, 0 ==> X, when we know X is not -0
797 if (match(Op1, m_Zero()) &&
798 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
799 return Op0;
800
801 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
802 // where nnan and ninf have to occur at least once somewhere in this
803 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000804 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000805 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
806 SubOp = Op1;
807 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
808 SubOp = Op0;
809 if (SubOp) {
810 Instruction *FSub = cast<Instruction>(SubOp);
811 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
812 (FMF.noInfs() || FSub->hasNoInfs()))
813 return Constant::getNullValue(Op0->getType());
814 }
815
Craig Topper9f008862014-04-15 04:59:12 +0000816 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000817}
818
819/// Given operands for an FSub, see if we can fold the result. If not, this
820/// returns null.
821static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
822 const Query &Q, unsigned MaxRecurse) {
823 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
824 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
825 Constant *Ops[] = { CLHS, CRHS };
826 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000827 Ops, Q.DL, Q.TLI);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000828 }
829 }
830
831 // fsub X, 0 ==> X
832 if (match(Op1, m_Zero()))
833 return Op0;
834
835 // fsub X, -0 ==> X, when we know X is not -0
836 if (match(Op1, m_NegZero()) &&
837 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
838 return Op0;
839
840 // fsub 0, (fsub -0.0, X) ==> X
841 Value *X;
842 if (match(Op0, m_AnyZero())) {
843 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
844 return X;
845 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
846 return X;
847 }
848
849 // fsub nnan ninf x, x ==> 0.0
850 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
851 return Constant::getNullValue(Op0->getType());
852
Craig Topper9f008862014-04-15 04:59:12 +0000853 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000854}
855
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000856/// Given the operands for an FMul, see if we can fold the result
857static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
858 FastMathFlags FMF,
859 const Query &Q,
860 unsigned MaxRecurse) {
861 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
862 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
863 Constant *Ops[] = { CLHS, CRHS };
864 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000865 Ops, Q.DL, Q.TLI);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000866 }
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000867
868 // Canonicalize the constant to the RHS.
869 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000870 }
871
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000872 // fmul X, 1.0 ==> X
873 if (match(Op1, m_FPOne()))
874 return Op0;
875
876 // fmul nnan nsz X, 0 ==> 0
877 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
878 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000879
Craig Topper9f008862014-04-15 04:59:12 +0000880 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000881}
882
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000883/// SimplifyMulInst - Given operands for a Mul, see if we can
884/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000885static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
886 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000887 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
888 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
889 Constant *Ops[] = { CLHS, CRHS };
890 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000891 Ops, Q.DL, Q.TLI);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000892 }
893
894 // Canonicalize the constant to the RHS.
895 std::swap(Op0, Op1);
896 }
897
898 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000899 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000900 return Constant::getNullValue(Op0->getType());
901
902 // X * 0 -> 0
903 if (match(Op1, m_Zero()))
904 return Op1;
905
906 // X * 1 -> X
907 if (match(Op1, m_One()))
908 return Op0;
909
Duncan Sandsb67edc62011-01-30 18:03:50 +0000910 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000911 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000912 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
913 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
914 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000915
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000916 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000917 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000918 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000919 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000920
921 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000922 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000923 MaxRecurse))
924 return V;
925
926 // Mul distributes over Add. Try some generic simplifications based on this.
927 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000928 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000929 return V;
930
931 // If the operation is with the result of a select instruction, check whether
932 // operating on either branch of the select always yields the same value.
933 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000934 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000935 MaxRecurse))
936 return V;
937
938 // If the operation is with the result of a phi instruction, check whether
939 // operating on all incoming values of the phi always yields the same value.
940 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000941 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000942 MaxRecurse))
943 return V;
944
Craig Topper9f008862014-04-15 04:59:12 +0000945 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000946}
947
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000948Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000949 const DataLayout *DL, const TargetLibraryInfo *TLI,
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000950 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000951 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000952}
953
954Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000955 const DataLayout *DL, const TargetLibraryInfo *TLI,
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000956 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000957 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000958}
959
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000960Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
961 FastMathFlags FMF,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000962 const DataLayout *DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000963 const TargetLibraryInfo *TLI,
964 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000965 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT), RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000966}
967
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000968Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000969 const TargetLibraryInfo *TLI,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000970 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000971 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000972}
973
Duncan Sands771e82a2011-01-28 16:51:11 +0000974/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
975/// fold the result. If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +0000976static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000977 const Query &Q, unsigned MaxRecurse) {
Duncan Sands771e82a2011-01-28 16:51:11 +0000978 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
979 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
980 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000981 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands771e82a2011-01-28 16:51:11 +0000982 }
983 }
984
Duncan Sands65995fa2011-01-28 18:50:50 +0000985 bool isSigned = Opcode == Instruction::SDiv;
986
Duncan Sands771e82a2011-01-28 16:51:11 +0000987 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000988 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000989 return Op1;
990
991 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000992 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000993 return Constant::getNullValue(Op0->getType());
994
995 // 0 / X -> 0, we don't need to preserve faults!
996 if (match(Op0, m_Zero()))
997 return Op0;
998
999 // X / 1 -> X
1000 if (match(Op1, m_One()))
1001 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001002
1003 if (Op0->getType()->isIntegerTy(1))
1004 // It can't be division by zero, hence it must be division by one.
1005 return Op0;
1006
1007 // X / X -> 1
1008 if (Op0 == Op1)
1009 return ConstantInt::get(Op0->getType(), 1);
1010
1011 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001012 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001013 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1014 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001015 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001016 // If the Mul knows it does not overflow, then we are good to go.
1017 if ((isSigned && Mul->hasNoSignedWrap()) ||
1018 (!isSigned && Mul->hasNoUnsignedWrap()))
1019 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001020 // If X has the form X = A / Y then X * Y cannot overflow.
1021 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1022 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1023 return X;
1024 }
1025
Duncan Sands65995fa2011-01-28 18:50:50 +00001026 // (X rem Y) / Y -> 0
1027 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1028 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1029 return Constant::getNullValue(Op0->getType());
1030
1031 // If the operation is with the result of a select instruction, check whether
1032 // operating on either branch of the select always yields the same value.
1033 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001034 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001035 return V;
1036
1037 // If the operation is with the result of a phi instruction, check whether
1038 // operating on all incoming values of the phi always yields the same value.
1039 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001040 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001041 return V;
1042
Craig Topper9f008862014-04-15 04:59:12 +00001043 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001044}
1045
1046/// SimplifySDivInst - Given operands for an SDiv, see if we can
1047/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001048static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1049 unsigned MaxRecurse) {
1050 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001051 return V;
1052
Craig Topper9f008862014-04-15 04:59:12 +00001053 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001054}
1055
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001056Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001057 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001058 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001059 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001060}
1061
1062/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1063/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001064static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1065 unsigned MaxRecurse) {
1066 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001067 return V;
1068
Craig Topper9f008862014-04-15 04:59:12 +00001069 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001070}
1071
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001072Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001073 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001074 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001075 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001076}
1077
Duncan Sandsb8cee002012-03-13 11:42:19 +00001078static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1079 unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001080 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001081 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001082 return Op0;
1083
1084 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001085 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001086 return Op1;
1087
Craig Topper9f008862014-04-15 04:59:12 +00001088 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001089}
1090
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001091Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001092 const TargetLibraryInfo *TLI,
Frits van Bommelc2549662011-01-29 15:26:31 +00001093 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001094 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001095}
1096
Duncan Sandsa3e36992011-05-02 16:27:02 +00001097/// SimplifyRem - Given operands for an SRem or URem, see if we can
1098/// fold the result. If not, this returns null.
1099static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001100 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001101 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1102 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1103 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001104 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001105 }
1106 }
1107
Duncan Sandsa3e36992011-05-02 16:27:02 +00001108 // X % undef -> undef
1109 if (match(Op1, m_Undef()))
1110 return Op1;
1111
1112 // undef % X -> 0
1113 if (match(Op0, m_Undef()))
1114 return Constant::getNullValue(Op0->getType());
1115
1116 // 0 % X -> 0, we don't need to preserve faults!
1117 if (match(Op0, m_Zero()))
1118 return Op0;
1119
1120 // X % 0 -> undef, we don't need to preserve faults!
1121 if (match(Op1, m_Zero()))
1122 return UndefValue::get(Op0->getType());
1123
1124 // X % 1 -> 0
1125 if (match(Op1, m_One()))
1126 return Constant::getNullValue(Op0->getType());
1127
1128 if (Op0->getType()->isIntegerTy(1))
1129 // It can't be remainder by zero, hence it must be remainder by one.
1130 return Constant::getNullValue(Op0->getType());
1131
1132 // X % X -> 0
1133 if (Op0 == Op1)
1134 return Constant::getNullValue(Op0->getType());
1135
1136 // If the operation is with the result of a select instruction, check whether
1137 // operating on either branch of the select always yields the same value.
1138 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001139 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001140 return V;
1141
1142 // If the operation is with the result of a phi instruction, check whether
1143 // operating on all incoming values of the phi always yields the same value.
1144 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001145 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001146 return V;
1147
Craig Topper9f008862014-04-15 04:59:12 +00001148 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001149}
1150
1151/// SimplifySRemInst - Given operands for an SRem, see if we can
1152/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001153static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1154 unsigned MaxRecurse) {
1155 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001156 return V;
1157
Craig Topper9f008862014-04-15 04:59:12 +00001158 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001159}
1160
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001161Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001162 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001163 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001164 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001165}
1166
1167/// SimplifyURemInst - Given operands for a URem, see if we can
1168/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001169static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001170 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001171 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001172 return V;
1173
Craig Topper9f008862014-04-15 04:59:12 +00001174 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001175}
1176
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001177Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001178 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001179 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001180 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001181}
1182
Duncan Sandsb8cee002012-03-13 11:42:19 +00001183static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001184 unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001185 // undef % X -> undef (the undef could be a snan).
1186 if (match(Op0, m_Undef()))
1187 return Op0;
1188
1189 // X % undef -> undef
1190 if (match(Op1, m_Undef()))
1191 return Op1;
1192
Craig Topper9f008862014-04-15 04:59:12 +00001193 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001194}
1195
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001196Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001197 const TargetLibraryInfo *TLI,
Duncan Sandsa3e36992011-05-02 16:27:02 +00001198 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001199 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001200}
1201
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001202/// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1203static bool isUndefShift(Value *Amount) {
1204 Constant *C = dyn_cast<Constant>(Amount);
1205 if (!C)
1206 return false;
1207
1208 // X shift by undef -> undef because it may shift by the bitwidth.
1209 if (isa<UndefValue>(C))
1210 return true;
1211
1212 // Shifting by the bitwidth or more is undefined.
1213 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1214 if (CI->getValue().getLimitedValue() >=
1215 CI->getType()->getScalarSizeInBits())
1216 return true;
1217
1218 // If all lanes of a vector shift are undefined the whole shift is.
1219 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1220 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1221 if (!isUndefShift(C->getAggregateElement(I)))
1222 return false;
1223 return true;
1224 }
1225
1226 return false;
1227}
1228
Duncan Sands571fd9a2011-01-14 14:44:12 +00001229/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sands7f60dc12011-01-14 00:37:45 +00001230/// fold the result. If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001231static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001232 const Query &Q, unsigned MaxRecurse) {
Duncan Sands7f60dc12011-01-14 00:37:45 +00001233 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1234 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1235 Constant *Ops[] = { C0, C1 };
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001236 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001237 }
1238 }
1239
Duncan Sands571fd9a2011-01-14 14:44:12 +00001240 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001241 if (match(Op0, m_Zero()))
1242 return Op0;
1243
Duncan Sands571fd9a2011-01-14 14:44:12 +00001244 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001245 if (match(Op1, m_Zero()))
1246 return Op0;
1247
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001248 // Fold undefined shifts.
1249 if (isUndefShift(Op1))
1250 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001251
Duncan Sands571fd9a2011-01-14 14:44:12 +00001252 // If the operation is with the result of a select instruction, check whether
1253 // operating on either branch of the select always yields the same value.
1254 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001255 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001256 return V;
1257
1258 // If the operation is with the result of a phi instruction, check whether
1259 // operating on all incoming values of the phi always yields the same value.
1260 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001261 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001262 return V;
1263
Craig Topper9f008862014-04-15 04:59:12 +00001264 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001265}
1266
1267/// SimplifyShlInst - Given operands for an Shl, see if we can
1268/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001269static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001270 const Query &Q, unsigned MaxRecurse) {
1271 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001272 return V;
1273
1274 // undef << X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001275 if (match(Op0, m_Undef()))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001276 return Constant::getNullValue(Op0->getType());
1277
Chris Lattner9e4aa022011-02-09 17:15:04 +00001278 // (X >> A) << A -> X
1279 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001280 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001281 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001282 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001283}
1284
Chris Lattner9e4aa022011-02-09 17:15:04 +00001285Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001286 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001287 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001288 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001289 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001290}
1291
1292/// SimplifyLShrInst - Given operands for an LShr, see if we can
1293/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001294static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001295 const Query &Q, unsigned MaxRecurse) {
1296 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001297 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001298
David Majnemera80fed72013-07-09 22:01:22 +00001299 // X >> X -> 0
1300 if (Op0 == Op1)
1301 return Constant::getNullValue(Op0->getType());
1302
Duncan Sands7f60dc12011-01-14 00:37:45 +00001303 // undef >>l X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001304 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001305 return Constant::getNullValue(Op0->getType());
1306
Chris Lattner9e4aa022011-02-09 17:15:04 +00001307 // (X << A) >> A -> X
1308 Value *X;
1309 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1310 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1311 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001312
Craig Topper9f008862014-04-15 04:59:12 +00001313 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001314}
1315
Chris Lattner9e4aa022011-02-09 17:15:04 +00001316Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001317 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001318 const TargetLibraryInfo *TLI,
1319 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001320 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001321 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001322}
1323
1324/// SimplifyAShrInst - Given operands for an AShr, see if we can
1325/// fold the result. If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001326static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001327 const Query &Q, unsigned MaxRecurse) {
1328 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001329 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001330
David Majnemera80fed72013-07-09 22:01:22 +00001331 // X >> X -> 0
1332 if (Op0 == Op1)
1333 return Constant::getNullValue(Op0->getType());
1334
Duncan Sands7f60dc12011-01-14 00:37:45 +00001335 // all ones >>a X -> all ones
1336 if (match(Op0, m_AllOnes()))
1337 return Op0;
1338
1339 // undef >>a X -> all ones
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001340 if (match(Op0, m_Undef()))
Duncan Sands7f60dc12011-01-14 00:37:45 +00001341 return Constant::getAllOnesValue(Op0->getType());
1342
Chris Lattner9e4aa022011-02-09 17:15:04 +00001343 // (X << A) >> A -> X
1344 Value *X;
1345 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1346 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1347 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001348
Suyog Sarda68862412014-07-17 06:28:15 +00001349 // Arithmetic shifting an all-sign-bit value is a no-op.
1350 unsigned NumSignBits = ComputeNumSignBits(Op0);
1351 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1352 return Op0;
1353
Craig Topper9f008862014-04-15 04:59:12 +00001354 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001355}
1356
Chris Lattner9e4aa022011-02-09 17:15:04 +00001357Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001358 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001359 const TargetLibraryInfo *TLI,
1360 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001361 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001362 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001363}
1364
Chris Lattnera71e9d62009-11-10 00:55:12 +00001365/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner084a1b52009-11-09 22:57:59 +00001366/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001367static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001368 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001369 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1370 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1371 Constant *Ops[] = { CLHS, CRHS };
1372 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001373 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001374 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001375
Chris Lattnera71e9d62009-11-10 00:55:12 +00001376 // Canonicalize the constant to the RHS.
1377 std::swap(Op0, Op1);
1378 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001379
Chris Lattnera71e9d62009-11-10 00:55:12 +00001380 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001381 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001382 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001383
Chris Lattnera71e9d62009-11-10 00:55:12 +00001384 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001385 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001386 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001387
Duncan Sandsc89ac072010-11-17 18:52:15 +00001388 // X & 0 = 0
1389 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001390 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001391
Duncan Sandsc89ac072010-11-17 18:52:15 +00001392 // X & -1 = X
1393 if (match(Op1, m_AllOnes()))
1394 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001395
Chris Lattnera71e9d62009-11-10 00:55:12 +00001396 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001397 if (match(Op0, m_Not(m_Specific(Op1))) ||
1398 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001399 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001400
Chris Lattnera71e9d62009-11-10 00:55:12 +00001401 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001402 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001403 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001404 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001405 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001406
Chris Lattnera71e9d62009-11-10 00:55:12 +00001407 // A & (A | ?) = A
1408 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001409 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001410 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001411
Duncan Sandsba286d72011-10-26 20:55:21 +00001412 // A & (-A) = A if A is a power of two or zero.
1413 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1414 match(Op1, m_Neg(m_Specific(Op0)))) {
Rafael Espindola319f74c2012-12-13 03:37:24 +00001415 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true))
Duncan Sandsba286d72011-10-26 20:55:21 +00001416 return Op0;
Rafael Espindola319f74c2012-12-13 03:37:24 +00001417 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true))
Duncan Sandsba286d72011-10-26 20:55:21 +00001418 return Op1;
1419 }
1420
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001421 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001422 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1423 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001424 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001425
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001426 // And distributes over Or. Try some generic simplifications based on this.
1427 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001428 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001429 return V;
1430
1431 // And distributes over Xor. Try some generic simplifications based on this.
1432 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001433 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001434 return V;
1435
Duncan Sandsb0579e92010-11-10 13:00:08 +00001436 // If the operation is with the result of a select instruction, check whether
1437 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001438 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001439 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1440 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001441 return V;
1442
1443 // If the operation is with the result of a phi instruction, check whether
1444 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001445 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001446 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001447 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001448 return V;
1449
Craig Topper9f008862014-04-15 04:59:12 +00001450 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001451}
1452
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001453Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001454 const TargetLibraryInfo *TLI,
Duncan Sands5ffc2982010-11-16 12:16:38 +00001455 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001456 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001457}
1458
Chris Lattnera71e9d62009-11-10 00:55:12 +00001459/// SimplifyOrInst - Given operands for an Or, see if we can
1460/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001461static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1462 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001463 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1464 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1465 Constant *Ops[] = { CLHS, CRHS };
1466 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001467 Ops, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001468 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001469
Chris Lattnera71e9d62009-11-10 00:55:12 +00001470 // Canonicalize the constant to the RHS.
1471 std::swap(Op0, Op1);
1472 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001473
Chris Lattnera71e9d62009-11-10 00:55:12 +00001474 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001475 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001476 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001477
Chris Lattnera71e9d62009-11-10 00:55:12 +00001478 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001479 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001480 return Op0;
1481
Duncan Sandsc89ac072010-11-17 18:52:15 +00001482 // X | 0 = X
1483 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001484 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001485
Duncan Sandsc89ac072010-11-17 18:52:15 +00001486 // X | -1 = -1
1487 if (match(Op1, m_AllOnes()))
1488 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001489
Chris Lattnera71e9d62009-11-10 00:55:12 +00001490 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001491 if (match(Op0, m_Not(m_Specific(Op1))) ||
1492 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001493 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001494
Chris Lattnera71e9d62009-11-10 00:55:12 +00001495 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001496 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001497 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001498 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001499 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001500
Chris Lattnera71e9d62009-11-10 00:55:12 +00001501 // A | (A & ?) = A
1502 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001503 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001504 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001505
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001506 // ~(A & ?) | A = -1
1507 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1508 (A == Op1 || B == Op1))
1509 return Constant::getAllOnesValue(Op1->getType());
1510
1511 // A | ~(A & ?) = -1
1512 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1513 (A == Op0 || B == Op0))
1514 return Constant::getAllOnesValue(Op0->getType());
1515
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001516 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001517 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1518 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001519 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001520
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001521 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001522 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1523 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001524 return V;
1525
Duncan Sandsb0579e92010-11-10 13:00:08 +00001526 // If the operation is with the result of a select instruction, check whether
1527 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001528 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001529 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001530 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001531 return V;
1532
Nick Lewycky8561a492014-06-19 03:51:46 +00001533 // (A & C)|(B & D)
1534 Value *C = nullptr, *D = nullptr;
1535 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1536 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1537 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1538 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1539 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1540 // (A & C1)|(B & C2)
1541 // If we have: ((V + N) & C1) | (V & C2)
1542 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1543 // replace with V+N.
1544 Value *V1, *V2;
1545 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1546 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1547 // Add commutes, try both ways.
1548 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
1549 return A;
1550 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
1551 return A;
1552 }
1553 // Or commutes, try both ways.
1554 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1555 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1556 // Add commutes, try both ways.
1557 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
1558 return B;
1559 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
1560 return B;
1561 }
1562 }
1563 }
1564
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001565 // If the operation is with the result of a phi instruction, check whether
1566 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001567 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001568 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001569 return V;
1570
Craig Topper9f008862014-04-15 04:59:12 +00001571 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001572}
1573
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001574Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001575 const TargetLibraryInfo *TLI,
Duncan Sands5ffc2982010-11-16 12:16:38 +00001576 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001577 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001578}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001579
Duncan Sandsc89ac072010-11-17 18:52:15 +00001580/// SimplifyXorInst - Given operands for a Xor, see if we can
1581/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001582static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1583 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001584 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1585 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1586 Constant *Ops[] = { CLHS, CRHS };
1587 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001588 Ops, Q.DL, Q.TLI);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001589 }
1590
1591 // Canonicalize the constant to the RHS.
1592 std::swap(Op0, Op1);
1593 }
1594
1595 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001596 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001597 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001598
1599 // A ^ 0 = A
1600 if (match(Op1, m_Zero()))
1601 return Op0;
1602
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001603 // A ^ A = 0
1604 if (Op0 == Op1)
1605 return Constant::getNullValue(Op0->getType());
1606
Duncan Sandsc89ac072010-11-17 18:52:15 +00001607 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001608 if (match(Op0, m_Not(m_Specific(Op1))) ||
1609 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001610 return Constant::getAllOnesValue(Op0->getType());
1611
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001612 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001613 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1614 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001615 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001616
Duncan Sandsb238de02010-11-19 09:20:39 +00001617 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1618 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1619 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1620 // only if B and C are equal. If B and C are equal then (since we assume
1621 // that operands have already been simplified) "select(cond, B, C)" should
1622 // have been simplified to the common value of B and C already. Analysing
1623 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1624 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001625
Craig Topper9f008862014-04-15 04:59:12 +00001626 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001627}
1628
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001629Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001630 const TargetLibraryInfo *TLI,
Duncan Sandsc89ac072010-11-17 18:52:15 +00001631 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001632 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001633}
1634
Chris Lattner229907c2011-07-18 04:54:35 +00001635static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001636 return CmpInst::makeCmpResultType(Op->getType());
1637}
1638
Duncan Sandsaf327282011-05-07 16:56:49 +00001639/// ExtractEquivalentCondition - Rummage around inside V looking for something
1640/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1641/// otherwise return null. Helper function for analyzing max/min idioms.
1642static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1643 Value *LHS, Value *RHS) {
1644 SelectInst *SI = dyn_cast<SelectInst>(V);
1645 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001646 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001647 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1648 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001649 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001650 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1651 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1652 return Cmp;
1653 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1654 LHS == CmpRHS && RHS == CmpLHS)
1655 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001656 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001657}
1658
Dan Gohman9631d902013-02-01 00:49:06 +00001659// A significant optimization not implemented here is assuming that alloca
1660// addresses are not equal to incoming argument values. They don't *alias*,
1661// as we say, but that doesn't mean they aren't equal, so we take a
1662// conservative approach.
1663//
1664// This is inspired in part by C++11 5.10p1:
1665// "Two pointers of the same type compare equal if and only if they are both
1666// null, both point to the same function, or both represent the same
1667// address."
1668//
1669// This is pretty permissive.
1670//
1671// It's also partly due to C11 6.5.9p6:
1672// "Two pointers compare equal if and only if both are null pointers, both are
1673// pointers to the same object (including a pointer to an object and a
1674// subobject at its beginning) or function, both are pointers to one past the
1675// last element of the same array object, or one is a pointer to one past the
1676// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001677// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001678// object in the address space.)
1679//
1680// C11's version is more restrictive, however there's no reason why an argument
1681// couldn't be a one-past-the-end value for a stack object in the caller and be
1682// equal to the beginning of a stack object in the callee.
1683//
1684// If the C and C++ standards are ever made sufficiently restrictive in this
1685// area, it may be possible to update LLVM's semantics accordingly and reinstate
1686// this optimization.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001687static Constant *computePointerICmp(const DataLayout *DL,
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001688 const TargetLibraryInfo *TLI,
Chandler Carruth8059c842012-03-25 21:28:14 +00001689 CmpInst::Predicate Pred,
1690 Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001691 // First, skip past any trivial no-ops.
1692 LHS = LHS->stripPointerCasts();
1693 RHS = RHS->stripPointerCasts();
1694
1695 // A non-null pointer is not equal to a null pointer.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00001696 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001697 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1698 return ConstantInt::get(GetCompareTy(LHS),
1699 !CmpInst::isTrueWhenEqual(Pred));
1700
Chandler Carruth8059c842012-03-25 21:28:14 +00001701 // We can only fold certain predicates on pointer comparisons.
1702 switch (Pred) {
1703 default:
Craig Topper9f008862014-04-15 04:59:12 +00001704 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001705
1706 // Equality comaprisons are easy to fold.
1707 case CmpInst::ICMP_EQ:
1708 case CmpInst::ICMP_NE:
1709 break;
1710
1711 // We can only handle unsigned relational comparisons because 'inbounds' on
1712 // a GEP only protects against unsigned wrapping.
1713 case CmpInst::ICMP_UGT:
1714 case CmpInst::ICMP_UGE:
1715 case CmpInst::ICMP_ULT:
1716 case CmpInst::ICMP_ULE:
1717 // However, we have to switch them to their signed variants to handle
1718 // negative indices from the base pointer.
1719 Pred = ICmpInst::getSignedPredicate(Pred);
1720 break;
1721 }
1722
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001723 // Strip off any constant offsets so that we can reason about them.
1724 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1725 // here and compare base addresses like AliasAnalysis does, however there are
1726 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1727 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1728 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001729 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1730 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00001731
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001732 // If LHS and RHS are related via constant offsets to the same base
1733 // value, we can replace it with an icmp which just compares the offsets.
1734 if (LHS == RHS)
1735 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00001736
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001737 // Various optimizations for (in)equality comparisons.
1738 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1739 // Different non-empty allocations that exist at the same time have
1740 // different addresses (if the program can tell). Global variables always
1741 // exist, so they always exist during the lifetime of each other and all
1742 // allocas. Two different allocas usually have different addresses...
1743 //
1744 // However, if there's an @llvm.stackrestore dynamically in between two
1745 // allocas, they may have the same address. It's tempting to reduce the
1746 // scope of the problem by only looking at *static* allocas here. That would
1747 // cover the majority of allocas while significantly reducing the likelihood
1748 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1749 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1750 // an entry block. Also, if we have a block that's not attached to a
1751 // function, we can't tell if it's "static" under the current definition.
1752 // Theoretically, this problem could be fixed by creating a new kind of
1753 // instruction kind specifically for static allocas. Such a new instruction
1754 // could be required to be at the top of the entry block, thus preventing it
1755 // from being subject to a @llvm.stackrestore. Instcombine could even
1756 // convert regular allocas into these special allocas. It'd be nifty.
1757 // However, until then, this problem remains open.
1758 //
1759 // So, we'll assume that two non-empty allocas have different addresses
1760 // for now.
1761 //
1762 // With all that, if the offsets are within the bounds of their allocations
1763 // (and not one-past-the-end! so we can't use inbounds!), and their
1764 // allocations aren't the same, the pointers are not equal.
1765 //
1766 // Note that it's not necessary to check for LHS being a global variable
1767 // address, due to canonicalization and constant folding.
1768 if (isa<AllocaInst>(LHS) &&
1769 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001770 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1771 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001772 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001773 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001774 getObjectSize(LHS, LHSSize, DL, TLI) &&
1775 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00001776 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1777 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001778 if (!LHSOffsetValue.isNegative() &&
1779 !RHSOffsetValue.isNegative() &&
1780 LHSOffsetValue.ult(LHSSize) &&
1781 RHSOffsetValue.ult(RHSSize)) {
1782 return ConstantInt::get(GetCompareTy(LHS),
1783 !CmpInst::isTrueWhenEqual(Pred));
1784 }
1785 }
1786
1787 // Repeat the above check but this time without depending on DataLayout
1788 // or being able to compute a precise size.
1789 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1790 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1791 LHSOffset->isNullValue() &&
1792 RHSOffset->isNullValue())
1793 return ConstantInt::get(GetCompareTy(LHS),
1794 !CmpInst::isTrueWhenEqual(Pred));
1795 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001796
1797 // Even if an non-inbounds GEP occurs along the path we can still optimize
1798 // equality comparisons concerning the result. We avoid walking the whole
1799 // chain again by starting where the last calls to
1800 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001801 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1802 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00001803 if (LHS == RHS)
1804 return ConstantExpr::getICmp(Pred,
1805 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1806 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001807 }
1808
1809 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00001810 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001811}
Chris Lattner01990f02012-02-24 19:01:58 +00001812
Chris Lattnerc1f19072009-11-09 23:28:39 +00001813/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1814/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001815static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001816 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00001817 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00001818 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00001819
Chris Lattnera71e9d62009-11-10 00:55:12 +00001820 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001821 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001822 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00001823
1824 // If we have a constant, make sure it is on the RHS.
1825 std::swap(LHS, RHS);
1826 Pred = CmpInst::getSwappedPredicate(Pred);
1827 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001828
Chris Lattner229907c2011-07-18 04:54:35 +00001829 Type *ITy = GetCompareTy(LHS); // The return type.
1830 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00001831
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001832 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00001833 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1834 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00001835 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001836 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00001837
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001838 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00001839 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001840 switch (Pred) {
1841 default: break;
1842 case ICmpInst::ICMP_EQ:
1843 // X == 1 -> X
1844 if (match(RHS, m_One()))
1845 return LHS;
1846 break;
1847 case ICmpInst::ICMP_NE:
1848 // X != 0 -> X
1849 if (match(RHS, m_Zero()))
1850 return LHS;
1851 break;
1852 case ICmpInst::ICMP_UGT:
1853 // X >u 0 -> X
1854 if (match(RHS, m_Zero()))
1855 return LHS;
1856 break;
1857 case ICmpInst::ICMP_UGE:
1858 // X >=u 1 -> X
1859 if (match(RHS, m_One()))
1860 return LHS;
1861 break;
1862 case ICmpInst::ICMP_SLT:
1863 // X <s 0 -> X
1864 if (match(RHS, m_Zero()))
1865 return LHS;
1866 break;
1867 case ICmpInst::ICMP_SLE:
1868 // X <=s -1 -> X
1869 if (match(RHS, m_One()))
1870 return LHS;
1871 break;
1872 }
1873 }
1874
Duncan Sandsd3951082011-01-25 09:38:29 +00001875 // If we are comparing with zero then try hard since this is a common case.
1876 if (match(RHS, m_Zero())) {
1877 bool LHSKnownNonNegative, LHSKnownNegative;
1878 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00001879 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00001880 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001881 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001882 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00001883 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001884 case ICmpInst::ICMP_EQ:
1885 case ICmpInst::ICMP_ULE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001886 if (isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001887 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001888 break;
1889 case ICmpInst::ICMP_NE:
1890 case ICmpInst::ICMP_UGT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001891 if (isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001892 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001893 break;
1894 case ICmpInst::ICMP_SLT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001895 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001896 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001897 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001898 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001899 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001900 break;
1901 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001902 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001903 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001904 return getTrue(ITy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001905 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001906 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001907 break;
1908 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001909 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001910 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001911 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001912 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001913 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001914 break;
1915 case ICmpInst::ICMP_SGT:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001916 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL);
Duncan Sandsd3951082011-01-25 09:38:29 +00001917 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00001918 return getFalse(ITy);
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001919 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL))
Duncan Sandsc1c92712011-07-26 15:03:53 +00001920 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00001921 break;
1922 }
1923 }
1924
1925 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00001926 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001927 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1928 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1929 if (RHS_CR.isEmptySet())
1930 return ConstantInt::getFalse(CI->getContext());
1931 if (RHS_CR.isFullSet())
1932 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00001933
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001934 // Many binary operators with constant RHS have easy to compute constant
1935 // range. Use them to check whether the comparison is a tautology.
David Majnemer78910fc2014-05-16 17:14:03 +00001936 unsigned Width = CI->getBitWidth();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001937 APInt Lower = APInt(Width, 0);
1938 APInt Upper = APInt(Width, 0);
1939 ConstantInt *CI2;
1940 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1941 // 'urem x, CI2' produces [0, CI2).
1942 Upper = CI2->getValue();
1943 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1944 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1945 Upper = CI2->getValue().abs();
1946 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00001947 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1948 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00001949 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001950 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1951 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1952 APInt NegOne = APInt::getAllOnesValue(Width);
1953 if (!CI2->isZero())
1954 Upper = NegOne.udiv(CI2->getValue()) + 1;
David Majnemerea8d5db2014-05-16 16:57:04 +00001955 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
David Majnemer651ed5e2014-07-04 00:23:39 +00001956 if (CI2->isMinSignedValue()) {
1957 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
1958 Lower = CI2->getValue();
1959 Upper = Lower.lshr(1) + 1;
1960 } else {
1961 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
1962 Upper = CI2->getValue().abs() + 1;
1963 Lower = (-Upper) + 1;
1964 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001965 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001966 APInt IntMin = APInt::getSignedMinValue(Width);
1967 APInt IntMax = APInt::getSignedMaxValue(Width);
David Majnemeraf9180f2014-07-14 20:38:45 +00001968 APInt Val = CI2->getValue();
1969 if (Val.isAllOnesValue()) {
1970 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
1971 // where CI2 != -1 and CI2 != 0 and CI2 != 1
1972 Lower = IntMin + 1;
1973 Upper = IntMax + 1;
1974 } else if (Val.countLeadingZeros() < Width - 1) {
1975 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
1976 // where CI2 != -1 and CI2 != 0 and CI2 != 1
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001977 Lower = IntMin.sdiv(Val);
David Majnemeraf9180f2014-07-14 20:38:45 +00001978 Upper = IntMax.sdiv(Val);
1979 if (Lower.sgt(Upper))
1980 std::swap(Lower, Upper);
1981 Upper = Upper + 1;
David Majnemer5ea4fc02014-07-14 19:49:57 +00001982 assert(Upper != Lower && "Upper part of range has wrapped!");
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001983 }
1984 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1985 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1986 APInt NegOne = APInt::getAllOnesValue(Width);
1987 if (CI2->getValue().ult(Width))
1988 Upper = NegOne.lshr(CI2->getValue()) + 1;
David Majnemer78910fc2014-05-16 17:14:03 +00001989 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
1990 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
1991 unsigned ShiftAmount = Width - 1;
1992 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
1993 ShiftAmount = CI2->getValue().countTrailingZeros();
1994 Lower = CI2->getValue().lshr(ShiftAmount);
1995 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00001996 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1997 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1998 APInt IntMin = APInt::getSignedMinValue(Width);
1999 APInt IntMax = APInt::getSignedMaxValue(Width);
2000 if (CI2->getValue().ult(Width)) {
2001 Lower = IntMin.ashr(CI2->getValue());
2002 Upper = IntMax.ashr(CI2->getValue()) + 1;
2003 }
David Majnemer78910fc2014-05-16 17:14:03 +00002004 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2005 unsigned ShiftAmount = Width - 1;
2006 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2007 ShiftAmount = CI2->getValue().countTrailingZeros();
2008 if (CI2->isNegative()) {
2009 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2010 Lower = CI2->getValue();
2011 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2012 } else {
2013 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2014 Lower = CI2->getValue().ashr(ShiftAmount);
2015 Upper = CI2->getValue() + 1;
2016 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002017 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2018 // 'or x, CI2' produces [CI2, UINT_MAX].
2019 Lower = CI2->getValue();
2020 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2021 // 'and x, CI2' produces [0, CI2].
2022 Upper = CI2->getValue() + 1;
2023 }
2024 if (Lower != Upper) {
2025 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2026 if (RHS_CR.contains(LHS_CR))
2027 return ConstantInt::getTrue(RHS->getContext());
2028 if (RHS_CR.inverse().contains(LHS_CR))
2029 return ConstantInt::getFalse(RHS->getContext());
2030 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002031 }
2032
Duncan Sands8fb2c382011-01-20 13:21:55 +00002033 // Compare of cast, for example (zext X) != 0 -> X != 0
2034 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2035 Instruction *LI = cast<CastInst>(LHS);
2036 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002037 Type *SrcTy = SrcOp->getType();
2038 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002039
2040 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2041 // if the integer type is the same size as the pointer type.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002042 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2043 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002044 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2045 // Transfer the cast to the constant.
2046 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2047 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002048 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002049 return V;
2050 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2051 if (RI->getOperand(0)->getType() == SrcTy)
2052 // Compare without the cast.
2053 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002054 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002055 return V;
2056 }
2057 }
2058
2059 if (isa<ZExtInst>(LHS)) {
2060 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2061 // same type.
2062 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2063 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2064 // Compare X and Y. Note that signed predicates become unsigned.
2065 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002066 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002067 MaxRecurse-1))
2068 return V;
2069 }
2070 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2071 // too. If not, then try to deduce the result of the comparison.
2072 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2073 // Compute the constant that would happen if we truncated to SrcTy then
2074 // reextended to DstTy.
2075 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2076 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2077
2078 // If the re-extended constant didn't change then this is effectively
2079 // also a case of comparing two zero-extended values.
2080 if (RExt == CI && MaxRecurse)
2081 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002082 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002083 return V;
2084
2085 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2086 // there. Use this to work out the result of the comparison.
2087 if (RExt != CI) {
2088 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002089 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002090 // LHS <u RHS.
2091 case ICmpInst::ICMP_EQ:
2092 case ICmpInst::ICMP_UGT:
2093 case ICmpInst::ICMP_UGE:
2094 return ConstantInt::getFalse(CI->getContext());
2095
2096 case ICmpInst::ICMP_NE:
2097 case ICmpInst::ICMP_ULT:
2098 case ICmpInst::ICMP_ULE:
2099 return ConstantInt::getTrue(CI->getContext());
2100
2101 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2102 // is non-negative then LHS <s RHS.
2103 case ICmpInst::ICMP_SGT:
2104 case ICmpInst::ICMP_SGE:
2105 return CI->getValue().isNegative() ?
2106 ConstantInt::getTrue(CI->getContext()) :
2107 ConstantInt::getFalse(CI->getContext());
2108
2109 case ICmpInst::ICMP_SLT:
2110 case ICmpInst::ICMP_SLE:
2111 return CI->getValue().isNegative() ?
2112 ConstantInt::getFalse(CI->getContext()) :
2113 ConstantInt::getTrue(CI->getContext());
2114 }
2115 }
2116 }
2117 }
2118
2119 if (isa<SExtInst>(LHS)) {
2120 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2121 // same type.
2122 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2123 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2124 // Compare X and Y. Note that the predicate does not change.
2125 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002126 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002127 return V;
2128 }
2129 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2130 // too. If not, then try to deduce the result of the comparison.
2131 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2132 // Compute the constant that would happen if we truncated to SrcTy then
2133 // reextended to DstTy.
2134 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2135 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2136
2137 // If the re-extended constant didn't change then this is effectively
2138 // also a case of comparing two sign-extended values.
2139 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002140 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002141 return V;
2142
2143 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2144 // bits there. Use this to work out the result of the comparison.
2145 if (RExt != CI) {
2146 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002147 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002148 case ICmpInst::ICMP_EQ:
2149 return ConstantInt::getFalse(CI->getContext());
2150 case ICmpInst::ICMP_NE:
2151 return ConstantInt::getTrue(CI->getContext());
2152
2153 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2154 // LHS >s RHS.
2155 case ICmpInst::ICMP_SGT:
2156 case ICmpInst::ICMP_SGE:
2157 return CI->getValue().isNegative() ?
2158 ConstantInt::getTrue(CI->getContext()) :
2159 ConstantInt::getFalse(CI->getContext());
2160 case ICmpInst::ICMP_SLT:
2161 case ICmpInst::ICMP_SLE:
2162 return CI->getValue().isNegative() ?
2163 ConstantInt::getFalse(CI->getContext()) :
2164 ConstantInt::getTrue(CI->getContext());
2165
2166 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2167 // LHS >u RHS.
2168 case ICmpInst::ICMP_UGT:
2169 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002170 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002171 if (MaxRecurse)
2172 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2173 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002174 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002175 return V;
2176 break;
2177 case ICmpInst::ICMP_ULT:
2178 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002179 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002180 if (MaxRecurse)
2181 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2182 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002183 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002184 return V;
2185 break;
2186 }
2187 }
2188 }
2189 }
2190 }
2191
Nick Lewyckyc9610302014-06-19 03:35:49 +00002192 // If a bit is known to be zero for A and known to be one for B,
2193 // then A and B cannot be equal.
2194 if (ICmpInst::isEquality(Pred)) {
2195 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2196 uint32_t BitWidth = CI->getBitWidth();
2197 APInt LHSKnownZero(BitWidth, 0);
2198 APInt LHSKnownOne(BitWidth, 0);
2199 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne);
2200 APInt RHSKnownZero(BitWidth, 0);
2201 APInt RHSKnownOne(BitWidth, 0);
2202 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne);
2203 if (((LHSKnownOne & RHSKnownZero) != 0) ||
2204 ((LHSKnownZero & RHSKnownOne) != 0))
2205 return (Pred == ICmpInst::ICMP_EQ)
2206 ? ConstantInt::getFalse(CI->getContext())
2207 : ConstantInt::getTrue(CI->getContext());
2208 }
2209 }
2210
Duncan Sandsd114ab32011-02-13 17:15:40 +00002211 // Special logic for binary operators.
2212 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2213 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2214 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002215 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002216 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002217 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2218 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2219 if (LBO && LBO->getOpcode() == Instruction::Add) {
2220 A = LBO->getOperand(0); B = LBO->getOperand(1);
2221 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2222 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2223 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2224 }
2225 if (RBO && RBO->getOpcode() == Instruction::Add) {
2226 C = RBO->getOperand(0); D = RBO->getOperand(1);
2227 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2228 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2229 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2230 }
2231
2232 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2233 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2234 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2235 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002236 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002237 return V;
2238
2239 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2240 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2241 if (Value *V = SimplifyICmpInst(Pred,
2242 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002243 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002244 return V;
2245
2246 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2247 if (A && C && (A == C || A == D || B == C || B == D) &&
2248 NoLHSWrapProblem && NoRHSWrapProblem) {
2249 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002250 Value *Y, *Z;
2251 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002252 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002253 Y = B;
2254 Z = D;
2255 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002256 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002257 Y = B;
2258 Z = C;
2259 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002260 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002261 Y = A;
2262 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002263 } else {
2264 assert(B == D);
2265 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002266 Y = A;
2267 Z = C;
2268 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002269 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002270 return V;
2271 }
2272 }
2273
David Majnemer2d6c0232014-05-14 20:16:28 +00002274 // 0 - (zext X) pred C
2275 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2276 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2277 if (RHSC->getValue().isStrictlyPositive()) {
2278 if (Pred == ICmpInst::ICMP_SLT)
2279 return ConstantInt::getTrue(RHSC->getContext());
2280 if (Pred == ICmpInst::ICMP_SGE)
2281 return ConstantInt::getFalse(RHSC->getContext());
2282 if (Pred == ICmpInst::ICMP_EQ)
2283 return ConstantInt::getFalse(RHSC->getContext());
2284 if (Pred == ICmpInst::ICMP_NE)
2285 return ConstantInt::getTrue(RHSC->getContext());
2286 }
2287 if (RHSC->getValue().isNonNegative()) {
2288 if (Pred == ICmpInst::ICMP_SLE)
2289 return ConstantInt::getTrue(RHSC->getContext());
2290 if (Pred == ICmpInst::ICMP_SGT)
2291 return ConstantInt::getFalse(RHSC->getContext());
2292 }
2293 }
2294 }
2295
Nick Lewycky35aeea92013-07-12 23:42:57 +00002296 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002297 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002298 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002299 switch (Pred) {
2300 default:
2301 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002302 case ICmpInst::ICMP_SGT:
2303 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002304 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002305 if (!KnownNonNegative)
2306 break;
2307 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002308 case ICmpInst::ICMP_EQ:
2309 case ICmpInst::ICMP_UGT:
2310 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002311 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002312 case ICmpInst::ICMP_SLT:
2313 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002314 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002315 if (!KnownNonNegative)
2316 break;
2317 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002318 case ICmpInst::ICMP_NE:
2319 case ICmpInst::ICMP_ULT:
2320 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002321 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002322 }
2323 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002324
2325 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002326 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2327 bool KnownNonNegative, KnownNegative;
2328 switch (Pred) {
2329 default:
2330 break;
2331 case ICmpInst::ICMP_SGT:
2332 case ICmpInst::ICMP_SGE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002333 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky980104d2011-03-09 06:26:03 +00002334 if (!KnownNonNegative)
2335 break;
2336 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002337 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002338 case ICmpInst::ICMP_UGT:
2339 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002340 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002341 case ICmpInst::ICMP_SLT:
2342 case ICmpInst::ICMP_SLE:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002343 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL);
Nick Lewycky980104d2011-03-09 06:26:03 +00002344 if (!KnownNonNegative)
2345 break;
2346 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002347 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002348 case ICmpInst::ICMP_ULT:
2349 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002350 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002351 }
2352 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002353
Duncan Sands92af0a82011-10-28 18:17:44 +00002354 // x udiv y <=u x.
2355 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2356 // icmp pred (X /u Y), X
2357 if (Pred == ICmpInst::ICMP_UGT)
2358 return getFalse(ITy);
2359 if (Pred == ICmpInst::ICMP_ULE)
2360 return getTrue(ITy);
2361 }
2362
Nick Lewycky9719a712011-03-05 05:19:11 +00002363 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2364 LBO->getOperand(1) == RBO->getOperand(1)) {
2365 switch (LBO->getOpcode()) {
2366 default: break;
2367 case Instruction::UDiv:
2368 case Instruction::LShr:
2369 if (ICmpInst::isSigned(Pred))
2370 break;
2371 // fall-through
2372 case Instruction::SDiv:
2373 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002374 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002375 break;
2376 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002377 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002378 return V;
2379 break;
2380 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002381 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002382 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2383 if (!NUW && !NSW)
2384 break;
2385 if (!NSW && ICmpInst::isSigned(Pred))
2386 break;
2387 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002388 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002389 return V;
2390 break;
2391 }
2392 }
2393 }
2394
Duncan Sands0a9c1242011-05-03 19:53:10 +00002395 // Simplify comparisons involving max/min.
2396 Value *A, *B;
2397 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002398 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002399
Duncan Sandsa2287852011-05-04 16:05:05 +00002400 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002401 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2402 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002403 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002404 // We analyze this as smax(A, B) pred A.
2405 P = Pred;
2406 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2407 (A == LHS || B == LHS)) {
2408 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002409 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002410 // We analyze this as smax(A, B) swapped-pred A.
2411 P = CmpInst::getSwappedPredicate(Pred);
2412 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2413 (A == RHS || B == RHS)) {
2414 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002415 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002416 // We analyze this as smax(-A, -B) swapped-pred -A.
2417 // Note that we do not need to actually form -A or -B thanks to EqP.
2418 P = CmpInst::getSwappedPredicate(Pred);
2419 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2420 (A == LHS || B == LHS)) {
2421 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002422 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002423 // We analyze this as smax(-A, -B) pred -A.
2424 // Note that we do not need to actually form -A or -B thanks to EqP.
2425 P = Pred;
2426 }
2427 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2428 // Cases correspond to "max(A, B) p A".
2429 switch (P) {
2430 default:
2431 break;
2432 case CmpInst::ICMP_EQ:
2433 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002434 // Equivalent to "A EqP B". This may be the same as the condition tested
2435 // in the max/min; if so, we can just return that.
2436 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2437 return V;
2438 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2439 return V;
2440 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002441 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002442 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002443 return V;
2444 break;
2445 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002446 case CmpInst::ICMP_SGT: {
2447 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2448 // Equivalent to "A InvEqP B". This may be the same as the condition
2449 // tested in the max/min; if so, we can just return that.
2450 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2451 return V;
2452 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2453 return V;
2454 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002455 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002456 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002457 return V;
2458 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002459 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002460 case CmpInst::ICMP_SGE:
2461 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002462 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002463 case CmpInst::ICMP_SLT:
2464 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002465 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002466 }
2467 }
2468
Duncan Sandsa2287852011-05-04 16:05:05 +00002469 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002470 P = CmpInst::BAD_ICMP_PREDICATE;
2471 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2472 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002473 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002474 // We analyze this as umax(A, B) pred A.
2475 P = Pred;
2476 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2477 (A == LHS || B == LHS)) {
2478 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002479 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002480 // We analyze this as umax(A, B) swapped-pred A.
2481 P = CmpInst::getSwappedPredicate(Pred);
2482 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2483 (A == RHS || B == RHS)) {
2484 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002485 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002486 // We analyze this as umax(-A, -B) swapped-pred -A.
2487 // Note that we do not need to actually form -A or -B thanks to EqP.
2488 P = CmpInst::getSwappedPredicate(Pred);
2489 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2490 (A == LHS || B == LHS)) {
2491 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002492 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002493 // We analyze this as umax(-A, -B) pred -A.
2494 // Note that we do not need to actually form -A or -B thanks to EqP.
2495 P = Pred;
2496 }
2497 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2498 // Cases correspond to "max(A, B) p A".
2499 switch (P) {
2500 default:
2501 break;
2502 case CmpInst::ICMP_EQ:
2503 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002504 // Equivalent to "A EqP B". This may be the same as the condition tested
2505 // in the max/min; if so, we can just return that.
2506 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2507 return V;
2508 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2509 return V;
2510 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002511 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002512 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002513 return V;
2514 break;
2515 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002516 case CmpInst::ICMP_UGT: {
2517 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2518 // Equivalent to "A InvEqP B". This may be the same as the condition
2519 // tested in the max/min; if so, we can just return that.
2520 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2521 return V;
2522 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2523 return V;
2524 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002525 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002526 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002527 return V;
2528 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002529 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002530 case CmpInst::ICMP_UGE:
2531 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002532 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002533 case CmpInst::ICMP_ULT:
2534 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002535 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002536 }
2537 }
2538
Duncan Sandsa2287852011-05-04 16:05:05 +00002539 // Variants on "max(x,y) >= min(x,z)".
2540 Value *C, *D;
2541 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2542 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2543 (A == C || A == D || B == C || B == D)) {
2544 // max(x, ?) pred min(x, ?).
2545 if (Pred == CmpInst::ICMP_SGE)
2546 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002547 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002548 if (Pred == CmpInst::ICMP_SLT)
2549 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002550 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002551 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2552 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2553 (A == C || A == D || B == C || B == D)) {
2554 // min(x, ?) pred max(x, ?).
2555 if (Pred == CmpInst::ICMP_SLE)
2556 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002557 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002558 if (Pred == CmpInst::ICMP_SGT)
2559 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002560 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002561 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2562 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2563 (A == C || A == D || B == C || B == D)) {
2564 // max(x, ?) pred min(x, ?).
2565 if (Pred == CmpInst::ICMP_UGE)
2566 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002567 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002568 if (Pred == CmpInst::ICMP_ULT)
2569 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002570 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002571 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2572 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2573 (A == C || A == D || B == C || B == D)) {
2574 // min(x, ?) pred max(x, ?).
2575 if (Pred == CmpInst::ICMP_ULE)
2576 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002577 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002578 if (Pred == CmpInst::ICMP_UGT)
2579 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002580 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00002581 }
2582
Chandler Carruth8059c842012-03-25 21:28:14 +00002583 // Simplify comparisons of related pointers using a powerful, recursive
2584 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00002585 if (LHS->getType()->isPointerTy())
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002586 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00002587 return C;
2588
Nick Lewycky3db143e2012-02-26 02:09:49 +00002589 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2590 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2591 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2592 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2593 (ICmpInst::isEquality(Pred) ||
2594 (GLHS->isInBounds() && GRHS->isInBounds() &&
2595 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2596 // The bases are equal and the indices are constant. Build a constant
2597 // expression GEP with the same indices and a null base pointer to see
2598 // what constant folding can make out of it.
2599 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2600 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2601 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2602
2603 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2604 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2605 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2606 }
2607 }
2608 }
2609
Duncan Sandsf532d312010-11-07 16:12:23 +00002610 // If the comparison is with the result of a select instruction, check whether
2611 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002612 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002613 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002614 return V;
2615
2616 // If the comparison is with the result of a phi instruction, check whether
2617 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002618 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002619 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002620 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00002621
Craig Topper9f008862014-04-15 04:59:12 +00002622 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00002623}
2624
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002625Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002626 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002627 const TargetLibraryInfo *TLI,
2628 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002629 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002630 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002631}
2632
Chris Lattnerc1f19072009-11-09 23:28:39 +00002633/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2634/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002635static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002636 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002637 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2638 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2639
Chris Lattnera71e9d62009-11-10 00:55:12 +00002640 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00002641 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002642 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00002643
Chris Lattnera71e9d62009-11-10 00:55:12 +00002644 // If we have a constant, make sure it is on the RHS.
2645 std::swap(LHS, RHS);
2646 Pred = CmpInst::getSwappedPredicate(Pred);
2647 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002648
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002649 // Fold trivial predicates.
2650 if (Pred == FCmpInst::FCMP_FALSE)
2651 return ConstantInt::get(GetCompareTy(LHS), 0);
2652 if (Pred == FCmpInst::FCMP_TRUE)
2653 return ConstantInt::get(GetCompareTy(LHS), 1);
2654
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002655 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2656 return UndefValue::get(GetCompareTy(LHS));
2657
2658 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00002659 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002660 if (CmpInst::isTrueWhenEqual(Pred))
2661 return ConstantInt::get(GetCompareTy(LHS), 1);
2662 if (CmpInst::isFalseWhenEqual(Pred))
2663 return ConstantInt::get(GetCompareTy(LHS), 0);
2664 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002665
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002666 // Handle fcmp with constant RHS
2667 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2668 // If the constant is a nan, see if we can fold the comparison based on it.
2669 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2670 if (CFP->getValueAPF().isNaN()) {
2671 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2672 return ConstantInt::getFalse(CFP->getContext());
2673 assert(FCmpInst::isUnordered(Pred) &&
2674 "Comparison must be either ordered or unordered!");
2675 // True if unordered.
2676 return ConstantInt::getTrue(CFP->getContext());
2677 }
Dan Gohman754e4a92010-02-22 04:06:03 +00002678 // Check whether the constant is an infinity.
2679 if (CFP->getValueAPF().isInfinity()) {
2680 if (CFP->getValueAPF().isNegative()) {
2681 switch (Pred) {
2682 case FCmpInst::FCMP_OLT:
2683 // No value is ordered and less than negative infinity.
2684 return ConstantInt::getFalse(CFP->getContext());
2685 case FCmpInst::FCMP_UGE:
2686 // All values are unordered with or at least negative infinity.
2687 return ConstantInt::getTrue(CFP->getContext());
2688 default:
2689 break;
2690 }
2691 } else {
2692 switch (Pred) {
2693 case FCmpInst::FCMP_OGT:
2694 // No value is ordered and greater than infinity.
2695 return ConstantInt::getFalse(CFP->getContext());
2696 case FCmpInst::FCMP_ULE:
2697 // All values are unordered with and at most infinity.
2698 return ConstantInt::getTrue(CFP->getContext());
2699 default:
2700 break;
2701 }
2702 }
2703 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002704 }
2705 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002706
Duncan Sandsa620bd12010-11-07 16:46:25 +00002707 // If the comparison is with the result of a select instruction, check whether
2708 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002709 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002710 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002711 return V;
2712
2713 // If the comparison is with the result of a phi instruction, check whether
2714 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002715 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002716 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00002717 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00002718
Craig Topper9f008862014-04-15 04:59:12 +00002719 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002720}
2721
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002722Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002723 const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002724 const TargetLibraryInfo *TLI,
2725 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002726 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002727 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002728}
2729
Chris Lattnerc707fa92010-04-20 05:32:14 +00002730/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2731/// the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002732static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2733 Value *FalseVal, const Query &Q,
2734 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00002735 // select true, X, Y -> X
2736 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002737 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2738 if (CB->isAllOnesValue())
2739 return TrueVal;
2740 if (CB->isNullValue())
2741 return FalseVal;
2742 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002743
Chris Lattnerc707fa92010-04-20 05:32:14 +00002744 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00002745 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00002746 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002747
Chris Lattnerc707fa92010-04-20 05:32:14 +00002748 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2749 if (isa<Constant>(TrueVal))
2750 return TrueVal;
2751 return FalseVal;
2752 }
Dan Gohman54664ed2011-07-01 01:03:43 +00002753 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2754 return FalseVal;
2755 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2756 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00002757
Craig Topper9f008862014-04-15 04:59:12 +00002758 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00002759}
2760
Duncan Sandsb8cee002012-03-13 11:42:19 +00002761Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002762 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002763 const TargetLibraryInfo *TLI,
2764 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002765 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002766 RecursionLimit);
2767}
2768
Chris Lattner8574aba2009-11-27 00:29:05 +00002769/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2770/// fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002771static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00002772 // The type of the GEP pointer operand.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002773 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
Duncan Sands8a0f4862010-11-22 13:42:49 +00002774
Chris Lattner8574aba2009-11-27 00:29:05 +00002775 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00002776 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00002777 return Ops[0];
2778
Duncan Sands8a0f4862010-11-22 13:42:49 +00002779 if (isa<UndefValue>(Ops[0])) {
2780 // Compute the (pointer) type returned by the GEP instruction.
Jay Foadd1b78492011-07-25 09:48:08 +00002781 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattner229907c2011-07-18 04:54:35 +00002782 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002783 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
2784 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Duncan Sands8a0f4862010-11-22 13:42:49 +00002785 return UndefValue::get(GEPTy);
2786 }
Chris Lattner8574aba2009-11-27 00:29:05 +00002787
Jay Foadb992a632011-07-19 15:07:52 +00002788 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002789 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00002790 if (match(Ops[1], m_Zero()))
2791 return Ops[0];
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002792 // getelementptr P, N -> P if P points to a type of zero size.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002793 if (Q.DL) {
Chris Lattner229907c2011-07-18 04:54:35 +00002794 Type *Ty = PtrTy->getElementType();
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002795 if (Ty->isSized() && Q.DL->getTypeAllocSize(Ty) == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00002796 return Ops[0];
2797 }
2798 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002799
Chris Lattner8574aba2009-11-27 00:29:05 +00002800 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00002801 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00002802 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00002803 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00002804
Jay Foaded8db7d2011-07-21 14:31:17 +00002805 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00002806}
2807
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002808Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002809 const TargetLibraryInfo *TLI,
2810 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002811 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002812}
2813
Duncan Sandsfd26a952011-09-05 06:52:48 +00002814/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2815/// can fold the result. If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002816static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2817 ArrayRef<unsigned> Idxs, const Query &Q,
2818 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00002819 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2820 if (Constant *CVal = dyn_cast<Constant>(Val))
2821 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2822
2823 // insertvalue x, undef, n -> x
2824 if (match(Val, m_Undef()))
2825 return Agg;
2826
2827 // insertvalue x, (extractvalue y, n), n
2828 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00002829 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2830 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00002831 // insertvalue undef, (extractvalue y, n), n -> y
2832 if (match(Agg, m_Undef()))
2833 return EV->getAggregateOperand();
2834
2835 // insertvalue y, (extractvalue y, n), n -> y
2836 if (Agg == EV->getAggregateOperand())
2837 return Agg;
2838 }
2839
Craig Topper9f008862014-04-15 04:59:12 +00002840 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00002841}
2842
Duncan Sandsb8cee002012-03-13 11:42:19 +00002843Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2844 ArrayRef<unsigned> Idxs,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002845 const DataLayout *DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002846 const TargetLibraryInfo *TLI,
2847 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002848 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002849 RecursionLimit);
2850}
2851
Duncan Sands7412f6e2010-11-17 04:30:22 +00002852/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002853static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00002854 // If all of the PHI's incoming values are the same then replace the PHI node
2855 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00002856 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00002857 bool HasUndefInput = false;
2858 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2859 Value *Incoming = PN->getIncomingValue(i);
2860 // If the incoming value is the phi node itself, it can safely be skipped.
2861 if (Incoming == PN) continue;
2862 if (isa<UndefValue>(Incoming)) {
2863 // Remember that we saw an undef value, but otherwise ignore them.
2864 HasUndefInput = true;
2865 continue;
2866 }
2867 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00002868 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00002869 CommonValue = Incoming;
2870 }
2871
2872 // If CommonValue is null then all of the incoming values were either undef or
2873 // equal to the phi node itself.
2874 if (!CommonValue)
2875 return UndefValue::get(PN->getType());
2876
2877 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2878 // instruction, we cannot return X as the result of the PHI node unless it
2879 // dominates the PHI block.
2880 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00002881 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00002882
2883 return CommonValue;
2884}
2885
Duncan Sands395ac42d2012-03-13 14:07:05 +00002886static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2887 if (Constant *C = dyn_cast<Constant>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002888 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
Duncan Sands395ac42d2012-03-13 14:07:05 +00002889
Craig Topper9f008862014-04-15 04:59:12 +00002890 return nullptr;
Duncan Sands395ac42d2012-03-13 14:07:05 +00002891}
2892
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002893Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00002894 const TargetLibraryInfo *TLI,
2895 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002896 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT), RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00002897}
2898
Chris Lattnera71e9d62009-11-10 00:55:12 +00002899//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00002900
Chris Lattnera71e9d62009-11-10 00:55:12 +00002901/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2902/// fold the result. If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002903static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002904 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00002905 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00002906 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002907 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002908 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002909 case Instruction::FAdd:
2910 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2911
Chris Lattner9e4aa022011-02-09 17:15:04 +00002912 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002913 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002914 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002915 case Instruction::FSub:
2916 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
2917
Duncan Sandsb8cee002012-03-13 11:42:19 +00002918 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00002919 case Instruction::FMul:
2920 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00002921 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2922 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2923 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2924 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2925 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2926 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002927 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00002928 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002929 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002930 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00002931 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00002932 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00002933 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2934 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2935 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2936 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002937 default:
2938 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2939 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2940 Constant *COps[] = {CLHS, CRHS};
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002941 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002942 Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002943 }
Duncan Sandsb0579e92010-11-10 13:00:08 +00002944
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002945 // If the operation is associative, try some generic simplifications.
2946 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002947 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002948 return V;
2949
Duncan Sandsb8cee002012-03-13 11:42:19 +00002950 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00002951 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002952 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002953 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002954 return V;
2955
2956 // If the operation is with the result of a phi instruction, check whether
2957 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00002958 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002959 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00002960 return V;
2961
Craig Topper9f008862014-04-15 04:59:12 +00002962 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00002963 }
2964}
Chris Lattnerc1f19072009-11-09 23:28:39 +00002965
Duncan Sands7e800d62010-11-14 11:23:23 +00002966Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002967 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002968 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002969 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT), RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00002970}
2971
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002972/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2973/// fold the result.
2974static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002975 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002976 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00002977 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2978 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002979}
2980
2981Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002982 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002983 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002984 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002985 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002986}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00002987
Michael Ilseman54857292013-02-07 19:26:05 +00002988static bool IsIdempotent(Intrinsic::ID ID) {
2989 switch (ID) {
2990 default: return false;
2991
2992 // Unary idempotent: f(f(x)) = f(x)
2993 case Intrinsic::fabs:
2994 case Intrinsic::floor:
2995 case Intrinsic::ceil:
2996 case Intrinsic::trunc:
2997 case Intrinsic::rint:
2998 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00002999 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00003000 return true;
3001 }
3002}
3003
3004template <typename IterTy>
3005static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
3006 const Query &Q, unsigned MaxRecurse) {
3007 // Perform idempotent optimizations
3008 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00003009 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003010
3011 // Unary Ops
3012 if (std::distance(ArgBegin, ArgEnd) == 1)
3013 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3014 if (II->getIntrinsicID() == IID)
3015 return II;
3016
Craig Topper9f008862014-04-15 04:59:12 +00003017 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003018}
3019
Chandler Carruth9dc35582012-12-28 11:30:55 +00003020template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00003021static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003022 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00003023 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00003024 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3025 Ty = PTy->getElementType();
3026 FunctionType *FTy = cast<FunctionType>(Ty);
3027
Dan Gohman85977e62011-11-04 18:32:42 +00003028 // call undef -> undef
Chandler Carruthf6182152012-12-28 14:23:29 +00003029 if (isa<UndefValue>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00003030 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00003031
Chandler Carruthf6182152012-12-28 14:23:29 +00003032 Function *F = dyn_cast<Function>(V);
3033 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00003034 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003035
Michael Ilseman54857292013-02-07 19:26:05 +00003036 if (unsigned IID = F->getIntrinsicID())
3037 if (Value *Ret =
3038 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3039 return Ret;
3040
Chandler Carruthf6182152012-12-28 14:23:29 +00003041 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00003042 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003043
3044 SmallVector<Constant *, 4> ConstantArgs;
3045 ConstantArgs.reserve(ArgEnd - ArgBegin);
3046 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3047 Constant *C = dyn_cast<Constant>(*I);
3048 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00003049 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003050 ConstantArgs.push_back(C);
3051 }
3052
3053 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00003054}
3055
Chandler Carruthf6182152012-12-28 14:23:29 +00003056Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003057 User::op_iterator ArgEnd, const DataLayout *DL,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003058 const TargetLibraryInfo *TLI,
3059 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003060 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003061 RecursionLimit);
3062}
3063
Chandler Carruthf6182152012-12-28 14:23:29 +00003064Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003065 const DataLayout *DL, const TargetLibraryInfo *TLI,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003066 const DominatorTree *DT) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003067 return ::SimplifyCall(V, Args.begin(), Args.end(), Query(DL, TLI, DT),
Chandler Carruth9dc35582012-12-28 11:30:55 +00003068 RecursionLimit);
3069}
3070
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003071/// SimplifyInstruction - See if we can compute a simplified version of this
3072/// instruction. If not, this returns null.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003073Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003074 const TargetLibraryInfo *TLI,
Duncan Sandsb99f39b2010-11-14 18:36:10 +00003075 const DominatorTree *DT) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00003076 Value *Result;
3077
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003078 switch (I->getOpcode()) {
3079 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003080 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003081 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003082 case Instruction::FAdd:
3083 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003084 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003085 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00003086 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003087 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3088 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3089 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003090 DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003091 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003092 case Instruction::FSub:
3093 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003094 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00003095 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00003096 case Instruction::Sub:
3097 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3098 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3099 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003100 DL, TLI, DT);
Duncan Sands0a2c41682010-12-15 14:07:39 +00003101 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003102 case Instruction::FMul:
3103 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003104 I->getFastMathFlags(), DL, TLI, DT);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00003105 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003106 case Instruction::Mul:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003107 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00003108 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00003109 case Instruction::SDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003110 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands771e82a2011-01-28 16:51:11 +00003111 break;
3112 case Instruction::UDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003113 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands771e82a2011-01-28 16:51:11 +00003114 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00003115 case Instruction::FDiv:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003116 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Frits van Bommelc2549662011-01-29 15:26:31 +00003117 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00003118 case Instruction::SRem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003119 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003120 break;
3121 case Instruction::URem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003122 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003123 break;
3124 case Instruction::FRem:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003125 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsa3e36992011-05-02 16:27:02 +00003126 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00003127 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003128 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3129 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3130 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003131 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003132 break;
3133 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003134 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3135 cast<BinaryOperator>(I)->isExact(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003136 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003137 break;
3138 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00003139 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3140 cast<BinaryOperator>(I)->isExact(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003141 DL, TLI, DT);
Duncan Sands7f60dc12011-01-14 00:37:45 +00003142 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003143 case Instruction::And:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003144 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003145 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003146 case Instruction::Or:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003147 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003148 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00003149 case Instruction::Xor:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003150 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sandsc89ac072010-11-17 18:52:15 +00003151 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003152 case Instruction::ICmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003153 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003154 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003155 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003156 case Instruction::FCmp:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003157 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003158 I->getOperand(0), I->getOperand(1), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003159 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003160 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00003161 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003162 I->getOperand(2), DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003163 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003164 case Instruction::GetElementPtr: {
3165 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003166 Result = SimplifyGEPInst(Ops, DL, TLI, DT);
Duncan Sands64e41cf2010-11-17 08:35:29 +00003167 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00003168 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00003169 case Instruction::InsertValue: {
3170 InsertValueInst *IV = cast<InsertValueInst>(I);
3171 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3172 IV->getInsertedValueOperand(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003173 IV->getIndices(), DL, TLI, DT);
Duncan Sandsfd26a952011-09-05 06:52:48 +00003174 break;
3175 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00003176 case Instruction::PHI:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003177 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT));
Duncan Sands64e41cf2010-11-17 08:35:29 +00003178 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003179 case Instruction::Call: {
3180 CallSite CS(cast<CallInst>(I));
3181 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003182 DL, TLI, DT);
Dan Gohman85977e62011-11-04 18:32:42 +00003183 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00003184 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00003185 case Instruction::Trunc:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003186 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003187 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003188 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00003189
3190 /// If called on unreachable code, the above logic may report that the
3191 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00003192 /// detecting that case here, returning a safe value instead.
3193 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003194}
3195
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003196/// \brief Implementation of recursive simplification through an instructions
3197/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00003198///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003199/// This is the common implementation of the recursive simplification routines.
3200/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3201/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3202/// instructions to process and attempt to simplify it using
3203/// InstructionSimplify.
3204///
3205/// This routine returns 'true' only when *it* simplifies something. The passed
3206/// in simplified value does not count toward this.
3207static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003208 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003209 const TargetLibraryInfo *TLI,
3210 const DominatorTree *DT) {
3211 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003212 SmallSetVector<Instruction *, 8> Worklist;
Duncan Sands7e800d62010-11-14 11:23:23 +00003213
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003214 // If we have an explicit value to collapse to, do that round of the
3215 // simplification loop by hand initially.
3216 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00003217 for (User *U : I->users())
3218 if (U != I)
3219 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00003220
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003221 // Replace the instruction with its simplified value.
3222 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00003223
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003224 // Gracefully handle edge cases where the instruction is not wired into any
3225 // parent block.
3226 if (I->getParent())
3227 I->eraseFromParent();
3228 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003229 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00003230 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003231
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00003232 // Note that we must test the size on each iteration, the worklist can grow.
3233 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3234 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00003235
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003236 // See if this instruction simplifies.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003237 SimpleV = SimplifyInstruction(I, DL, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003238 if (!SimpleV)
3239 continue;
3240
3241 Simplified = true;
3242
3243 // Stash away all the uses of the old instruction so we can check them for
3244 // recursive simplifications after a RAUW. This is cheaper than checking all
3245 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003246 for (User *U : I->users())
3247 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003248
3249 // Replace the instruction with its simplified value.
3250 I->replaceAllUsesWith(SimpleV);
3251
3252 // Gracefully handle edge cases where the instruction is not wired into any
3253 // parent block.
3254 if (I->getParent())
3255 I->eraseFromParent();
3256 }
3257 return Simplified;
3258}
3259
3260bool llvm::recursivelySimplifyInstruction(Instruction *I,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003261 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003262 const TargetLibraryInfo *TLI,
3263 const DominatorTree *DT) {
Craig Topper9f008862014-04-15 04:59:12 +00003264 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003265}
3266
3267bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003268 const DataLayout *DL,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00003269 const TargetLibraryInfo *TLI,
3270 const DominatorTree *DT) {
3271 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3272 assert(SimpleV && "Must provide a simplified value.");
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003273 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT);
Chris Lattner852d6d62009-11-10 22:26:15 +00003274}