blob: a9fed16f8aa8d1690c6cfb4025e4c32316882e84 [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"
Hal Finkelafcd8db2014-12-01 23:38:06 +000023#include "llvm/Analysis/AliasAnalysis.h"
Anna Thomas43d7e1c2016-05-03 14:58:21 +000024#include "llvm/Analysis/CaptureTracking.h"
Chris Lattner084a1b52009-11-09 22:57:59 +000025#include "llvm/Analysis/ConstantFolding.h"
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +000026#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000027#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000028#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000029#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000031#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000032#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000033#include "llvm/IR/GlobalAlias.h"
34#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000035#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000036#include "llvm/IR/ValueHandle.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000037#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000038using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000039using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000040
Chandler Carruthf1221bd2014-04-22 02:48:03 +000041#define DEBUG_TYPE "instsimplify"
42
Chris Lattner9e4aa022011-02-09 17:15:04 +000043enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000044
Duncan Sands3547d2e2010-12-22 09:40:51 +000045STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000046STATISTIC(NumReassoc, "Number of reassociations");
47
Benjamin Kramercfd8d902014-09-12 08:56:53 +000048namespace {
Duncan Sandsb8cee002012-03-13 11:42:19 +000049struct Query {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000050 const DataLayout &DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000051 const TargetLibraryInfo *TLI;
52 const DominatorTree *DT;
Chandler Carruth66b31302015-01-04 12:03:27 +000053 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000054 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000055
Mehdi Aminia28d91d2015-03-10 02:37:25 +000056 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
Chandler Carruth66b31302015-01-04 12:03:27 +000057 const DominatorTree *dt, AssumptionCache *ac = nullptr,
Hal Finkel60db0582014-09-07 18:57:58 +000058 const Instruction *cxti = nullptr)
Chandler Carruth66b31302015-01-04 12:03:27 +000059 : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000060};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000061} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000062
63static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
64static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000065 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000066static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
67 const Query &, unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000068static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000069 unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000070static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
71static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sands395ac42d2012-03-13 14:07:05 +000072static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000073
Sanjay Patel472cc782016-01-11 22:14:42 +000074/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000075/// a vector with every element false, as appropriate for the type.
76static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000077 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000078 "Expected i1 type or a vector of i1!");
79 return Constant::getNullValue(Ty);
80}
81
Sanjay Patel472cc782016-01-11 22:14:42 +000082/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000083/// a vector with every element true, as appropriate for the type.
84static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000085 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000086 "Expected i1 type or a vector of i1!");
87 return Constant::getAllOnesValue(Ty);
88}
89
Duncan Sands3d5692a2011-10-30 19:56:36 +000090/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
91static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
92 Value *RHS) {
93 CmpInst *Cmp = dyn_cast<CmpInst>(V);
94 if (!Cmp)
95 return false;
96 CmpInst::Predicate CPred = Cmp->getPredicate();
97 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
98 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
99 return true;
100 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
101 CRHS == LHS;
102}
103
Sanjay Patel472cc782016-01-11 22:14:42 +0000104/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000105static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
106 Instruction *I = dyn_cast<Instruction>(V);
107 if (!I)
108 // Arguments and constants dominate all instructions.
109 return true;
110
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000111 // If we are processing instructions (and/or basic blocks) that have not been
112 // fully added to a function, the parent nodes may still be null. Simply
113 // return the conservative answer in these cases.
114 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
115 return false;
116
Duncan Sands5ffc2982010-11-16 12:16:38 +0000117 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000118 if (DT) {
119 if (!DT->isReachableFromEntry(P->getParent()))
120 return true;
121 if (!DT->isReachableFromEntry(I->getParent()))
122 return false;
123 return DT->dominates(I, P);
124 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000125
David Majnemer8a1c45d2015-12-12 05:38:55 +0000126 // Otherwise, if the instruction is in the entry block and is not an invoke,
127 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000128 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000129 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000130 return true;
131
132 return false;
133}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000134
Sanjay Patel472cc782016-01-11 22:14:42 +0000135/// Simplify "A op (B op' C)" by distributing op over op', turning it into
136/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000137/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
138/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
139/// Returns the simplified value, or null if no simplification was performed.
140static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000141 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000142 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000143 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000144 // Recursion is always used, so bail out at once if we already hit the limit.
145 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000146 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000147
148 // Check whether the expression has the form "(A op' B) op C".
149 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
150 if (Op0->getOpcode() == OpcodeToExpand) {
151 // It does! Try turning it into "(A op C) op' (B op C)".
152 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
153 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000154 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
155 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000156 // They do! Return "L op' R" if it simplifies or is already available.
157 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000158 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
159 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000160 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000161 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000162 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000163 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000164 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000165 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000166 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000167 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000168 }
169 }
170
171 // Check whether the expression has the form "A op (B op' C)".
172 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
173 if (Op1->getOpcode() == OpcodeToExpand) {
174 // It does! Try turning it into "(A op B) op' (A op C)".
175 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
176 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000177 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
178 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000179 // They do! Return "L op' R" if it simplifies or is already available.
180 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000181 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
182 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000183 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000184 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000185 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000186 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000187 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000188 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000189 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000190 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000191 }
192 }
193
Craig Topper9f008862014-04-15 04:59:12 +0000194 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000195}
196
Sanjay Patel472cc782016-01-11 22:14:42 +0000197/// Generic simplifications for associative binary operations.
198/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000199static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000200 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000201 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000202 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
203
204 // Recursion is always used, so bail out at once if we already hit the limit.
205 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000206 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000207
208 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
209 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
210
211 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
212 if (Op0 && Op0->getOpcode() == Opcode) {
213 Value *A = Op0->getOperand(0);
214 Value *B = Op0->getOperand(1);
215 Value *C = RHS;
216
217 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000218 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000219 // It does! Return "A op V" if it simplifies or is already available.
220 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000221 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000222 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000223 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000224 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000225 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000226 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000227 }
228 }
229
230 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
231 if (Op1 && Op1->getOpcode() == Opcode) {
232 Value *A = LHS;
233 Value *B = Op1->getOperand(0);
234 Value *C = Op1->getOperand(1);
235
236 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000237 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000238 // It does! Return "V op C" if it simplifies or is already available.
239 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000240 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000241 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000242 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000243 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000244 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000245 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000246 }
247 }
248
249 // The remaining transforms require commutativity as well as associativity.
250 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000251 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000252
253 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
254 if (Op0 && Op0->getOpcode() == Opcode) {
255 Value *A = Op0->getOperand(0);
256 Value *B = Op0->getOperand(1);
257 Value *C = RHS;
258
259 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000260 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000261 // It does! Return "V op B" if it simplifies or is already available.
262 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000263 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000264 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000265 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000266 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000267 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000268 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000269 }
270 }
271
272 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
273 if (Op1 && Op1->getOpcode() == Opcode) {
274 Value *A = LHS;
275 Value *B = Op1->getOperand(0);
276 Value *C = Op1->getOperand(1);
277
278 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000279 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000280 // It does! Return "B op V" if it simplifies or is already available.
281 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000282 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000283 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000284 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000285 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000286 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000287 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000288 }
289 }
290
Craig Topper9f008862014-04-15 04:59:12 +0000291 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000292}
293
Sanjay Patel472cc782016-01-11 22:14:42 +0000294/// In the case of a binary operation with a select instruction as an operand,
295/// try to simplify the binop by seeing whether evaluating it on both branches
296/// of the select results in the same value. Returns the common value if so,
297/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000298static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000299 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000300 // Recursion is always used, so bail out at once if we already hit the limit.
301 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000302 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000303
Duncan Sandsb0579e92010-11-10 13:00:08 +0000304 SelectInst *SI;
305 if (isa<SelectInst>(LHS)) {
306 SI = cast<SelectInst>(LHS);
307 } else {
308 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
309 SI = cast<SelectInst>(RHS);
310 }
311
312 // Evaluate the BinOp on the true and false branches of the select.
313 Value *TV;
314 Value *FV;
315 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000316 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
317 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000318 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000319 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
320 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000321 }
322
Duncan Sandse3c53952011-01-01 16:12:09 +0000323 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000324 // If they both failed to simplify then return null.
325 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000326 return TV;
327
328 // If one branch simplified to undef, return the other one.
329 if (TV && isa<UndefValue>(TV))
330 return FV;
331 if (FV && isa<UndefValue>(FV))
332 return TV;
333
334 // If applying the operation did not change the true and false select values,
335 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000336 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000337 return SI;
338
339 // If one branch simplified and the other did not, and the simplified
340 // value is equal to the unsimplified one, return the simplified value.
341 // For example, select (cond, X, X & Z) & Z -> X & Z.
342 if ((FV && !TV) || (TV && !FV)) {
343 // Check that the simplified value has the form "X op Y" where "op" is the
344 // same as the original operation.
345 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
346 if (Simplified && Simplified->getOpcode() == Opcode) {
347 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
348 // We already know that "op" is the same as for the simplified value. See
349 // if the operands match too. If so, return the simplified value.
350 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
351 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
352 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000353 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
354 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000355 return Simplified;
356 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000357 Simplified->getOperand(1) == UnsimplifiedLHS &&
358 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000359 return Simplified;
360 }
361 }
362
Craig Topper9f008862014-04-15 04:59:12 +0000363 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000364}
365
Sanjay Patel472cc782016-01-11 22:14:42 +0000366/// In the case of a comparison with a select instruction, try to simplify the
367/// comparison by seeing whether both branches of the select result in the same
368/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000369static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000370 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000371 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000372 // Recursion is always used, so bail out at once if we already hit the limit.
373 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000374 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000375
Duncan Sandsb0579e92010-11-10 13:00:08 +0000376 // Make sure the select is on the LHS.
377 if (!isa<SelectInst>(LHS)) {
378 std::swap(LHS, RHS);
379 Pred = CmpInst::getSwappedPredicate(Pred);
380 }
381 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
382 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000383 Value *Cond = SI->getCondition();
384 Value *TV = SI->getTrueValue();
385 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000386
Duncan Sands06504022011-02-03 09:37:39 +0000387 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000388 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000389 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000390 if (TCmp == Cond) {
391 // It not only simplified, it simplified to the select condition. Replace
392 // it with 'true'.
393 TCmp = getTrue(Cond->getType());
394 } else if (!TCmp) {
395 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
396 // condition then we can replace it with 'true'. Otherwise give up.
397 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000398 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000399 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000400 }
401
Duncan Sands3d5692a2011-10-30 19:56:36 +0000402 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000403 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000404 if (FCmp == Cond) {
405 // It not only simplified, it simplified to the select condition. Replace
406 // it with 'false'.
407 FCmp = getFalse(Cond->getType());
408 } else if (!FCmp) {
409 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
410 // condition then we can replace it with 'false'. Otherwise give up.
411 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000412 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000413 FCmp = getFalse(Cond->getType());
414 }
415
416 // If both sides simplified to the same value, then use it as the result of
417 // the original comparison.
418 if (TCmp == FCmp)
419 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000420
421 // The remaining cases only make sense if the select condition has the same
422 // type as the result of the comparison, so bail out if this is not so.
423 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000424 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000425 // If the false value simplified to false, then the result of the compare
426 // is equal to "Cond && TCmp". This also catches the case when the false
427 // value simplified to false and the true value to true, returning "Cond".
428 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000429 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000430 return V;
431 // If the true value simplified to true, then the result of the compare
432 // is equal to "Cond || FCmp".
433 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000434 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000435 return V;
436 // Finally, if the false value simplified to true and the true value to
437 // false, then the result of the compare is equal to "!Cond".
438 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
439 if (Value *V =
440 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000441 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000442 return V;
443
Craig Topper9f008862014-04-15 04:59:12 +0000444 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000445}
446
Sanjay Patel472cc782016-01-11 22:14:42 +0000447/// In the case of a binary operation with an operand that is a PHI instruction,
448/// try to simplify the binop by seeing whether evaluating it on the incoming
449/// phi values yields the same result for every value. If so returns the common
450/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000451static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000452 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000453 // Recursion is always used, so bail out at once if we already hit the limit.
454 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000455 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000456
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000457 PHINode *PI;
458 if (isa<PHINode>(LHS)) {
459 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000460 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000461 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000462 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000463 } else {
464 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
465 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000466 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000467 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000468 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000469 }
470
471 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000472 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000473 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000474 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000475 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000476 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000477 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
478 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000479 // If the operation failed to simplify, or simplified to a different value
480 // to previously, then give up.
481 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000482 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000483 CommonValue = V;
484 }
485
486 return CommonValue;
487}
488
Sanjay Patel472cc782016-01-11 22:14:42 +0000489/// In the case of a comparison with a PHI instruction, try to simplify the
490/// comparison by seeing whether comparing with all of the incoming phi values
491/// yields the same result every time. If so returns the common result,
492/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000493static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000494 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000495 // Recursion is always used, so bail out at once if we already hit the limit.
496 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000497 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000498
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000499 // Make sure the phi is on the LHS.
500 if (!isa<PHINode>(LHS)) {
501 std::swap(LHS, RHS);
502 Pred = CmpInst::getSwappedPredicate(Pred);
503 }
504 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
505 PHINode *PI = cast<PHINode>(LHS);
506
Duncan Sands5ffc2982010-11-16 12:16:38 +0000507 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000508 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000509 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000510
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000511 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000512 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000513 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000514 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000515 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000516 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000517 // If the operation failed to simplify, or simplified to a different value
518 // to previously, then give up.
519 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000520 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000521 CommonValue = V;
522 }
523
524 return CommonValue;
525}
526
Sanjay Patel472cc782016-01-11 22:14:42 +0000527/// Given operands for an Add, see if we can fold the result.
528/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000529static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000530 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000531 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000532 if (Constant *CRHS = dyn_cast<Constant>(Op1))
533 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000534
Chris Lattner3d9823b2009-11-27 17:42:22 +0000535 // Canonicalize the constant to the RHS.
536 std::swap(Op0, Op1);
537 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000538
Duncan Sands0a2c41682010-12-15 14:07:39 +0000539 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000540 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000541 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000542
Duncan Sands0a2c41682010-12-15 14:07:39 +0000543 // X + 0 -> X
544 if (match(Op1, m_Zero()))
545 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000546
Duncan Sands0a2c41682010-12-15 14:07:39 +0000547 // X + (Y - X) -> Y
548 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000549 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000550 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000551 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
552 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000553 return Y;
554
555 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000556 if (match(Op0, m_Not(m_Specific(Op1))) ||
557 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000558 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000559
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000560 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000561 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000562 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000563 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000564
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000565 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000566 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000567 MaxRecurse))
568 return V;
569
Duncan Sandsb238de02010-11-19 09:20:39 +0000570 // Threading Add over selects and phi nodes is pointless, so don't bother.
571 // Threading over the select in "A + select(cond, B, C)" means evaluating
572 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
573 // only if B and C are equal. If B and C are equal then (since we assume
574 // that operands have already been simplified) "select(cond, B, C)" should
575 // have been simplified to the common value of B and C already. Analysing
576 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
577 // for threading over phi nodes.
578
Craig Topper9f008862014-04-15 04:59:12 +0000579 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000580}
581
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000582Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000583 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000584 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000585 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
587 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000588}
589
Chandler Carrutha0796552012-03-12 11:19:31 +0000590/// \brief Compute the base pointer and cumulative constant offsets for V.
591///
592/// This strips all constant offsets off of V, leaving it the base pointer, and
593/// accumulates the total constant offset applied in the returned constant. It
594/// returns 0 if V is not a pointer, and returns the constant '0' if there are
595/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000596///
597/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
599/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000600static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000601 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000602 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000603
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000605 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000606
607 // Even though we don't look through PHI nodes, we could be called on an
608 // instruction in an unreachable block, which may be on a cycle.
609 SmallPtrSet<Value *, 4> Visited;
610 Visited.insert(V);
611 do {
612 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000613 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000614 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000615 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000616 V = GEP->getPointerOperand();
617 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000618 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000619 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000620 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000621 break;
622 V = GA->getAliasee();
623 } else {
624 break;
625 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000626 assert(V->getType()->getScalarType()->isPointerTy() &&
627 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000628 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000629
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000630 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
631 if (V->getType()->isVectorTy())
632 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
633 OffsetIntPtr);
634 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000635}
636
637/// \brief Compute the constant difference between two pointer values.
638/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000639static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
640 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000641 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
642 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000643
644 // If LHS and RHS are not related via constant offsets to the same base
645 // value, there is nothing we can do here.
646 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000647 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000648
649 // Otherwise, the difference of LHS - RHS can be computed as:
650 // LHS - RHS
651 // = (LHSOffset + Base) - (RHSOffset + Base)
652 // = LHSOffset - RHSOffset
653 return ConstantExpr::getSub(LHSOffset, RHSOffset);
654}
655
Sanjay Patel472cc782016-01-11 22:14:42 +0000656/// Given operands for a Sub, see if we can fold the result.
657/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000658static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000659 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000660 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000661 if (Constant *CRHS = dyn_cast<Constant>(Op1))
662 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000663
664 // X - undef -> undef
665 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000666 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000667 return UndefValue::get(Op0->getType());
668
669 // X - 0 -> X
670 if (match(Op1, m_Zero()))
671 return Op0;
672
673 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000674 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000675 return Constant::getNullValue(Op0->getType());
676
David Majnemer4efa9ff2014-11-22 07:15:16 +0000677 // 0 - X -> 0 if the sub is NUW.
678 if (isNUW && match(Op0, m_Zero()))
679 return Op0;
David Majnemercd4fbcd2014-07-31 04:49:18 +0000680
Duncan Sands99589d02011-01-18 11:50:19 +0000681 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
682 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000683 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000684 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
685 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000686 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000687 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000688 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000689 // It does, we successfully reassociated!
690 ++NumReassoc;
691 return W;
692 }
693 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000694 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000695 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000696 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000697 // It does, we successfully reassociated!
698 ++NumReassoc;
699 return W;
700 }
701 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000702
Duncan Sands99589d02011-01-18 11:50:19 +0000703 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
704 // For example, X - (X + 1) -> -1
705 X = Op0;
706 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
707 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000708 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000709 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000710 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000711 // It does, we successfully reassociated!
712 ++NumReassoc;
713 return W;
714 }
715 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000716 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000717 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000718 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000719 // It does, we successfully reassociated!
720 ++NumReassoc;
721 return W;
722 }
723 }
724
725 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
726 // For example, X - (X - Y) -> Y.
727 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000728 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
729 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000730 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000731 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000732 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000733 // It does, we successfully reassociated!
734 ++NumReassoc;
735 return W;
736 }
737
Duncan Sands395ac42d2012-03-13 14:07:05 +0000738 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
739 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
740 match(Op1, m_Trunc(m_Value(Y))))
741 if (X->getType() == Y->getType())
742 // See if "V === X - Y" simplifies.
743 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
744 // It does! Now see if "trunc V" simplifies.
745 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
746 // It does, return the simplified "trunc V".
747 return W;
748
749 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000750 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000751 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000752 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000753 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
754
Duncan Sands99589d02011-01-18 11:50:19 +0000755 // i1 sub -> xor.
756 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000757 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000758 return V;
759
Duncan Sands0a2c41682010-12-15 14:07:39 +0000760 // Threading Sub over selects and phi nodes is pointless, so don't bother.
761 // Threading over the select in "A - select(cond, B, C)" means evaluating
762 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
763 // only if B and C are equal. If B and C are equal then (since we assume
764 // that operands have already been simplified) "select(cond, B, C)" should
765 // have been simplified to the common value of B and C already. Analysing
766 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
767 // for threading over phi nodes.
768
Craig Topper9f008862014-04-15 04:59:12 +0000769 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000770}
771
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000772Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000773 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000774 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000775 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000776 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
777 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000778}
779
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000780/// Given operands for an FAdd, see if we can fold the result. If not, this
781/// returns null.
782static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
783 const Query &Q, unsigned MaxRecurse) {
784 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000785 if (Constant *CRHS = dyn_cast<Constant>(Op1))
786 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000787
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()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000798 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000799 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)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000824 if (Constant *CRHS = dyn_cast<Constant>(Op1))
825 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000826 }
827
828 // fsub X, 0 ==> X
829 if (match(Op1, m_Zero()))
830 return Op0;
831
832 // fsub X, -0 ==> X, when we know X is not -0
833 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000834 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000835 return Op0;
836
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000837 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000838 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000839 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
840 return X;
841
842 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000843 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000844 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
845 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000846
Benjamin Kramer228680d2015-06-14 21:01:20 +0000847 // fsub nnan x, x ==> 0.0
848 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000849 return Constant::getNullValue(Op0->getType());
850
Craig Topper9f008862014-04-15 04:59:12 +0000851 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000852}
853
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000854/// Given the operands for an FMul, see if we can fold the result
855static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
856 FastMathFlags FMF,
857 const Query &Q,
858 unsigned MaxRecurse) {
859 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000860 if (Constant *CRHS = dyn_cast<Constant>(Op1))
861 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000862
863 // Canonicalize the constant to the RHS.
864 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000865 }
866
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000867 // fmul X, 1.0 ==> X
868 if (match(Op1, m_FPOne()))
869 return Op0;
870
871 // fmul nnan nsz X, 0 ==> 0
872 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
873 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000874
Craig Topper9f008862014-04-15 04:59:12 +0000875 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000876}
877
Sanjay Patel472cc782016-01-11 22:14:42 +0000878/// Given operands for a Mul, see if we can fold the result.
879/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000880static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
881 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000882 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000883 if (Constant *CRHS = dyn_cast<Constant>(Op1))
884 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000885
886 // Canonicalize the constant to the RHS.
887 std::swap(Op0, Op1);
888 }
889
890 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000891 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000892 return Constant::getNullValue(Op0->getType());
893
894 // X * 0 -> 0
895 if (match(Op1, m_Zero()))
896 return Op1;
897
898 // X * 1 -> X
899 if (match(Op1, m_One()))
900 return Op0;
901
Duncan Sandsb67edc62011-01-30 18:03:50 +0000902 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000903 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000904 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
905 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
906 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000907
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000908 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000909 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000910 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000911 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000912
913 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000914 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000915 MaxRecurse))
916 return V;
917
918 // Mul distributes over Add. Try some generic simplifications based on this.
919 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000920 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000921 return V;
922
923 // If the operation is with the result of a select instruction, check whether
924 // operating on either branch of the select always yields the same value.
925 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000926 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000927 MaxRecurse))
928 return V;
929
930 // If the operation is with the result of a phi instruction, check whether
931 // operating on all incoming values of the phi always yields the same value.
932 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000933 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000934 MaxRecurse))
935 return V;
936
Craig Topper9f008862014-04-15 04:59:12 +0000937 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000938}
939
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000940Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000941 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000942 const TargetLibraryInfo *TLI,
943 const DominatorTree *DT, AssumptionCache *AC,
944 const Instruction *CxtI) {
945 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000946 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000947}
948
949Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000950 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000951 const TargetLibraryInfo *TLI,
952 const DominatorTree *DT, AssumptionCache *AC,
953 const Instruction *CxtI) {
954 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000955 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000956}
957
Chandler Carruth66b31302015-01-04 12:03:27 +0000958Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000959 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000960 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000961 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000962 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000963 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000964 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000965}
966
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000967Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000968 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000969 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000970 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000971 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000972 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000973}
974
Sanjay Patel472cc782016-01-11 22:14:42 +0000975/// Given operands for an SDiv or UDiv, see if we can fold the result.
976/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +0000977static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000978 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000979 if (Constant *C0 = dyn_cast<Constant>(Op0))
980 if (Constant *C1 = dyn_cast<Constant>(Op1))
981 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +0000982
Duncan Sands65995fa2011-01-28 18:50:50 +0000983 bool isSigned = Opcode == Instruction::SDiv;
984
Duncan Sands771e82a2011-01-28 16:51:11 +0000985 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000986 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000987 return Op1;
988
David Majnemer71dc8fb2014-12-10 07:52:18 +0000989 // X / 0 -> undef, we don't need to preserve faults!
990 if (match(Op1, m_Zero()))
991 return UndefValue::get(Op1->getType());
992
Duncan Sands771e82a2011-01-28 16:51:11 +0000993 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000994 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000995 return Constant::getNullValue(Op0->getType());
996
997 // 0 / X -> 0, we don't need to preserve faults!
998 if (match(Op0, m_Zero()))
999 return Op0;
1000
1001 // X / 1 -> X
1002 if (match(Op1, m_One()))
1003 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001004
1005 if (Op0->getType()->isIntegerTy(1))
1006 // It can't be division by zero, hence it must be division by one.
1007 return Op0;
1008
1009 // X / X -> 1
1010 if (Op0 == Op1)
1011 return ConstantInt::get(Op0->getType(), 1);
1012
1013 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001014 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001015 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1016 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001017 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001018 // If the Mul knows it does not overflow, then we are good to go.
1019 if ((isSigned && Mul->hasNoSignedWrap()) ||
1020 (!isSigned && Mul->hasNoUnsignedWrap()))
1021 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001022 // If X has the form X = A / Y then X * Y cannot overflow.
1023 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1024 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1025 return X;
1026 }
1027
Duncan Sands65995fa2011-01-28 18:50:50 +00001028 // (X rem Y) / Y -> 0
1029 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1030 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1031 return Constant::getNullValue(Op0->getType());
1032
David Majnemercb9d5962014-10-11 10:20:01 +00001033 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1034 ConstantInt *C1, *C2;
1035 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1036 match(Op1, m_ConstantInt(C2))) {
1037 bool Overflow;
1038 C1->getValue().umul_ov(C2->getValue(), Overflow);
1039 if (Overflow)
1040 return Constant::getNullValue(Op0->getType());
1041 }
1042
Duncan Sands65995fa2011-01-28 18:50:50 +00001043 // If the operation is with the result of a select instruction, check whether
1044 // operating on either branch of the select always yields the same value.
1045 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001046 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001047 return V;
1048
1049 // If the operation is with the result of a phi instruction, check whether
1050 // operating on all incoming values of the phi always yields the same value.
1051 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001052 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001053 return V;
1054
Craig Topper9f008862014-04-15 04:59:12 +00001055 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001056}
1057
Sanjay Patel472cc782016-01-11 22:14:42 +00001058/// Given operands for an SDiv, see if we can fold the result.
1059/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001060static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1061 unsigned MaxRecurse) {
1062 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001063 return V;
1064
Craig Topper9f008862014-04-15 04:59:12 +00001065 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001066}
1067
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001068Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001069 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001070 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001071 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001072 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001073 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001074}
1075
Sanjay Patel472cc782016-01-11 22:14:42 +00001076/// Given operands for a UDiv, see if we can fold the result.
1077/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001078static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1079 unsigned MaxRecurse) {
1080 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001081 return V;
1082
Craig Topper9f008862014-04-15 04:59:12 +00001083 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001084}
1085
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001086Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001087 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001088 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001089 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001090 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001091 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001092}
1093
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001094static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1095 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001096 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001097 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001098 return Op0;
1099
1100 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001101 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001102 return Op1;
1103
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001104 // 0 / X -> 0
1105 // Requires that NaNs are off (X could be zero) and signed zeroes are
1106 // ignored (X could be positive or negative, so the output sign is unknown).
1107 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1108 return Op0;
1109
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001110 if (FMF.noNaNs()) {
1111 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001112 if (Op0 == Op1)
1113 return ConstantFP::get(Op0->getType(), 1.0);
1114
1115 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001116 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001117 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1118 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1119 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1120 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1121 BinaryOperator::getFNegArgument(Op1) == Op0))
1122 return ConstantFP::get(Op0->getType(), -1.0);
1123 }
1124
Craig Topper9f008862014-04-15 04:59:12 +00001125 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001126}
1127
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001128Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001129 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001130 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001131 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001132 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001133 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001134 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001135}
1136
Sanjay Patel472cc782016-01-11 22:14:42 +00001137/// Given operands for an SRem or URem, see if we can fold the result.
1138/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001139static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001140 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001141 if (Constant *C0 = dyn_cast<Constant>(Op0))
1142 if (Constant *C1 = dyn_cast<Constant>(Op1))
1143 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001144
Duncan Sandsa3e36992011-05-02 16:27:02 +00001145 // X % undef -> undef
1146 if (match(Op1, m_Undef()))
1147 return Op1;
1148
1149 // undef % X -> 0
1150 if (match(Op0, m_Undef()))
1151 return Constant::getNullValue(Op0->getType());
1152
1153 // 0 % X -> 0, we don't need to preserve faults!
1154 if (match(Op0, m_Zero()))
1155 return Op0;
1156
1157 // X % 0 -> undef, we don't need to preserve faults!
1158 if (match(Op1, m_Zero()))
1159 return UndefValue::get(Op0->getType());
1160
1161 // X % 1 -> 0
1162 if (match(Op1, m_One()))
1163 return Constant::getNullValue(Op0->getType());
1164
1165 if (Op0->getType()->isIntegerTy(1))
1166 // It can't be remainder by zero, hence it must be remainder by one.
1167 return Constant::getNullValue(Op0->getType());
1168
1169 // X % X -> 0
1170 if (Op0 == Op1)
1171 return Constant::getNullValue(Op0->getType());
1172
David Majnemerb435a422014-09-17 04:16:35 +00001173 // (X % Y) % Y -> X % Y
1174 if ((Opcode == Instruction::SRem &&
1175 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1176 (Opcode == Instruction::URem &&
1177 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001178 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001179
Duncan Sandsa3e36992011-05-02 16:27:02 +00001180 // If the operation is with the result of a select instruction, check whether
1181 // operating on either branch of the select always yields the same value.
1182 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001183 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001184 return V;
1185
1186 // If the operation is with the result of a phi instruction, check whether
1187 // operating on all incoming values of the phi always yields the same value.
1188 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001189 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001190 return V;
1191
Craig Topper9f008862014-04-15 04:59:12 +00001192 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001193}
1194
Sanjay Patel472cc782016-01-11 22:14:42 +00001195/// Given operands for an SRem, see if we can fold the result.
1196/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001197static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1198 unsigned MaxRecurse) {
1199 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001200 return V;
1201
Craig Topper9f008862014-04-15 04:59:12 +00001202 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001203}
1204
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001205Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001206 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001207 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001208 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001209 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001210 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001211}
1212
Sanjay Patel472cc782016-01-11 22:14:42 +00001213/// Given operands for a URem, see if we can fold the result.
1214/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001215static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001216 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001217 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001218 return V;
1219
Craig Topper9f008862014-04-15 04:59:12 +00001220 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001221}
1222
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001223Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001224 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001225 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001226 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001227 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001228 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001229}
1230
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001231static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1232 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001233 // undef % X -> undef (the undef could be a snan).
1234 if (match(Op0, m_Undef()))
1235 return Op0;
1236
1237 // X % undef -> undef
1238 if (match(Op1, m_Undef()))
1239 return Op1;
1240
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001241 // 0 % X -> 0
1242 // Requires that NaNs are off (X could be zero) and signed zeroes are
1243 // ignored (X could be positive or negative, so the output sign is unknown).
1244 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1245 return Op0;
1246
Craig Topper9f008862014-04-15 04:59:12 +00001247 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001248}
1249
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001250Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001251 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001252 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001253 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001254 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001255 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001256 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001257}
1258
Sanjay Patel472cc782016-01-11 22:14:42 +00001259/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001260static bool isUndefShift(Value *Amount) {
1261 Constant *C = dyn_cast<Constant>(Amount);
1262 if (!C)
1263 return false;
1264
1265 // X shift by undef -> undef because it may shift by the bitwidth.
1266 if (isa<UndefValue>(C))
1267 return true;
1268
1269 // Shifting by the bitwidth or more is undefined.
1270 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1271 if (CI->getValue().getLimitedValue() >=
1272 CI->getType()->getScalarSizeInBits())
1273 return true;
1274
1275 // If all lanes of a vector shift are undefined the whole shift is.
1276 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1277 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1278 if (!isUndefShift(C->getAggregateElement(I)))
1279 return false;
1280 return true;
1281 }
1282
1283 return false;
1284}
1285
Sanjay Patel472cc782016-01-11 22:14:42 +00001286/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1287/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001288static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001289 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001290 if (Constant *C0 = dyn_cast<Constant>(Op0))
1291 if (Constant *C1 = dyn_cast<Constant>(Op1))
1292 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001293
Duncan Sands571fd9a2011-01-14 14:44:12 +00001294 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001295 if (match(Op0, m_Zero()))
1296 return Op0;
1297
Duncan Sands571fd9a2011-01-14 14:44:12 +00001298 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001299 if (match(Op1, m_Zero()))
1300 return Op0;
1301
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001302 // Fold undefined shifts.
1303 if (isUndefShift(Op1))
1304 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001305
Duncan Sands571fd9a2011-01-14 14:44:12 +00001306 // If the operation is with the result of a select instruction, check whether
1307 // operating on either branch of the select always yields the same value.
1308 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001309 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001310 return V;
1311
1312 // If the operation is with the result of a phi instruction, check whether
1313 // operating on all incoming values of the phi always yields the same value.
1314 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001315 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001316 return V;
1317
Sanjay Patel6786bc52016-05-10 20:46:54 +00001318 // If any bits in the shift amount make that value greater than or equal to
1319 // the number of bits in the type, the shift is undefined.
1320 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1321 APInt KnownZero(BitWidth, 0);
1322 APInt KnownOne(BitWidth, 0);
1323 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1324 if (KnownOne.getLimitedValue() >= BitWidth)
1325 return UndefValue::get(Op0->getType());
1326
1327 // If all valid bits in the shift amount are known zero, the first operand is
1328 // unchanged.
1329 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1330 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1331 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1332 return Op0;
1333
Craig Topper9f008862014-04-15 04:59:12 +00001334 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001335}
1336
David Majnemerbf7550e2014-11-05 00:59:59 +00001337/// \brief Given operands for an Shl, LShr or AShr, see if we can
1338/// fold the result. If not, this returns null.
1339static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1340 bool isExact, const Query &Q,
1341 unsigned MaxRecurse) {
1342 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1343 return V;
1344
1345 // X >> X -> 0
1346 if (Op0 == Op1)
1347 return Constant::getNullValue(Op0->getType());
1348
David Majnemer65c52ae2014-12-17 01:54:33 +00001349 // undef >> X -> 0
1350 // undef >> X -> undef (if it's exact)
1351 if (match(Op0, m_Undef()))
1352 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1353
David Majnemerbf7550e2014-11-05 00:59:59 +00001354 // The low bit cannot be shifted out of an exact shift if it is set.
1355 if (isExact) {
1356 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1357 APInt Op0KnownZero(BitWidth, 0);
1358 APInt Op0KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00001359 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1360 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001361 if (Op0KnownOne[0])
1362 return Op0;
1363 }
1364
1365 return nullptr;
1366}
1367
Sanjay Patel472cc782016-01-11 22:14:42 +00001368/// Given operands for an Shl, see if we can fold the result.
1369/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001370static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001371 const Query &Q, unsigned MaxRecurse) {
1372 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001373 return V;
1374
1375 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001376 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001377 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001378 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001379
Chris Lattner9e4aa022011-02-09 17:15:04 +00001380 // (X >> A) << A -> X
1381 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001382 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001383 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001384 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001385}
1386
Chris Lattner9e4aa022011-02-09 17:15:04 +00001387Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001388 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001389 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001390 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001391 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001392 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001393}
1394
Sanjay Patel472cc782016-01-11 22:14:42 +00001395/// Given operands for an LShr, see if we can fold the result.
1396/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001397static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001398 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001399 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1400 MaxRecurse))
1401 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001402
Chris Lattner9e4aa022011-02-09 17:15:04 +00001403 // (X << A) >> A -> X
1404 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001405 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001406 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001407
Craig Topper9f008862014-04-15 04:59:12 +00001408 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001409}
1410
Chris Lattner9e4aa022011-02-09 17:15:04 +00001411Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001412 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001413 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001414 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001415 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001416 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001417 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001418}
1419
Sanjay Patel472cc782016-01-11 22:14:42 +00001420/// Given operands for an AShr, see if we can fold the result.
1421/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001422static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001423 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001424 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1425 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001426 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001427
1428 // all ones >>a X -> all ones
1429 if (match(Op0, m_AllOnes()))
1430 return Op0;
1431
Chris Lattner9e4aa022011-02-09 17:15:04 +00001432 // (X << A) >> A -> X
1433 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001434 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001435 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001436
Suyog Sarda68862412014-07-17 06:28:15 +00001437 // Arithmetic shifting an all-sign-bit value is a no-op.
Chandler Carruth66b31302015-01-04 12:03:27 +00001438 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001439 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1440 return Op0;
1441
Craig Topper9f008862014-04-15 04:59:12 +00001442 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001443}
1444
Chris Lattner9e4aa022011-02-09 17:15:04 +00001445Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001446 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001447 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001448 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001449 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001450 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001451 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001452}
1453
David Majnemer1af36e52014-12-06 10:51:40 +00001454static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1455 ICmpInst *UnsignedICmp, bool IsAnd) {
1456 Value *X, *Y;
1457
1458 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001459 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1460 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001461 return nullptr;
1462
1463 ICmpInst::Predicate UnsignedPred;
1464 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1465 ICmpInst::isUnsigned(UnsignedPred))
1466 ;
1467 else if (match(UnsignedICmp,
1468 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1469 ICmpInst::isUnsigned(UnsignedPred))
1470 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1471 else
1472 return nullptr;
1473
1474 // X < Y && Y != 0 --> X < Y
1475 // X < Y || Y != 0 --> Y != 0
1476 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1477 return IsAnd ? UnsignedICmp : ZeroICmp;
1478
1479 // X >= Y || Y != 0 --> true
1480 // X >= Y || Y == 0 --> X >= Y
1481 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1482 if (EqPred == ICmpInst::ICMP_NE)
1483 return getTrue(UnsignedICmp->getType());
1484 return UnsignedICmp;
1485 }
1486
David Majnemerd5b3aa42014-12-08 18:30:43 +00001487 // X < Y && Y == 0 --> false
1488 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1489 IsAnd)
1490 return getFalse(UnsignedICmp->getType());
1491
David Majnemer1af36e52014-12-06 10:51:40 +00001492 return nullptr;
1493}
1494
Sanjay Patel472cc782016-01-11 22:14:42 +00001495/// Simplify (and (icmp ...) (icmp ...)) to true when we can tell that the range
1496/// of possible values cannot be satisfied.
David Majnemera315bd82014-09-15 08:15:28 +00001497static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1498 ICmpInst::Predicate Pred0, Pred1;
1499 ConstantInt *CI1, *CI2;
1500 Value *V;
David Majnemer1af36e52014-12-06 10:51:40 +00001501
1502 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1503 return X;
1504
David Majnemera315bd82014-09-15 08:15:28 +00001505 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1506 m_ConstantInt(CI2))))
1507 return nullptr;
1508
1509 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1510 return nullptr;
1511
1512 Type *ITy = Op0->getType();
1513
1514 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1515 bool isNSW = AddInst->hasNoSignedWrap();
1516 bool isNUW = AddInst->hasNoUnsignedWrap();
1517
1518 const APInt &CI1V = CI1->getValue();
1519 const APInt &CI2V = CI2->getValue();
1520 const APInt Delta = CI2V - CI1V;
1521 if (CI1V.isStrictlyPositive()) {
1522 if (Delta == 2) {
1523 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1524 return getFalse(ITy);
1525 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1526 return getFalse(ITy);
1527 }
1528 if (Delta == 1) {
1529 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1530 return getFalse(ITy);
1531 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1532 return getFalse(ITy);
1533 }
1534 }
1535 if (CI1V.getBoolValue() && isNUW) {
1536 if (Delta == 2)
1537 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1538 return getFalse(ITy);
1539 if (Delta == 1)
1540 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1541 return getFalse(ITy);
1542 }
1543
1544 return nullptr;
1545}
1546
Sanjay Patel472cc782016-01-11 22:14:42 +00001547/// Given operands for an And, see if we can fold the result.
1548/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001549static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001550 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001551 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001552 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1553 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001554
Chris Lattnera71e9d62009-11-10 00:55:12 +00001555 // Canonicalize the constant to the RHS.
1556 std::swap(Op0, Op1);
1557 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001558
Chris Lattnera71e9d62009-11-10 00:55:12 +00001559 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001560 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001561 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001562
Chris Lattnera71e9d62009-11-10 00:55:12 +00001563 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001564 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001565 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001566
Duncan Sandsc89ac072010-11-17 18:52:15 +00001567 // X & 0 = 0
1568 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001569 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001570
Duncan Sandsc89ac072010-11-17 18:52:15 +00001571 // X & -1 = X
1572 if (match(Op1, m_AllOnes()))
1573 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001574
Chris Lattnera71e9d62009-11-10 00:55:12 +00001575 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001576 if (match(Op0, m_Not(m_Specific(Op1))) ||
1577 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001578 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001579
Chris Lattnera71e9d62009-11-10 00:55:12 +00001580 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001581 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001582 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001583 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001584 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001585
Chris Lattnera71e9d62009-11-10 00:55:12 +00001586 // A & (A | ?) = A
1587 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001588 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001589 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001590
Duncan Sandsba286d72011-10-26 20:55:21 +00001591 // A & (-A) = A if A is a power of two or zero.
1592 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1593 match(Op1, m_Neg(m_Specific(Op0)))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001594 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1595 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001596 return Op0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001597 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1598 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001599 return Op1;
1600 }
1601
David Majnemera315bd82014-09-15 08:15:28 +00001602 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1603 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1604 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1605 return V;
1606 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1607 return V;
1608 }
1609 }
1610
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001611 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001612 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1613 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001614 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001615
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001616 // And distributes over Or. Try some generic simplifications based on this.
1617 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001618 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001619 return V;
1620
1621 // And distributes over Xor. Try some generic simplifications based on this.
1622 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001623 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001624 return V;
1625
Duncan Sandsb0579e92010-11-10 13:00:08 +00001626 // If the operation is with the result of a select instruction, check whether
1627 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001628 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001629 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1630 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001631 return V;
1632
1633 // If the operation is with the result of a phi instruction, check whether
1634 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001635 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001636 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001637 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001638 return V;
1639
Craig Topper9f008862014-04-15 04:59:12 +00001640 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001641}
1642
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001643Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001644 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001645 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001646 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001647 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001648 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001649}
1650
Sanjay Patel472cc782016-01-11 22:14:42 +00001651/// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1652/// contains all possible values.
David Majnemera315bd82014-09-15 08:15:28 +00001653static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
1654 ICmpInst::Predicate Pred0, Pred1;
1655 ConstantInt *CI1, *CI2;
1656 Value *V;
David Majnemer1af36e52014-12-06 10:51:40 +00001657
1658 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1659 return X;
1660
David Majnemera315bd82014-09-15 08:15:28 +00001661 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_ConstantInt(CI1)),
1662 m_ConstantInt(CI2))))
1663 return nullptr;
1664
1665 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Specific(CI1))))
1666 return nullptr;
1667
1668 Type *ITy = Op0->getType();
1669
1670 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1671 bool isNSW = AddInst->hasNoSignedWrap();
1672 bool isNUW = AddInst->hasNoUnsignedWrap();
1673
1674 const APInt &CI1V = CI1->getValue();
1675 const APInt &CI2V = CI2->getValue();
1676 const APInt Delta = CI2V - CI1V;
1677 if (CI1V.isStrictlyPositive()) {
1678 if (Delta == 2) {
1679 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1680 return getTrue(ITy);
1681 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1682 return getTrue(ITy);
1683 }
1684 if (Delta == 1) {
1685 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1686 return getTrue(ITy);
1687 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1688 return getTrue(ITy);
1689 }
1690 }
1691 if (CI1V.getBoolValue() && isNUW) {
1692 if (Delta == 2)
1693 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1694 return getTrue(ITy);
1695 if (Delta == 1)
1696 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1697 return getTrue(ITy);
1698 }
1699
1700 return nullptr;
1701}
1702
Sanjay Patel472cc782016-01-11 22:14:42 +00001703/// Given operands for an Or, see if we can fold the result.
1704/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001705static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1706 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001707 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001708 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1709 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001710
Chris Lattnera71e9d62009-11-10 00:55:12 +00001711 // Canonicalize the constant to the RHS.
1712 std::swap(Op0, Op1);
1713 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001714
Chris Lattnera71e9d62009-11-10 00:55:12 +00001715 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001716 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001717 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001718
Chris Lattnera71e9d62009-11-10 00:55:12 +00001719 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001720 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001721 return Op0;
1722
Duncan Sandsc89ac072010-11-17 18:52:15 +00001723 // X | 0 = X
1724 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001725 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001726
Duncan Sandsc89ac072010-11-17 18:52:15 +00001727 // X | -1 = -1
1728 if (match(Op1, m_AllOnes()))
1729 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001730
Chris Lattnera71e9d62009-11-10 00:55:12 +00001731 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001732 if (match(Op0, m_Not(m_Specific(Op1))) ||
1733 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001734 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001735
Chris Lattnera71e9d62009-11-10 00:55:12 +00001736 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001737 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001738 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001739 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001740 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001741
Chris Lattnera71e9d62009-11-10 00:55:12 +00001742 // A | (A & ?) = A
1743 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001744 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001745 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001746
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001747 // ~(A & ?) | A = -1
1748 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1749 (A == Op1 || B == Op1))
1750 return Constant::getAllOnesValue(Op1->getType());
1751
1752 // A | ~(A & ?) = -1
1753 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1754 (A == Op0 || B == Op0))
1755 return Constant::getAllOnesValue(Op0->getType());
1756
David Majnemera315bd82014-09-15 08:15:28 +00001757 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1758 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1759 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1760 return V;
1761 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1762 return V;
1763 }
1764 }
1765
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001766 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001767 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1768 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001769 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001770
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001771 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001772 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1773 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001774 return V;
1775
Duncan Sandsb0579e92010-11-10 13:00:08 +00001776 // If the operation is with the result of a select instruction, check whether
1777 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001778 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001779 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001780 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001781 return V;
1782
Nick Lewycky8561a492014-06-19 03:51:46 +00001783 // (A & C)|(B & D)
1784 Value *C = nullptr, *D = nullptr;
1785 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1786 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1787 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1788 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1789 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1790 // (A & C1)|(B & C2)
1791 // If we have: ((V + N) & C1) | (V & C2)
1792 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1793 // replace with V+N.
1794 Value *V1, *V2;
1795 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1796 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1797 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001798 if (V1 == B &&
1799 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001800 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001801 if (V2 == B &&
1802 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001803 return A;
1804 }
1805 // Or commutes, try both ways.
1806 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1807 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1808 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001809 if (V1 == A &&
1810 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001811 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001812 if (V2 == A &&
1813 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001814 return B;
1815 }
1816 }
1817 }
1818
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001819 // If the operation is with the result of a phi instruction, check whether
1820 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001821 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001822 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001823 return V;
1824
Craig Topper9f008862014-04-15 04:59:12 +00001825 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001826}
1827
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001828Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001829 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001830 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001831 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001832 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001833 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001834}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001835
Sanjay Patel472cc782016-01-11 22:14:42 +00001836/// Given operands for a Xor, see if we can fold the result.
1837/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001838static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1839 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001840 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001841 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1842 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001843
1844 // Canonicalize the constant to the RHS.
1845 std::swap(Op0, Op1);
1846 }
1847
1848 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001849 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001850 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001851
1852 // A ^ 0 = A
1853 if (match(Op1, m_Zero()))
1854 return Op0;
1855
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001856 // A ^ A = 0
1857 if (Op0 == Op1)
1858 return Constant::getNullValue(Op0->getType());
1859
Duncan Sandsc89ac072010-11-17 18:52:15 +00001860 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001861 if (match(Op0, m_Not(m_Specific(Op1))) ||
1862 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001863 return Constant::getAllOnesValue(Op0->getType());
1864
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001865 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001866 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1867 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001868 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001869
Duncan Sandsb238de02010-11-19 09:20:39 +00001870 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1871 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1872 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1873 // only if B and C are equal. If B and C are equal then (since we assume
1874 // that operands have already been simplified) "select(cond, B, C)" should
1875 // have been simplified to the common value of B and C already. Analysing
1876 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1877 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001878
Craig Topper9f008862014-04-15 04:59:12 +00001879 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001880}
1881
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001882Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001883 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001884 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001885 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001886 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001887 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001888}
1889
Chris Lattner229907c2011-07-18 04:54:35 +00001890static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001891 return CmpInst::makeCmpResultType(Op->getType());
1892}
1893
Sanjay Patel472cc782016-01-11 22:14:42 +00001894/// Rummage around inside V looking for something equivalent to the comparison
1895/// "LHS Pred RHS". Return such a value if found, otherwise return null.
1896/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00001897static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1898 Value *LHS, Value *RHS) {
1899 SelectInst *SI = dyn_cast<SelectInst>(V);
1900 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001901 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001902 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1903 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001904 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001905 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1906 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1907 return Cmp;
1908 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1909 LHS == CmpRHS && RHS == CmpLHS)
1910 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001911 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001912}
1913
Dan Gohman9631d902013-02-01 00:49:06 +00001914// A significant optimization not implemented here is assuming that alloca
1915// addresses are not equal to incoming argument values. They don't *alias*,
1916// as we say, but that doesn't mean they aren't equal, so we take a
1917// conservative approach.
1918//
1919// This is inspired in part by C++11 5.10p1:
1920// "Two pointers of the same type compare equal if and only if they are both
1921// null, both point to the same function, or both represent the same
1922// address."
1923//
1924// This is pretty permissive.
1925//
1926// It's also partly due to C11 6.5.9p6:
1927// "Two pointers compare equal if and only if both are null pointers, both are
1928// pointers to the same object (including a pointer to an object and a
1929// subobject at its beginning) or function, both are pointers to one past the
1930// last element of the same array object, or one is a pointer to one past the
1931// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001932// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001933// object in the address space.)
1934//
1935// C11's version is more restrictive, however there's no reason why an argument
1936// couldn't be a one-past-the-end value for a stack object in the caller and be
1937// equal to the beginning of a stack object in the callee.
1938//
1939// If the C and C++ standards are ever made sufficiently restrictive in this
1940// area, it may be possible to update LLVM's semantics accordingly and reinstate
1941// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00001942static Constant *
1943computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1944 const DominatorTree *DT, CmpInst::Predicate Pred,
1945 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001946 // First, skip past any trivial no-ops.
1947 LHS = LHS->stripPointerCasts();
1948 RHS = RHS->stripPointerCasts();
1949
1950 // A non-null pointer is not equal to a null pointer.
Benjamin Kramerfd4777c2013-09-24 16:37:51 +00001951 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001952 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1953 return ConstantInt::get(GetCompareTy(LHS),
1954 !CmpInst::isTrueWhenEqual(Pred));
1955
Chandler Carruth8059c842012-03-25 21:28:14 +00001956 // We can only fold certain predicates on pointer comparisons.
1957 switch (Pred) {
1958 default:
Craig Topper9f008862014-04-15 04:59:12 +00001959 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001960
1961 // Equality comaprisons are easy to fold.
1962 case CmpInst::ICMP_EQ:
1963 case CmpInst::ICMP_NE:
1964 break;
1965
1966 // We can only handle unsigned relational comparisons because 'inbounds' on
1967 // a GEP only protects against unsigned wrapping.
1968 case CmpInst::ICMP_UGT:
1969 case CmpInst::ICMP_UGE:
1970 case CmpInst::ICMP_ULT:
1971 case CmpInst::ICMP_ULE:
1972 // However, we have to switch them to their signed variants to handle
1973 // negative indices from the base pointer.
1974 Pred = ICmpInst::getSignedPredicate(Pred);
1975 break;
1976 }
1977
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001978 // Strip off any constant offsets so that we can reason about them.
1979 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1980 // here and compare base addresses like AliasAnalysis does, however there are
1981 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1982 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1983 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00001984 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1985 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00001986
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001987 // If LHS and RHS are related via constant offsets to the same base
1988 // value, we can replace it with an icmp which just compares the offsets.
1989 if (LHS == RHS)
1990 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00001991
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001992 // Various optimizations for (in)equality comparisons.
1993 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1994 // Different non-empty allocations that exist at the same time have
1995 // different addresses (if the program can tell). Global variables always
1996 // exist, so they always exist during the lifetime of each other and all
1997 // allocas. Two different allocas usually have different addresses...
1998 //
1999 // However, if there's an @llvm.stackrestore dynamically in between two
2000 // allocas, they may have the same address. It's tempting to reduce the
2001 // scope of the problem by only looking at *static* allocas here. That would
2002 // cover the majority of allocas while significantly reducing the likelihood
2003 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2004 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2005 // an entry block. Also, if we have a block that's not attached to a
2006 // function, we can't tell if it's "static" under the current definition.
2007 // Theoretically, this problem could be fixed by creating a new kind of
2008 // instruction kind specifically for static allocas. Such a new instruction
2009 // could be required to be at the top of the entry block, thus preventing it
2010 // from being subject to a @llvm.stackrestore. Instcombine could even
2011 // convert regular allocas into these special allocas. It'd be nifty.
2012 // However, until then, this problem remains open.
2013 //
2014 // So, we'll assume that two non-empty allocas have different addresses
2015 // for now.
2016 //
2017 // With all that, if the offsets are within the bounds of their allocations
2018 // (and not one-past-the-end! so we can't use inbounds!), and their
2019 // allocations aren't the same, the pointers are not equal.
2020 //
2021 // Note that it's not necessary to check for LHS being a global variable
2022 // address, due to canonicalization and constant folding.
2023 if (isa<AllocaInst>(LHS) &&
2024 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002025 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2026 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002027 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002028 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002029 getObjectSize(LHS, LHSSize, DL, TLI) &&
2030 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002031 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2032 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002033 if (!LHSOffsetValue.isNegative() &&
2034 !RHSOffsetValue.isNegative() &&
2035 LHSOffsetValue.ult(LHSSize) &&
2036 RHSOffsetValue.ult(RHSSize)) {
2037 return ConstantInt::get(GetCompareTy(LHS),
2038 !CmpInst::isTrueWhenEqual(Pred));
2039 }
2040 }
2041
2042 // Repeat the above check but this time without depending on DataLayout
2043 // or being able to compute a precise size.
2044 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2045 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2046 LHSOffset->isNullValue() &&
2047 RHSOffset->isNullValue())
2048 return ConstantInt::get(GetCompareTy(LHS),
2049 !CmpInst::isTrueWhenEqual(Pred));
2050 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002051
2052 // Even if an non-inbounds GEP occurs along the path we can still optimize
2053 // equality comparisons concerning the result. We avoid walking the whole
2054 // chain again by starting where the last calls to
2055 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002056 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2057 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002058 if (LHS == RHS)
2059 return ConstantExpr::getICmp(Pred,
2060 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2061 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002062
2063 // If one side of the equality comparison must come from a noalias call
2064 // (meaning a system memory allocation function), and the other side must
2065 // come from a pointer that cannot overlap with dynamically-allocated
2066 // memory within the lifetime of the current function (allocas, byval
2067 // arguments, globals), then determine the comparison result here.
2068 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2069 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2070 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2071
2072 // Is the set of underlying objects all noalias calls?
2073 auto IsNAC = [](SmallVectorImpl<Value *> &Objects) {
Craig Topperb4b66d02015-11-29 04:37:14 +00002074 return std::all_of(Objects.begin(), Objects.end(), isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002075 };
2076
2077 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002078 // noalias calls. For allocas, we consider only static ones (dynamic
2079 // allocas might be transformed into calls to malloc not simultaneously
2080 // live with the compared-to allocation). For globals, we exclude symbols
2081 // that might be resolve lazily to symbols in another dynamically-loaded
2082 // library (and, thus, could be malloc'ed by the implementation).
Hal Finkelafcd8db2014-12-01 23:38:06 +00002083 auto IsAllocDisjoint = [](SmallVectorImpl<Value *> &Objects) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002084 return std::all_of(Objects.begin(), Objects.end(), [](Value *V) {
2085 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2086 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2087 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2088 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002089 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002090 !GV->isThreadLocal();
2091 if (const Argument *A = dyn_cast<Argument>(V))
2092 return A->hasByValAttr();
2093 return false;
2094 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002095 };
2096
2097 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2098 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2099 return ConstantInt::get(GetCompareTy(LHS),
2100 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002101
2102 // Fold comparisons for non-escaping pointer even if the allocation call
2103 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2104 // dynamic allocation call could be either of the operands.
2105 Value *MI = nullptr;
2106 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT, TLI))
2107 MI = LHS;
2108 else if (isAllocLikeFn(RHS, TLI) &&
2109 llvm::isKnownNonNullAt(LHS, CxtI, DT, TLI))
2110 MI = RHS;
2111 // FIXME: We should also fold the compare when the pointer escapes, but the
2112 // compare dominates the pointer escape
2113 if (MI && !PointerMayBeCaptured(MI, true, true))
2114 return ConstantInt::get(GetCompareTy(LHS),
2115 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002116 }
2117
2118 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002119 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002120}
Chris Lattner01990f02012-02-24 19:01:58 +00002121
Sanjay Patel472cc782016-01-11 22:14:42 +00002122/// Given operands for an ICmpInst, see if we can fold the result.
2123/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002124static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002125 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00002126 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002127 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00002128
Chris Lattnera71e9d62009-11-10 00:55:12 +00002129 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00002130 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002131 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002132
2133 // If we have a constant, make sure it is on the RHS.
2134 std::swap(LHS, RHS);
2135 Pred = CmpInst::getSwappedPredicate(Pred);
2136 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002137
Chris Lattner229907c2011-07-18 04:54:35 +00002138 Type *ITy = GetCompareTy(LHS); // The return type.
2139 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00002140
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002141 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00002142 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2143 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00002144 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002145 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00002146
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002147 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00002148 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002149 switch (Pred) {
2150 default: break;
2151 case ICmpInst::ICMP_EQ:
2152 // X == 1 -> X
2153 if (match(RHS, m_One()))
2154 return LHS;
2155 break;
2156 case ICmpInst::ICMP_NE:
2157 // X != 0 -> X
2158 if (match(RHS, m_Zero()))
2159 return LHS;
2160 break;
2161 case ICmpInst::ICMP_UGT:
2162 // X >u 0 -> X
2163 if (match(RHS, m_Zero()))
2164 return LHS;
2165 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002166 case ICmpInst::ICMP_UGE: {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002167 // X >=u 1 -> X
2168 if (match(RHS, m_One()))
2169 return LHS;
Chad Rosier41dd31f2016-04-20 19:15:26 +00002170 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002171 return getTrue(ITy);
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002172 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002173 }
2174 case ICmpInst::ICMP_SGE: {
Junmo Park53470fc2016-04-05 21:14:31 +00002175 /// For signed comparison, the values for an i1 are 0 and -1
Philip Reamesdbbd7792015-10-29 03:19:10 +00002176 /// respectively. This maps into a truth table of:
2177 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2178 /// 0 | 0 | 1 (0 >= 0) | 1
2179 /// 0 | 1 | 1 (0 >= -1) | 1
2180 /// 1 | 0 | 0 (-1 >= 0) | 0
2181 /// 1 | 1 | 1 (-1 >= -1) | 1
Chad Rosier41dd31f2016-04-20 19:15:26 +00002182 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reamesdbbd7792015-10-29 03:19:10 +00002183 return getTrue(ITy);
2184 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002185 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002186 case ICmpInst::ICMP_SLT:
2187 // X <s 0 -> X
2188 if (match(RHS, m_Zero()))
2189 return LHS;
2190 break;
2191 case ICmpInst::ICMP_SLE:
2192 // X <=s -1 -> X
2193 if (match(RHS, m_One()))
2194 return LHS;
2195 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002196 case ICmpInst::ICMP_ULE: {
Chad Rosier41dd31f2016-04-20 19:15:26 +00002197 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002198 return getTrue(ITy);
2199 break;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002200 }
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002201 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002202 }
2203
Duncan Sandsd3951082011-01-25 09:38:29 +00002204 // If we are comparing with zero then try hard since this is a common case.
2205 if (match(RHS, m_Zero())) {
2206 bool LHSKnownNonNegative, LHSKnownNegative;
2207 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002208 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00002209 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002210 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002211 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002212 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002213 case ICmpInst::ICMP_EQ:
2214 case ICmpInst::ICMP_ULE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002215 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002216 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002217 break;
2218 case ICmpInst::ICMP_NE:
2219 case ICmpInst::ICMP_UGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002220 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002221 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002222 break;
2223 case ICmpInst::ICMP_SLT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002224 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2225 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002226 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002227 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002228 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002229 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002230 break;
2231 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002232 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2233 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002234 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002235 return getTrue(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002236 if (LHSKnownNonNegative &&
2237 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002238 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002239 break;
2240 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002241 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2242 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002243 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002244 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002245 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002246 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002247 break;
2248 case ICmpInst::ICMP_SGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002249 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2250 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002251 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002252 return getFalse(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002253 if (LHSKnownNonNegative &&
2254 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002255 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002256 break;
2257 }
2258 }
2259
2260 // See if we are doing a comparison with a constant integer.
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002261 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002262 // Rule out tautological comparisons (eg., ult 0 or uge 0).
2263 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
2264 if (RHS_CR.isEmptySet())
2265 return ConstantInt::getFalse(CI->getContext());
2266 if (RHS_CR.isFullSet())
2267 return ConstantInt::getTrue(CI->getContext());
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002268
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002269 // Many binary operators with constant RHS have easy to compute constant
2270 // range. Use them to check whether the comparison is a tautology.
David Majnemer78910fc2014-05-16 17:14:03 +00002271 unsigned Width = CI->getBitWidth();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002272 APInt Lower = APInt(Width, 0);
2273 APInt Upper = APInt(Width, 0);
2274 ConstantInt *CI2;
2275 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2276 // 'urem x, CI2' produces [0, CI2).
2277 Upper = CI2->getValue();
2278 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2279 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2280 Upper = CI2->getValue().abs();
2281 Lower = (-Upper) + 1;
Duncan Sands92af0a82011-10-28 18:17:44 +00002282 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2283 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman0bae8b22011-11-08 21:08:02 +00002284 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002285 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2286 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2287 APInt NegOne = APInt::getAllOnesValue(Width);
2288 if (!CI2->isZero())
2289 Upper = NegOne.udiv(CI2->getValue()) + 1;
David Majnemerea8d5db2014-05-16 16:57:04 +00002290 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
David Majnemer651ed5e2014-07-04 00:23:39 +00002291 if (CI2->isMinSignedValue()) {
2292 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2293 Lower = CI2->getValue();
2294 Upper = Lower.lshr(1) + 1;
2295 } else {
2296 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2297 Upper = CI2->getValue().abs() + 1;
2298 Lower = (-Upper) + 1;
2299 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002300 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002301 APInt IntMin = APInt::getSignedMinValue(Width);
2302 APInt IntMax = APInt::getSignedMaxValue(Width);
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002303 const APInt &Val = CI2->getValue();
David Majnemeraf9180f2014-07-14 20:38:45 +00002304 if (Val.isAllOnesValue()) {
2305 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2306 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2307 Lower = IntMin + 1;
2308 Upper = IntMax + 1;
2309 } else if (Val.countLeadingZeros() < Width - 1) {
2310 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2311 // where CI2 != -1 and CI2 != 0 and CI2 != 1
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002312 Lower = IntMin.sdiv(Val);
David Majnemeraf9180f2014-07-14 20:38:45 +00002313 Upper = IntMax.sdiv(Val);
2314 if (Lower.sgt(Upper))
2315 std::swap(Lower, Upper);
2316 Upper = Upper + 1;
David Majnemer5ea4fc02014-07-14 19:49:57 +00002317 assert(Upper != Lower && "Upper part of range has wrapped!");
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002318 }
David Majnemerd6d16712014-08-27 18:03:46 +00002319 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2320 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2321 Lower = CI2->getValue();
2322 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2323 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2324 if (CI2->isNegative()) {
2325 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2326 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2327 Lower = CI2->getValue().shl(ShiftAmount);
2328 Upper = CI2->getValue() + 1;
2329 } else {
2330 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2331 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2332 Lower = CI2->getValue();
2333 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2334 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002335 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2336 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2337 APInt NegOne = APInt::getAllOnesValue(Width);
2338 if (CI2->getValue().ult(Width))
2339 Upper = NegOne.lshr(CI2->getValue()) + 1;
David Majnemer78910fc2014-05-16 17:14:03 +00002340 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2341 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2342 unsigned ShiftAmount = Width - 1;
2343 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2344 ShiftAmount = CI2->getValue().countTrailingZeros();
2345 Lower = CI2->getValue().lshr(ShiftAmount);
2346 Upper = CI2->getValue() + 1;
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002347 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2348 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2349 APInt IntMin = APInt::getSignedMinValue(Width);
2350 APInt IntMax = APInt::getSignedMaxValue(Width);
2351 if (CI2->getValue().ult(Width)) {
2352 Lower = IntMin.ashr(CI2->getValue());
2353 Upper = IntMax.ashr(CI2->getValue()) + 1;
2354 }
David Majnemer78910fc2014-05-16 17:14:03 +00002355 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2356 unsigned ShiftAmount = Width - 1;
2357 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2358 ShiftAmount = CI2->getValue().countTrailingZeros();
2359 if (CI2->isNegative()) {
2360 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2361 Lower = CI2->getValue();
2362 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2363 } else {
2364 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2365 Lower = CI2->getValue().ashr(ShiftAmount);
2366 Upper = CI2->getValue() + 1;
2367 }
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002368 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2369 // 'or x, CI2' produces [CI2, UINT_MAX].
2370 Lower = CI2->getValue();
2371 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2372 // 'and x, CI2' produces [0, CI2].
2373 Upper = CI2->getValue() + 1;
David Majnemer2df38cd2015-08-20 23:01:41 +00002374 } else if (match(LHS, m_NUWAdd(m_Value(), m_ConstantInt(CI2)))) {
2375 // 'add nuw x, CI2' produces [CI2, UINT_MAX].
2376 Lower = CI2->getValue();
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002377 }
Chen Li5cd6dee2015-09-23 17:58:44 +00002378
2379 ConstantRange LHS_CR = Lower != Upper ? ConstantRange(Lower, Upper)
2380 : ConstantRange(Width, true);
2381
2382 if (auto *I = dyn_cast<Instruction>(LHS))
2383 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002384 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
Chen Li5cd6dee2015-09-23 17:58:44 +00002385
2386 if (!LHS_CR.isFullSet()) {
Nick Lewycky3cec6f52011-03-04 07:00:57 +00002387 if (RHS_CR.contains(LHS_CR))
2388 return ConstantInt::getTrue(RHS->getContext());
2389 if (RHS_CR.inverse().contains(LHS_CR))
2390 return ConstantInt::getFalse(RHS->getContext());
2391 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002392 }
2393
Chen Li7452d952015-09-26 03:26:47 +00002394 // If both operands have range metadata, use the metadata
2395 // to simplify the comparison.
2396 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2397 auto RHS_Instr = dyn_cast<Instruction>(RHS);
2398 auto LHS_Instr = dyn_cast<Instruction>(LHS);
2399
2400 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2401 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002402 auto RHS_CR = getConstantRangeFromMetadata(
2403 *RHS_Instr->getMetadata(LLVMContext::MD_range));
2404 auto LHS_CR = getConstantRangeFromMetadata(
2405 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00002406
2407 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2408 if (Satisfied_CR.contains(LHS_CR))
2409 return ConstantInt::getTrue(RHS->getContext());
2410
2411 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2412 CmpInst::getInversePredicate(Pred), RHS_CR);
2413 if (InversedSatisfied_CR.contains(LHS_CR))
2414 return ConstantInt::getFalse(RHS->getContext());
2415 }
2416 }
2417
Duncan Sands8fb2c382011-01-20 13:21:55 +00002418 // Compare of cast, for example (zext X) != 0 -> X != 0
2419 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2420 Instruction *LI = cast<CastInst>(LHS);
2421 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002422 Type *SrcTy = SrcOp->getType();
2423 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002424
2425 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2426 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002427 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2428 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002429 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2430 // Transfer the cast to the constant.
2431 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2432 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002433 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002434 return V;
2435 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2436 if (RI->getOperand(0)->getType() == SrcTy)
2437 // Compare without the cast.
2438 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002439 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002440 return V;
2441 }
2442 }
2443
2444 if (isa<ZExtInst>(LHS)) {
2445 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2446 // same type.
2447 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2448 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2449 // Compare X and Y. Note that signed predicates become unsigned.
2450 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002451 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002452 MaxRecurse-1))
2453 return V;
2454 }
2455 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2456 // too. If not, then try to deduce the result of the comparison.
2457 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2458 // Compute the constant that would happen if we truncated to SrcTy then
2459 // reextended to DstTy.
2460 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2461 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2462
2463 // If the re-extended constant didn't change then this is effectively
2464 // also a case of comparing two zero-extended values.
2465 if (RExt == CI && MaxRecurse)
2466 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002467 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002468 return V;
2469
2470 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2471 // there. Use this to work out the result of the comparison.
2472 if (RExt != CI) {
2473 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002474 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002475 // LHS <u RHS.
2476 case ICmpInst::ICMP_EQ:
2477 case ICmpInst::ICMP_UGT:
2478 case ICmpInst::ICMP_UGE:
2479 return ConstantInt::getFalse(CI->getContext());
2480
2481 case ICmpInst::ICMP_NE:
2482 case ICmpInst::ICMP_ULT:
2483 case ICmpInst::ICMP_ULE:
2484 return ConstantInt::getTrue(CI->getContext());
2485
2486 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2487 // is non-negative then LHS <s RHS.
2488 case ICmpInst::ICMP_SGT:
2489 case ICmpInst::ICMP_SGE:
2490 return CI->getValue().isNegative() ?
2491 ConstantInt::getTrue(CI->getContext()) :
2492 ConstantInt::getFalse(CI->getContext());
2493
2494 case ICmpInst::ICMP_SLT:
2495 case ICmpInst::ICMP_SLE:
2496 return CI->getValue().isNegative() ?
2497 ConstantInt::getFalse(CI->getContext()) :
2498 ConstantInt::getTrue(CI->getContext());
2499 }
2500 }
2501 }
2502 }
2503
2504 if (isa<SExtInst>(LHS)) {
2505 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2506 // same type.
2507 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2508 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2509 // Compare X and Y. Note that the predicate does not change.
2510 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002511 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002512 return V;
2513 }
2514 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2515 // too. If not, then try to deduce the result of the comparison.
2516 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2517 // Compute the constant that would happen if we truncated to SrcTy then
2518 // reextended to DstTy.
2519 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2520 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2521
2522 // If the re-extended constant didn't change then this is effectively
2523 // also a case of comparing two sign-extended values.
2524 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002525 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002526 return V;
2527
2528 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2529 // bits there. Use this to work out the result of the comparison.
2530 if (RExt != CI) {
2531 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002532 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002533 case ICmpInst::ICMP_EQ:
2534 return ConstantInt::getFalse(CI->getContext());
2535 case ICmpInst::ICMP_NE:
2536 return ConstantInt::getTrue(CI->getContext());
2537
2538 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2539 // LHS >s RHS.
2540 case ICmpInst::ICMP_SGT:
2541 case ICmpInst::ICMP_SGE:
2542 return CI->getValue().isNegative() ?
2543 ConstantInt::getTrue(CI->getContext()) :
2544 ConstantInt::getFalse(CI->getContext());
2545 case ICmpInst::ICMP_SLT:
2546 case ICmpInst::ICMP_SLE:
2547 return CI->getValue().isNegative() ?
2548 ConstantInt::getFalse(CI->getContext()) :
2549 ConstantInt::getTrue(CI->getContext());
2550
2551 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2552 // LHS >u RHS.
2553 case ICmpInst::ICMP_UGT:
2554 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002555 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002556 if (MaxRecurse)
2557 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2558 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002559 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002560 return V;
2561 break;
2562 case ICmpInst::ICMP_ULT:
2563 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002564 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002565 if (MaxRecurse)
2566 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2567 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002568 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002569 return V;
2570 break;
2571 }
2572 }
2573 }
2574 }
2575 }
2576
James Molloy1d88d6f2015-10-22 13:18:42 +00002577 // icmp eq|ne X, Y -> false|true if X != Y
2578 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2579 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2580 LLVMContext &Ctx = LHS->getType()->getContext();
2581 return Pred == ICmpInst::ICMP_NE ?
2582 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2583 }
Junmo Park53470fc2016-04-05 21:14:31 +00002584
Duncan Sandsd114ab32011-02-13 17:15:40 +00002585 // Special logic for binary operators.
2586 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2587 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2588 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002589 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002590 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002591 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2592 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2593 if (LBO && LBO->getOpcode() == Instruction::Add) {
2594 A = LBO->getOperand(0); B = LBO->getOperand(1);
2595 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2596 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2597 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2598 }
2599 if (RBO && RBO->getOpcode() == Instruction::Add) {
2600 C = RBO->getOperand(0); D = RBO->getOperand(1);
2601 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2602 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2603 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2604 }
2605
2606 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2607 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2608 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2609 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002610 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002611 return V;
2612
2613 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2614 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2615 if (Value *V = SimplifyICmpInst(Pred,
2616 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002617 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002618 return V;
2619
2620 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2621 if (A && C && (A == C || A == D || B == C || B == D) &&
2622 NoLHSWrapProblem && NoRHSWrapProblem) {
2623 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002624 Value *Y, *Z;
2625 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002626 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002627 Y = B;
2628 Z = D;
2629 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002630 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002631 Y = B;
2632 Z = C;
2633 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002634 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002635 Y = A;
2636 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002637 } else {
2638 assert(B == D);
2639 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002640 Y = A;
2641 Z = C;
2642 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002643 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002644 return V;
2645 }
2646 }
2647
Nick Lewycky762f8a82016-04-21 00:53:14 +00002648 {
2649 Value *Y = nullptr;
2650 // icmp pred (or X, Y), X
2651 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2652 if (Pred == ICmpInst::ICMP_ULT)
2653 return getFalse(ITy);
2654 if (Pred == ICmpInst::ICMP_UGE)
2655 return getTrue(ITy);
2656
2657 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2658 bool RHSKnownNonNegative, RHSKnownNegative;
2659 bool YKnownNonNegative, YKnownNegative;
2660 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2661 Q.AC, Q.CxtI, Q.DT);
2662 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2663 Q.CxtI, Q.DT);
2664 if (RHSKnownNonNegative && YKnownNegative)
2665 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2666 if (RHSKnownNegative || YKnownNonNegative)
2667 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2668 }
2669 }
2670 // icmp pred X, (or X, Y)
2671 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2672 if (Pred == ICmpInst::ICMP_ULE)
2673 return getTrue(ITy);
2674 if (Pred == ICmpInst::ICMP_UGT)
2675 return getFalse(ITy);
2676
2677 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2678 bool LHSKnownNonNegative, LHSKnownNegative;
2679 bool YKnownNonNegative, YKnownNegative;
2680 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2681 Q.AC, Q.CxtI, Q.DT);
2682 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2683 Q.CxtI, Q.DT);
2684 if (LHSKnownNonNegative && YKnownNegative)
2685 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2686 if (LHSKnownNegative || YKnownNonNegative)
2687 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2688 }
2689 }
David Majnemerbd9ce4e2014-11-25 02:55:48 +00002690 }
2691
2692 // icmp pred (and X, Y), X
2693 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2694 m_And(m_Specific(RHS), m_Value())))) {
2695 if (Pred == ICmpInst::ICMP_UGT)
2696 return getFalse(ITy);
2697 if (Pred == ICmpInst::ICMP_ULE)
2698 return getTrue(ITy);
2699 }
2700 // icmp pred X, (and X, Y)
2701 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2702 m_And(m_Specific(LHS), m_Value())))) {
2703 if (Pred == ICmpInst::ICMP_UGE)
2704 return getTrue(ITy);
2705 if (Pred == ICmpInst::ICMP_ULT)
2706 return getFalse(ITy);
2707 }
2708
David Majnemer2d6c0232014-05-14 20:16:28 +00002709 // 0 - (zext X) pred C
2710 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2711 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2712 if (RHSC->getValue().isStrictlyPositive()) {
2713 if (Pred == ICmpInst::ICMP_SLT)
2714 return ConstantInt::getTrue(RHSC->getContext());
2715 if (Pred == ICmpInst::ICMP_SGE)
2716 return ConstantInt::getFalse(RHSC->getContext());
2717 if (Pred == ICmpInst::ICMP_EQ)
2718 return ConstantInt::getFalse(RHSC->getContext());
2719 if (Pred == ICmpInst::ICMP_NE)
2720 return ConstantInt::getTrue(RHSC->getContext());
2721 }
2722 if (RHSC->getValue().isNonNegative()) {
2723 if (Pred == ICmpInst::ICMP_SLE)
2724 return ConstantInt::getTrue(RHSC->getContext());
2725 if (Pred == ICmpInst::ICMP_SGT)
2726 return ConstantInt::getFalse(RHSC->getContext());
2727 }
2728 }
2729 }
2730
Nick Lewycky35aeea92013-07-12 23:42:57 +00002731 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002732 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002733 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002734 switch (Pred) {
2735 default:
2736 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002737 case ICmpInst::ICMP_SGT:
2738 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002739 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2740 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002741 if (!KnownNonNegative)
2742 break;
2743 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002744 case ICmpInst::ICMP_EQ:
2745 case ICmpInst::ICMP_UGT:
2746 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002747 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002748 case ICmpInst::ICMP_SLT:
2749 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002750 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2751 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002752 if (!KnownNonNegative)
2753 break;
2754 // fall-through
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002755 case ICmpInst::ICMP_NE:
2756 case ICmpInst::ICMP_ULT:
2757 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002758 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002759 }
2760 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002761
2762 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002763 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2764 bool KnownNonNegative, KnownNegative;
2765 switch (Pred) {
2766 default:
2767 break;
2768 case ICmpInst::ICMP_SGT:
2769 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002770 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2771 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002772 if (!KnownNonNegative)
2773 break;
2774 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002775 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002776 case ICmpInst::ICMP_UGT:
2777 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002778 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002779 case ICmpInst::ICMP_SLT:
2780 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002781 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2782 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002783 if (!KnownNonNegative)
2784 break;
2785 // fall-through
Nick Lewycky774647d2011-03-09 08:20:06 +00002786 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002787 case ICmpInst::ICMP_ULT:
2788 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002789 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002790 }
2791 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002792
David Majnemer3af5bf32016-01-21 18:55:54 +00002793 // x >> y <=u x
Duncan Sands92af0a82011-10-28 18:17:44 +00002794 // x udiv y <=u x.
David Majnemer3af5bf32016-01-21 18:55:54 +00002795 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2796 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2797 // icmp pred (X op Y), X
Duncan Sands92af0a82011-10-28 18:17:44 +00002798 if (Pred == ICmpInst::ICMP_UGT)
2799 return getFalse(ITy);
2800 if (Pred == ICmpInst::ICMP_ULE)
2801 return getTrue(ITy);
2802 }
2803
David Majnemer76d06bc2014-08-28 03:34:28 +00002804 // handle:
2805 // CI2 << X == CI
2806 // CI2 << X != CI
2807 //
2808 // where CI2 is a power of 2 and CI isn't
2809 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2810 const APInt *CI2Val, *CIVal = &CI->getValue();
2811 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2812 CI2Val->isPowerOf2()) {
2813 if (!CIVal->isPowerOf2()) {
2814 // CI2 << X can equal zero in some circumstances,
2815 // this simplification is unsafe if CI is zero.
2816 //
2817 // We know it is safe if:
2818 // - The shift is nsw, we can't shift out the one bit.
2819 // - The shift is nuw, we can't shift out the one bit.
2820 // - CI2 is one
2821 // - CI isn't zero
2822 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2823 *CI2Val == 1 || !CI->isZero()) {
2824 if (Pred == ICmpInst::ICMP_EQ)
2825 return ConstantInt::getFalse(RHS->getContext());
2826 if (Pred == ICmpInst::ICMP_NE)
2827 return ConstantInt::getTrue(RHS->getContext());
2828 }
2829 }
2830 if (CIVal->isSignBit() && *CI2Val == 1) {
2831 if (Pred == ICmpInst::ICMP_UGT)
2832 return ConstantInt::getFalse(RHS->getContext());
2833 if (Pred == ICmpInst::ICMP_ULE)
2834 return ConstantInt::getTrue(RHS->getContext());
2835 }
2836 }
2837 }
2838
Nick Lewycky9719a712011-03-05 05:19:11 +00002839 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2840 LBO->getOperand(1) == RBO->getOperand(1)) {
2841 switch (LBO->getOpcode()) {
2842 default: break;
2843 case Instruction::UDiv:
2844 case Instruction::LShr:
2845 if (ICmpInst::isSigned(Pred))
2846 break;
2847 // fall-through
2848 case Instruction::SDiv:
2849 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002850 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002851 break;
2852 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002853 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002854 return V;
2855 break;
2856 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002857 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002858 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2859 if (!NUW && !NSW)
2860 break;
2861 if (!NSW && ICmpInst::isSigned(Pred))
2862 break;
2863 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002864 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002865 return V;
2866 break;
2867 }
2868 }
2869 }
2870
Duncan Sands0a9c1242011-05-03 19:53:10 +00002871 // Simplify comparisons involving max/min.
2872 Value *A, *B;
2873 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002874 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002875
Duncan Sandsa2287852011-05-04 16:05:05 +00002876 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002877 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2878 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002879 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002880 // We analyze this as smax(A, B) pred A.
2881 P = Pred;
2882 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2883 (A == LHS || B == LHS)) {
2884 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002885 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002886 // We analyze this as smax(A, B) swapped-pred A.
2887 P = CmpInst::getSwappedPredicate(Pred);
2888 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2889 (A == RHS || B == RHS)) {
2890 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002891 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002892 // We analyze this as smax(-A, -B) swapped-pred -A.
2893 // Note that we do not need to actually form -A or -B thanks to EqP.
2894 P = CmpInst::getSwappedPredicate(Pred);
2895 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2896 (A == LHS || B == LHS)) {
2897 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002898 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002899 // We analyze this as smax(-A, -B) pred -A.
2900 // Note that we do not need to actually form -A or -B thanks to EqP.
2901 P = Pred;
2902 }
2903 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2904 // Cases correspond to "max(A, B) p A".
2905 switch (P) {
2906 default:
2907 break;
2908 case CmpInst::ICMP_EQ:
2909 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002910 // Equivalent to "A EqP B". This may be the same as the condition tested
2911 // in the max/min; if so, we can just return that.
2912 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2913 return V;
2914 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2915 return V;
2916 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002917 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002918 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002919 return V;
2920 break;
2921 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002922 case CmpInst::ICMP_SGT: {
2923 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2924 // Equivalent to "A InvEqP B". This may be the same as the condition
2925 // tested in the max/min; if so, we can just return that.
2926 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2927 return V;
2928 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2929 return V;
2930 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002931 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002932 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002933 return V;
2934 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002935 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002936 case CmpInst::ICMP_SGE:
2937 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002938 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002939 case CmpInst::ICMP_SLT:
2940 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002941 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002942 }
2943 }
2944
Duncan Sandsa2287852011-05-04 16:05:05 +00002945 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002946 P = CmpInst::BAD_ICMP_PREDICATE;
2947 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2948 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002949 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002950 // We analyze this as umax(A, B) pred A.
2951 P = Pred;
2952 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2953 (A == LHS || B == LHS)) {
2954 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002955 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002956 // We analyze this as umax(A, B) swapped-pred A.
2957 P = CmpInst::getSwappedPredicate(Pred);
2958 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2959 (A == RHS || B == RHS)) {
2960 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002961 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002962 // We analyze this as umax(-A, -B) swapped-pred -A.
2963 // Note that we do not need to actually form -A or -B thanks to EqP.
2964 P = CmpInst::getSwappedPredicate(Pred);
2965 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2966 (A == LHS || B == LHS)) {
2967 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002968 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002969 // We analyze this as umax(-A, -B) pred -A.
2970 // Note that we do not need to actually form -A or -B thanks to EqP.
2971 P = Pred;
2972 }
2973 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2974 // Cases correspond to "max(A, B) p A".
2975 switch (P) {
2976 default:
2977 break;
2978 case CmpInst::ICMP_EQ:
2979 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002980 // Equivalent to "A EqP B". This may be the same as the condition tested
2981 // in the max/min; if so, we can just return that.
2982 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2983 return V;
2984 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2985 return V;
2986 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002987 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002988 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002989 return V;
2990 break;
2991 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002992 case CmpInst::ICMP_UGT: {
2993 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2994 // Equivalent to "A InvEqP B". This may be the same as the condition
2995 // tested in the max/min; if so, we can just return that.
2996 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2997 return V;
2998 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2999 return V;
3000 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003001 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003002 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003003 return V;
3004 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00003005 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00003006 case CmpInst::ICMP_UGE:
3007 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003008 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003009 case CmpInst::ICMP_ULT:
3010 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003011 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003012 }
3013 }
3014
Duncan Sandsa2287852011-05-04 16:05:05 +00003015 // Variants on "max(x,y) >= min(x,z)".
3016 Value *C, *D;
3017 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3018 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3019 (A == C || A == D || B == C || B == D)) {
3020 // max(x, ?) pred min(x, ?).
3021 if (Pred == CmpInst::ICMP_SGE)
3022 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003023 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003024 if (Pred == CmpInst::ICMP_SLT)
3025 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003026 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003027 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3028 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3029 (A == C || A == D || B == C || B == D)) {
3030 // min(x, ?) pred max(x, ?).
3031 if (Pred == CmpInst::ICMP_SLE)
3032 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003033 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003034 if (Pred == CmpInst::ICMP_SGT)
3035 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003036 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003037 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3038 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3039 (A == C || A == D || B == C || B == D)) {
3040 // max(x, ?) pred min(x, ?).
3041 if (Pred == CmpInst::ICMP_UGE)
3042 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003043 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003044 if (Pred == CmpInst::ICMP_ULT)
3045 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003046 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003047 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3048 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3049 (A == C || A == D || B == C || B == D)) {
3050 // min(x, ?) pred max(x, ?).
3051 if (Pred == CmpInst::ICMP_ULE)
3052 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003053 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003054 if (Pred == CmpInst::ICMP_UGT)
3055 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003056 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003057 }
3058
Chandler Carruth8059c842012-03-25 21:28:14 +00003059 // Simplify comparisons of related pointers using a powerful, recursive
3060 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003061 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003062 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003063 return C;
3064
Nick Lewycky3db143e2012-02-26 02:09:49 +00003065 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3066 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3067 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3068 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3069 (ICmpInst::isEquality(Pred) ||
3070 (GLHS->isInBounds() && GRHS->isInBounds() &&
3071 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3072 // The bases are equal and the indices are constant. Build a constant
3073 // expression GEP with the same indices and a null base pointer to see
3074 // what constant folding can make out of it.
3075 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3076 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003077 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3078 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003079
3080 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003081 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3082 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003083 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3084 }
3085 }
3086 }
3087
David Majnemer5854e9f2014-11-16 02:20:08 +00003088 // If a bit is known to be zero for A and known to be one for B,
3089 // then A and B cannot be equal.
3090 if (ICmpInst::isEquality(Pred)) {
3091 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3092 uint32_t BitWidth = CI->getBitWidth();
3093 APInt LHSKnownZero(BitWidth, 0);
3094 APInt LHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003095 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003096 Q.CxtI, Q.DT);
3097 const APInt &RHSVal = CI->getValue();
3098 if (((LHSKnownZero & RHSVal) != 0) || ((LHSKnownOne & ~RHSVal) != 0))
3099 return Pred == ICmpInst::ICMP_EQ
3100 ? ConstantInt::getFalse(CI->getContext())
3101 : ConstantInt::getTrue(CI->getContext());
3102 }
3103 }
3104
Duncan Sandsf532d312010-11-07 16:12:23 +00003105 // If the comparison is with the result of a select instruction, check whether
3106 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003107 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003108 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003109 return V;
3110
3111 // If the comparison is with the result of a phi instruction, check whether
3112 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003113 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003114 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003115 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003116
Craig Topper9f008862014-04-15 04:59:12 +00003117 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003118}
3119
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003120Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003121 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003122 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003123 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003124 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003125 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003126 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003127}
3128
Sanjay Patel472cc782016-01-11 22:14:42 +00003129/// Given operands for an FCmpInst, see if we can fold the result.
3130/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003131static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003132 FastMathFlags FMF, const Query &Q,
3133 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003134 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3135 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3136
Chris Lattnera71e9d62009-11-10 00:55:12 +00003137 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003138 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003139 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003140
Chris Lattnera71e9d62009-11-10 00:55:12 +00003141 // If we have a constant, make sure it is on the RHS.
3142 std::swap(LHS, RHS);
3143 Pred = CmpInst::getSwappedPredicate(Pred);
3144 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003145
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003146 // Fold trivial predicates.
3147 if (Pred == FCmpInst::FCMP_FALSE)
3148 return ConstantInt::get(GetCompareTy(LHS), 0);
3149 if (Pred == FCmpInst::FCMP_TRUE)
3150 return ConstantInt::get(GetCompareTy(LHS), 1);
3151
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003152 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3153 if (FMF.noNaNs()) {
3154 if (Pred == FCmpInst::FCMP_UNO)
3155 return ConstantInt::get(GetCompareTy(LHS), 0);
3156 if (Pred == FCmpInst::FCMP_ORD)
3157 return ConstantInt::get(GetCompareTy(LHS), 1);
3158 }
3159
Mehdi Aminieb242a52015-03-09 03:20:25 +00003160 // fcmp pred x, undef and fcmp pred undef, x
3161 // fold to true if unordered, false if ordered
3162 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3163 // Choosing NaN for the undef will always make unordered comparison succeed
3164 // and ordered comparison fail.
3165 return ConstantInt::get(GetCompareTy(LHS), CmpInst::isUnordered(Pred));
3166 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003167
3168 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003169 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003170 if (CmpInst::isTrueWhenEqual(Pred))
3171 return ConstantInt::get(GetCompareTy(LHS), 1);
3172 if (CmpInst::isFalseWhenEqual(Pred))
3173 return ConstantInt::get(GetCompareTy(LHS), 0);
3174 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003175
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003176 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003177 const ConstantFP *CFP = nullptr;
3178 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3179 if (RHS->getType()->isVectorTy())
3180 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3181 else
3182 CFP = dyn_cast<ConstantFP>(RHSC);
3183 }
3184 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003185 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003186 if (CFP->getValueAPF().isNaN()) {
3187 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
3188 return ConstantInt::getFalse(CFP->getContext());
3189 assert(FCmpInst::isUnordered(Pred) &&
3190 "Comparison must be either ordered or unordered!");
3191 // True if unordered.
David Majnemer3ee5f342016-04-13 06:55:52 +00003192 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003193 }
3194 // Check whether the constant is an infinity.
3195 if (CFP->getValueAPF().isInfinity()) {
3196 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003197 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003198 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003199 // No value is ordered and less than negative infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003200 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003201 case FCmpInst::FCMP_UGE:
3202 // All values are unordered with or at least negative infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003203 return ConstantInt::get(GetCompareTy(LHS), 1);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003204 default:
3205 break;
3206 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003207 } else {
3208 switch (Pred) {
3209 case FCmpInst::FCMP_OGT:
3210 // No value is ordered and greater than infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003211 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003212 case FCmpInst::FCMP_ULE:
3213 // All values are unordered with and at most infinity.
David Majnemer3ee5f342016-04-13 06:55:52 +00003214 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003215 default:
3216 break;
3217 }
3218 }
3219 }
3220 if (CFP->getValueAPF().isZero()) {
3221 switch (Pred) {
3222 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003223 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3224 return ConstantInt::get(GetCompareTy(LHS), 1);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003225 break;
3226 case FCmpInst::FCMP_OLT:
3227 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003228 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
3229 return ConstantInt::get(GetCompareTy(LHS), 0);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003230 break;
3231 default:
3232 break;
3233 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003234 }
3235 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003236
Duncan Sandsa620bd12010-11-07 16:46:25 +00003237 // If the comparison is with the result of a select instruction, check whether
3238 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003239 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003240 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003241 return V;
3242
3243 // If the comparison is with the result of a phi instruction, check whether
3244 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003245 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003246 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003247 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003248
Craig Topper9f008862014-04-15 04:59:12 +00003249 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003250}
3251
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003252Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003253 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003254 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003255 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003256 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003257 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3258 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003259}
3260
Sanjay Patel472cc782016-01-11 22:14:42 +00003261/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003262static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3263 const Query &Q,
3264 unsigned MaxRecurse) {
3265 // Trivial replacement.
3266 if (V == Op)
3267 return RepOp;
3268
3269 auto *I = dyn_cast<Instruction>(V);
3270 if (!I)
3271 return nullptr;
3272
3273 // If this is a binary operator, try to simplify it with the replaced op.
3274 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3275 // Consider:
3276 // %cmp = icmp eq i32 %x, 2147483647
3277 // %add = add nsw i32 %x, 1
3278 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3279 //
3280 // We can't replace %sel with %add unless we strip away the flags.
3281 if (isa<OverflowingBinaryOperator>(B))
3282 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3283 return nullptr;
3284 if (isa<PossiblyExactOperator>(B))
3285 if (B->isExact())
3286 return nullptr;
3287
3288 if (MaxRecurse) {
3289 if (B->getOperand(0) == Op)
3290 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3291 MaxRecurse - 1);
3292 if (B->getOperand(1) == Op)
3293 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3294 MaxRecurse - 1);
3295 }
3296 }
3297
3298 // Same for CmpInsts.
3299 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3300 if (MaxRecurse) {
3301 if (C->getOperand(0) == Op)
3302 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3303 MaxRecurse - 1);
3304 if (C->getOperand(1) == Op)
3305 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3306 MaxRecurse - 1);
3307 }
3308 }
3309
3310 // TODO: We could hand off more cases to instsimplify here.
3311
3312 // If all operands are constant after substituting Op for RepOp then we can
3313 // constant fold the instruction.
3314 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3315 // Build a list of all constant operands.
3316 SmallVector<Constant *, 8> ConstOps;
3317 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3318 if (I->getOperand(i) == Op)
3319 ConstOps.push_back(CRepOp);
3320 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3321 ConstOps.push_back(COp);
3322 else
3323 break;
3324 }
3325
3326 // All operands were constants, fold it.
3327 if (ConstOps.size() == I->getNumOperands()) {
3328 if (CmpInst *C = dyn_cast<CmpInst>(I))
3329 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3330 ConstOps[1], Q.DL, Q.TLI);
3331
3332 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3333 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003334 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003335
Manuel Jacobe9024592016-01-21 06:33:22 +00003336 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003337 }
3338 }
3339
3340 return nullptr;
3341}
3342
Sanjay Patel472cc782016-01-11 22:14:42 +00003343/// Given operands for a SelectInst, see if we can fold the result.
3344/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003345static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3346 Value *FalseVal, const Query &Q,
3347 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003348 // select true, X, Y -> X
3349 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003350 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3351 if (CB->isAllOnesValue())
3352 return TrueVal;
3353 if (CB->isNullValue())
3354 return FalseVal;
3355 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003356
Chris Lattnerc707fa92010-04-20 05:32:14 +00003357 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003358 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003359 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003360
Chris Lattnerc707fa92010-04-20 05:32:14 +00003361 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3362 if (isa<Constant>(TrueVal))
3363 return TrueVal;
3364 return FalseVal;
3365 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003366 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3367 return FalseVal;
3368 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3369 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003370
David Majnemer3f0fb982015-06-06 22:40:21 +00003371 if (const auto *ICI = dyn_cast<ICmpInst>(CondVal)) {
3372 unsigned BitWidth = Q.DL.getTypeSizeInBits(TrueVal->getType());
David Majnemer7bd71442014-12-20 03:29:59 +00003373 ICmpInst::Predicate Pred = ICI->getPredicate();
David Majnemer3f0fb982015-06-06 22:40:21 +00003374 Value *CmpLHS = ICI->getOperand(0);
3375 Value *CmpRHS = ICI->getOperand(1);
David Majnemer147f8582014-12-20 04:45:33 +00003376 APInt MinSignedValue = APInt::getSignBit(BitWidth);
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003377 Value *X;
3378 const APInt *Y;
David Majnemer7bd71442014-12-20 03:29:59 +00003379 bool TrueWhenUnset;
David Majnemer147f8582014-12-20 04:45:33 +00003380 bool IsBitTest = false;
David Majnemer0b6a0b02014-12-20 03:04:38 +00003381 if (ICmpInst::isEquality(Pred) &&
David Majnemer3f0fb982015-06-06 22:40:21 +00003382 match(CmpLHS, m_And(m_Value(X), m_APInt(Y))) &&
3383 match(CmpRHS, m_Zero())) {
David Majnemer7bd71442014-12-20 03:29:59 +00003384 IsBitTest = true;
3385 TrueWhenUnset = Pred == ICmpInst::ICMP_EQ;
David Majnemer3f0fb982015-06-06 22:40:21 +00003386 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
3387 X = CmpLHS;
David Majnemer7bd71442014-12-20 03:29:59 +00003388 Y = &MinSignedValue;
3389 IsBitTest = true;
3390 TrueWhenUnset = false;
David Majnemer3f0fb982015-06-06 22:40:21 +00003391 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
3392 X = CmpLHS;
David Majnemer7bd71442014-12-20 03:29:59 +00003393 Y = &MinSignedValue;
3394 IsBitTest = true;
3395 TrueWhenUnset = true;
3396 }
3397 if (IsBitTest) {
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003398 const APInt *C;
3399 // (X & Y) == 0 ? X & ~Y : X --> X
3400 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3401 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3402 *Y == ~*C)
David Majnemer7bd71442014-12-20 03:29:59 +00003403 return TrueWhenUnset ? FalseVal : TrueVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003404 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3405 // (X & Y) != 0 ? X : X & ~Y --> X
3406 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3407 *Y == ~*C)
David Majnemer7bd71442014-12-20 03:29:59 +00003408 return TrueWhenUnset ? FalseVal : TrueVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003409
3410 if (Y->isPowerOf2()) {
3411 // (X & Y) == 0 ? X | Y : X --> X | Y
3412 // (X & Y) != 0 ? X | Y : X --> X
3413 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3414 *Y == *C)
David Majnemer7bd71442014-12-20 03:29:59 +00003415 return TrueWhenUnset ? TrueVal : FalseVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003416 // (X & Y) == 0 ? X : X | Y --> X
3417 // (X & Y) != 0 ? X : X | Y --> X | Y
3418 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3419 *Y == *C)
David Majnemer7bd71442014-12-20 03:29:59 +00003420 return TrueWhenUnset ? TrueVal : FalseVal;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003421 }
3422 }
David Majnemer3f0fb982015-06-06 22:40:21 +00003423 if (ICI->hasOneUse()) {
3424 const APInt *C;
3425 if (match(CmpRHS, m_APInt(C))) {
3426 // X < MIN ? T : F --> F
3427 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3428 return FalseVal;
3429 // X < MIN ? T : F --> F
3430 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3431 return FalseVal;
3432 // X > MAX ? T : F --> F
3433 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3434 return FalseVal;
3435 // X > MAX ? T : F --> F
3436 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3437 return FalseVal;
3438 }
3439 }
3440
3441 // If we have an equality comparison then we know the value in one of the
3442 // arms of the select. See if substituting this value into the arm and
3443 // simplifying the result yields the same value as the other arm.
3444 if (Pred == ICmpInst::ICMP_EQ) {
3445 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3446 TrueVal ||
3447 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3448 TrueVal)
3449 return FalseVal;
3450 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3451 FalseVal ||
3452 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3453 FalseVal)
3454 return FalseVal;
3455 } else if (Pred == ICmpInst::ICMP_NE) {
3456 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3457 FalseVal ||
3458 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3459 FalseVal)
3460 return TrueVal;
3461 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3462 TrueVal ||
3463 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3464 TrueVal)
3465 return TrueVal;
3466 }
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003467 }
3468
Craig Topper9f008862014-04-15 04:59:12 +00003469 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003470}
3471
Duncan Sandsb8cee002012-03-13 11:42:19 +00003472Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003473 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003474 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003475 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003476 const Instruction *CxtI) {
3477 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Chandler Carruth66b31302015-01-04 12:03:27 +00003478 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003479}
3480
Sanjay Patel472cc782016-01-11 22:14:42 +00003481/// Given operands for an GetElementPtrInst, see if we can fold the result.
3482/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003483static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3484 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003485 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003486 unsigned AS =
3487 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003488
Chris Lattner8574aba2009-11-27 00:29:05 +00003489 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003490 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003491 return Ops[0];
3492
Nico Weber48c82402014-08-27 20:06:19 +00003493 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003494 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003495 Type *GEPTy = PointerType::get(LastType, AS);
3496 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3497 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3498
3499 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003500 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003501
Jay Foadb992a632011-07-19 15:07:52 +00003502 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003503 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003504 if (match(Ops[1], m_Zero()))
3505 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003506
David Blaikie4a2e73b2015-04-02 18:55:32 +00003507 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003508 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003509 Value *P;
3510 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003511 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003512 // getelementptr P, N -> P if P points to a type of zero size.
3513 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003514 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003515
3516 // The following transforms are only safe if the ptrtoint cast
3517 // doesn't truncate the pointers.
3518 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003519 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003520 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3521 if (match(P, m_Zero()))
3522 return Constant::getNullValue(GEPTy);
3523 Value *Temp;
3524 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003525 if (Temp->getType() == GEPTy)
3526 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003527 return nullptr;
3528 };
3529
3530 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3531 if (TyAllocSize == 1 &&
3532 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3533 if (Value *R = PtrToIntOrZero(P))
3534 return R;
3535
3536 // getelementptr V, (ashr (sub P, V), C) -> Q
3537 // if P points to a type of size 1 << C.
3538 if (match(Ops[1],
3539 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3540 m_ConstantInt(C))) &&
3541 TyAllocSize == 1ULL << C)
3542 if (Value *R = PtrToIntOrZero(P))
3543 return R;
3544
3545 // getelementptr V, (sdiv (sub P, V), C) -> Q
3546 // if P points to a type of size C.
3547 if (match(Ops[1],
3548 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3549 m_SpecificInt(TyAllocSize))))
3550 if (Value *R = PtrToIntOrZero(P))
3551 return R;
3552 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003553 }
3554 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003555
Chris Lattner8574aba2009-11-27 00:29:05 +00003556 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003557 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003558 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003559 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003560
David Blaikie4a2e73b2015-04-02 18:55:32 +00003561 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3562 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003563}
3564
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003565Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3566 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003567 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003568 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003569 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003570 return ::SimplifyGEPInst(SrcTy, Ops,
3571 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003572}
3573
Sanjay Patel472cc782016-01-11 22:14:42 +00003574/// Given operands for an InsertValueInst, see if we can fold the result.
3575/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003576static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3577 ArrayRef<unsigned> Idxs, const Query &Q,
3578 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003579 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3580 if (Constant *CVal = dyn_cast<Constant>(Val))
3581 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3582
3583 // insertvalue x, undef, n -> x
3584 if (match(Val, m_Undef()))
3585 return Agg;
3586
3587 // insertvalue x, (extractvalue y, n), n
3588 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003589 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3590 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003591 // insertvalue undef, (extractvalue y, n), n -> y
3592 if (match(Agg, m_Undef()))
3593 return EV->getAggregateOperand();
3594
3595 // insertvalue y, (extractvalue y, n), n -> y
3596 if (Agg == EV->getAggregateOperand())
3597 return Agg;
3598 }
3599
Craig Topper9f008862014-04-15 04:59:12 +00003600 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003601}
3602
Chandler Carruth66b31302015-01-04 12:03:27 +00003603Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003604 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003605 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3606 const Instruction *CxtI) {
3607 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003608 RecursionLimit);
3609}
3610
Sanjay Patel472cc782016-01-11 22:14:42 +00003611/// Given operands for an ExtractValueInst, see if we can fold the result.
3612/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003613static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3614 const Query &, unsigned) {
3615 if (auto *CAgg = dyn_cast<Constant>(Agg))
3616 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3617
3618 // extractvalue x, (insertvalue y, elt, n), n -> elt
3619 unsigned NumIdxs = Idxs.size();
3620 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3621 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3622 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3623 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3624 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3625 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3626 Idxs.slice(0, NumCommonIdxs)) {
3627 if (NumIdxs == NumInsertValueIdxs)
3628 return IVI->getInsertedValueOperand();
3629 break;
3630 }
3631 }
3632
3633 return nullptr;
3634}
3635
3636Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3637 const DataLayout &DL,
3638 const TargetLibraryInfo *TLI,
3639 const DominatorTree *DT,
3640 AssumptionCache *AC,
3641 const Instruction *CxtI) {
3642 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3643 RecursionLimit);
3644}
3645
Sanjay Patel472cc782016-01-11 22:14:42 +00003646/// Given operands for an ExtractElementInst, see if we can fold the result.
3647/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003648static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3649 unsigned) {
3650 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3651 if (auto *CIdx = dyn_cast<Constant>(Idx))
3652 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3653
3654 // The index is not relevant if our vector is a splat.
3655 if (auto *Splat = CVec->getSplatValue())
3656 return Splat;
3657
3658 if (isa<UndefValue>(Vec))
3659 return UndefValue::get(Vec->getType()->getVectorElementType());
3660 }
3661
3662 // If extracting a specified index from the vector, see if we can recursively
3663 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003664 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3665 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003666 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003667
3668 return nullptr;
3669}
3670
3671Value *llvm::SimplifyExtractElementInst(
3672 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3673 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3674 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3675 RecursionLimit);
3676}
3677
Sanjay Patel472cc782016-01-11 22:14:42 +00003678/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003679static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003680 // If all of the PHI's incoming values are the same then replace the PHI node
3681 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003682 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003683 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003684 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003685 // If the incoming value is the phi node itself, it can safely be skipped.
3686 if (Incoming == PN) continue;
3687 if (isa<UndefValue>(Incoming)) {
3688 // Remember that we saw an undef value, but otherwise ignore them.
3689 HasUndefInput = true;
3690 continue;
3691 }
3692 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003693 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003694 CommonValue = Incoming;
3695 }
3696
3697 // If CommonValue is null then all of the incoming values were either undef or
3698 // equal to the phi node itself.
3699 if (!CommonValue)
3700 return UndefValue::get(PN->getType());
3701
3702 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3703 // instruction, we cannot return X as the result of the PHI node unless it
3704 // dominates the PHI block.
3705 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003706 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003707
3708 return CommonValue;
3709}
3710
Duncan Sands395ac42d2012-03-13 14:07:05 +00003711static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3712 if (Constant *C = dyn_cast<Constant>(Op))
Manuel Jacob925d0292016-01-21 06:31:08 +00003713 return ConstantFoldCastOperand(Instruction::Trunc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003714
Craig Topper9f008862014-04-15 04:59:12 +00003715 return nullptr;
Duncan Sands395ac42d2012-03-13 14:07:05 +00003716}
3717
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003718Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout &DL,
Duncan Sands395ac42d2012-03-13 14:07:05 +00003719 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003720 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003721 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003722 return ::SimplifyTruncInst(Op, Ty, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00003723 RecursionLimit);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003724}
3725
Chris Lattnera71e9d62009-11-10 00:55:12 +00003726//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00003727
Sanjay Patel472cc782016-01-11 22:14:42 +00003728/// Given operands for a BinaryOperator, see if we can fold the result.
3729/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003730static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003731 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00003732 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00003733 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003734 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003735 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003736 case Instruction::FAdd:
3737 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3738
Chris Lattner9e4aa022011-02-09 17:15:04 +00003739 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003740 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003741 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003742 case Instruction::FSub:
3743 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3744
Duncan Sandsb8cee002012-03-13 11:42:19 +00003745 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003746 case Instruction::FMul:
3747 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003748 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3749 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003750 case Instruction::FDiv:
3751 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003752 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3753 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003754 case Instruction::FRem:
3755 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003756 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003757 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003758 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003759 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003760 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003761 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003762 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3763 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3764 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3765 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003766 default:
3767 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00003768 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3769 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00003770
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003771 // If the operation is associative, try some generic simplifications.
3772 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003773 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003774 return V;
3775
Duncan Sandsb8cee002012-03-13 11:42:19 +00003776 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00003777 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003778 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003779 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003780 return V;
3781
3782 // If the operation is with the result of a phi instruction, check whether
3783 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003784 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003785 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00003786 return V;
3787
Craig Topper9f008862014-04-15 04:59:12 +00003788 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00003789 }
3790}
Chris Lattnerc1f19072009-11-09 23:28:39 +00003791
Sanjay Patel472cc782016-01-11 22:14:42 +00003792/// Given operands for a BinaryOperator, see if we can fold the result.
3793/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003794/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3795/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3796static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3797 const FastMathFlags &FMF, const Query &Q,
3798 unsigned MaxRecurse) {
3799 switch (Opcode) {
3800 case Instruction::FAdd:
3801 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3802 case Instruction::FSub:
3803 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3804 case Instruction::FMul:
3805 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3806 default:
3807 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3808 }
3809}
3810
Duncan Sands7e800d62010-11-14 11:23:23 +00003811Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003812 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003813 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003814 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003815 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00003816 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00003817}
3818
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003819Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003820 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003821 const TargetLibraryInfo *TLI,
3822 const DominatorTree *DT, AssumptionCache *AC,
3823 const Instruction *CxtI) {
3824 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3825 RecursionLimit);
3826}
3827
Sanjay Patel472cc782016-01-11 22:14:42 +00003828/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003829static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003830 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003831 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003832 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003833 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003834}
3835
3836Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003837 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003838 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003839 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003840 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003841 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003842}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003843
Michael Ilseman54857292013-02-07 19:26:05 +00003844static bool IsIdempotent(Intrinsic::ID ID) {
3845 switch (ID) {
3846 default: return false;
3847
3848 // Unary idempotent: f(f(x)) = f(x)
3849 case Intrinsic::fabs:
3850 case Intrinsic::floor:
3851 case Intrinsic::ceil:
3852 case Intrinsic::trunc:
3853 case Intrinsic::rint:
3854 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00003855 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00003856 return true;
3857 }
3858}
3859
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00003860static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
3861 const DataLayout &DL) {
3862 GlobalValue *PtrSym;
3863 APInt PtrOffset;
3864 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
3865 return nullptr;
3866
3867 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
3868 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
3869 Type *Int32PtrTy = Int32Ty->getPointerTo();
3870 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
3871
3872 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
3873 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
3874 return nullptr;
3875
3876 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
3877 if (OffsetInt % 4 != 0)
3878 return nullptr;
3879
3880 Constant *C = ConstantExpr::getGetElementPtr(
3881 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
3882 ConstantInt::get(Int64Ty, OffsetInt / 4));
3883 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
3884 if (!Loaded)
3885 return nullptr;
3886
3887 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
3888 if (!LoadedCE)
3889 return nullptr;
3890
3891 if (LoadedCE->getOpcode() == Instruction::Trunc) {
3892 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3893 if (!LoadedCE)
3894 return nullptr;
3895 }
3896
3897 if (LoadedCE->getOpcode() != Instruction::Sub)
3898 return nullptr;
3899
3900 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
3901 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
3902 return nullptr;
3903 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
3904
3905 Constant *LoadedRHS = LoadedCE->getOperand(1);
3906 GlobalValue *LoadedRHSSym;
3907 APInt LoadedRHSOffset;
3908 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
3909 DL) ||
3910 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
3911 return nullptr;
3912
3913 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
3914}
3915
Michael Ilseman54857292013-02-07 19:26:05 +00003916template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00003917static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00003918 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00003919 Intrinsic::ID IID = F->getIntrinsicID();
3920 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
3921 Type *ReturnType = F->getReturnType();
3922
3923 // Binary Ops
3924 if (NumOperands == 2) {
3925 Value *LHS = *ArgBegin;
3926 Value *RHS = *(ArgBegin + 1);
3927 if (IID == Intrinsic::usub_with_overflow ||
3928 IID == Intrinsic::ssub_with_overflow) {
3929 // X - X -> { 0, false }
3930 if (LHS == RHS)
3931 return Constant::getNullValue(ReturnType);
3932
3933 // X - undef -> undef
3934 // undef - X -> undef
3935 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
3936 return UndefValue::get(ReturnType);
3937 }
3938
3939 if (IID == Intrinsic::uadd_with_overflow ||
3940 IID == Intrinsic::sadd_with_overflow) {
3941 // X + undef -> undef
3942 if (isa<UndefValue>(RHS))
3943 return UndefValue::get(ReturnType);
3944 }
3945
3946 if (IID == Intrinsic::umul_with_overflow ||
3947 IID == Intrinsic::smul_with_overflow) {
3948 // X * 0 -> { 0, false }
3949 if (match(RHS, m_Zero()))
3950 return Constant::getNullValue(ReturnType);
3951
3952 // X * undef -> { 0, false }
3953 if (match(RHS, m_Undef()))
3954 return Constant::getNullValue(ReturnType);
3955 }
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00003956
3957 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
3958 isa<Constant>(RHS))
3959 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
3960 Q.DL);
David Majnemer15032582015-05-22 03:56:46 +00003961 }
3962
Michael Ilseman54857292013-02-07 19:26:05 +00003963 // Perform idempotent optimizations
3964 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00003965 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003966
3967 // Unary Ops
David Majnemer15032582015-05-22 03:56:46 +00003968 if (NumOperands == 1)
Michael Ilseman54857292013-02-07 19:26:05 +00003969 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3970 if (II->getIntrinsicID() == IID)
3971 return II;
3972
Craig Topper9f008862014-04-15 04:59:12 +00003973 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00003974}
3975
Chandler Carruth9dc35582012-12-28 11:30:55 +00003976template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00003977static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00003978 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00003979 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00003980 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3981 Ty = PTy->getElementType();
3982 FunctionType *FTy = cast<FunctionType>(Ty);
3983
Dan Gohman85977e62011-11-04 18:32:42 +00003984 // call undef -> undef
Chandler Carruthf6182152012-12-28 14:23:29 +00003985 if (isa<UndefValue>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00003986 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00003987
Chandler Carruthf6182152012-12-28 14:23:29 +00003988 Function *F = dyn_cast<Function>(V);
3989 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00003990 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003991
David Majnemer15032582015-05-22 03:56:46 +00003992 if (F->isIntrinsic())
3993 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00003994 return Ret;
3995
Chandler Carruthf6182152012-12-28 14:23:29 +00003996 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00003997 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00003998
3999 SmallVector<Constant *, 4> ConstantArgs;
4000 ConstantArgs.reserve(ArgEnd - ArgBegin);
4001 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4002 Constant *C = dyn_cast<Constant>(*I);
4003 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004004 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004005 ConstantArgs.push_back(C);
4006 }
4007
4008 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004009}
4010
Chandler Carruthf6182152012-12-28 14:23:29 +00004011Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004012 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004013 const TargetLibraryInfo *TLI, const DominatorTree *DT,
4014 AssumptionCache *AC, const Instruction *CxtI) {
4015 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004016 RecursionLimit);
4017}
4018
Chandler Carruthf6182152012-12-28 14:23:29 +00004019Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004020 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004021 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004022 const Instruction *CxtI) {
4023 return ::SimplifyCall(V, Args.begin(), Args.end(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004024 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004025}
4026
Sanjay Patel472cc782016-01-11 22:14:42 +00004027/// See if we can compute a simplified version of this instruction.
4028/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004029Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004030 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004031 const DominatorTree *DT, AssumptionCache *AC) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004032 Value *Result;
4033
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004034 switch (I->getOpcode()) {
4035 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004036 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004037 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004038 case Instruction::FAdd:
4039 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004040 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004041 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004042 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004043 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4044 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004045 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4046 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004047 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004048 case Instruction::FSub:
4049 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004050 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004051 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004052 case Instruction::Sub:
4053 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4054 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004055 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4056 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004057 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004058 case Instruction::FMul:
4059 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004060 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004061 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004062 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004063 Result =
4064 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004065 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004066 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004067 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4068 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004069 break;
4070 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004071 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4072 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004073 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004074 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004075 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4076 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004077 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004078 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004079 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4080 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004081 break;
4082 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004083 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4084 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004085 break;
4086 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004087 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4088 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004089 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004090 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004091 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4092 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004093 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4094 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004095 break;
4096 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004097 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004098 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4099 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004100 break;
4101 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004102 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004103 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4104 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004105 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004106 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004107 Result =
4108 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004109 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004110 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004111 Result =
4112 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004113 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004114 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004115 Result =
4116 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004117 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004118 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004119 Result =
4120 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4121 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004122 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004123 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004124 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4125 I->getOperand(0), I->getOperand(1),
4126 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004127 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004128 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004129 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004130 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004131 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004132 case Instruction::GetElementPtr: {
4133 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004134 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4135 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004136 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004137 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004138 case Instruction::InsertValue: {
4139 InsertValueInst *IV = cast<InsertValueInst>(I);
4140 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4141 IV->getInsertedValueOperand(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004142 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004143 break;
4144 }
David Majnemer25a796e2015-07-13 01:15:46 +00004145 case Instruction::ExtractValue: {
4146 auto *EVI = cast<ExtractValueInst>(I);
4147 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4148 EVI->getIndices(), DL, TLI, DT, AC, I);
4149 break;
4150 }
David Majnemer599ca442015-07-13 01:15:53 +00004151 case Instruction::ExtractElement: {
4152 auto *EEI = cast<ExtractElementInst>(I);
4153 Result = SimplifyExtractElementInst(
4154 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4155 break;
4156 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004157 case Instruction::PHI:
Chandler Carruth66b31302015-01-04 12:03:27 +00004158 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004159 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004160 case Instruction::Call: {
4161 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004162 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4163 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004164 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004165 }
Duncan Sands395ac42d2012-03-13 14:07:05 +00004166 case Instruction::Trunc:
Chandler Carruth66b31302015-01-04 12:03:27 +00004167 Result =
4168 SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT, AC, I);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004169 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004170 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004171
Hal Finkelf2199b22015-10-23 20:37:08 +00004172 // In general, it is possible for computeKnownBits to determine all bits in a
4173 // value even when the operands are not all constants.
4174 if (!Result && I->getType()->isIntegerTy()) {
4175 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4176 APInt KnownZero(BitWidth, 0);
4177 APInt KnownOne(BitWidth, 0);
4178 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4179 if ((KnownZero | KnownOne).isAllOnesValue())
4180 Result = ConstantInt::get(I->getContext(), KnownOne);
4181 }
4182
Duncan Sands64e41cf2010-11-17 08:35:29 +00004183 /// If called on unreachable code, the above logic may report that the
4184 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004185 /// detecting that case here, returning a safe value instead.
4186 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004187}
4188
Sanjay Patelf44bd382016-01-20 18:59:48 +00004189/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004190/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004191///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004192/// This is the common implementation of the recursive simplification routines.
4193/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4194/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4195/// instructions to process and attempt to simplify it using
4196/// InstructionSimplify.
4197///
4198/// This routine returns 'true' only when *it* simplifies something. The passed
4199/// in simplified value does not count toward this.
4200static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004201 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004202 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004203 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004204 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004205 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004206 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004207
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004208 // If we have an explicit value to collapse to, do that round of the
4209 // simplification loop by hand initially.
4210 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004211 for (User *U : I->users())
4212 if (U != I)
4213 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004214
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004215 // Replace the instruction with its simplified value.
4216 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004217
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004218 // Gracefully handle edge cases where the instruction is not wired into any
4219 // parent block.
4220 if (I->getParent())
4221 I->eraseFromParent();
4222 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004223 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004224 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004225
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004226 // Note that we must test the size on each iteration, the worklist can grow.
4227 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4228 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004229
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004230 // See if this instruction simplifies.
Chandler Carruth66b31302015-01-04 12:03:27 +00004231 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004232 if (!SimpleV)
4233 continue;
4234
4235 Simplified = true;
4236
4237 // Stash away all the uses of the old instruction so we can check them for
4238 // recursive simplifications after a RAUW. This is cheaper than checking all
4239 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004240 for (User *U : I->users())
4241 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004242
4243 // Replace the instruction with its simplified value.
4244 I->replaceAllUsesWith(SimpleV);
4245
4246 // Gracefully handle edge cases where the instruction is not wired into any
4247 // parent block.
4248 if (I->getParent())
4249 I->eraseFromParent();
4250 }
4251 return Simplified;
4252}
4253
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004254bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004255 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004256 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004257 AssumptionCache *AC) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004258 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004259}
4260
4261bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004262 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004263 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004264 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004265 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4266 assert(SimpleV && "Must provide a simplified value.");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004267 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004268}