blob: 8d6c83b1b8ddc67e3036d077e17f0cef3c739bb9 [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);
David Majnemer6774d612016-07-26 17:58:05 +000072static Value *SimplifyCastInst(unsigned, Value *, Type *,
73 const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000074
Sanjay Patel472cc782016-01-11 22:14:42 +000075/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000076/// a vector with every element false, as appropriate for the type.
77static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000078 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000079 "Expected i1 type or a vector of i1!");
80 return Constant::getNullValue(Ty);
81}
82
Sanjay Patel472cc782016-01-11 22:14:42 +000083/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000084/// a vector with every element true, as appropriate for the type.
85static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000086 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000087 "Expected i1 type or a vector of i1!");
88 return Constant::getAllOnesValue(Ty);
89}
90
Duncan Sands3d5692a2011-10-30 19:56:36 +000091/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
92static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
93 Value *RHS) {
94 CmpInst *Cmp = dyn_cast<CmpInst>(V);
95 if (!Cmp)
96 return false;
97 CmpInst::Predicate CPred = Cmp->getPredicate();
98 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
99 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
100 return true;
101 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
102 CRHS == LHS;
103}
104
Sanjay Patel472cc782016-01-11 22:14:42 +0000105/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000106static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
107 Instruction *I = dyn_cast<Instruction>(V);
108 if (!I)
109 // Arguments and constants dominate all instructions.
110 return true;
111
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000112 // If we are processing instructions (and/or basic blocks) that have not been
113 // fully added to a function, the parent nodes may still be null. Simply
114 // return the conservative answer in these cases.
115 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
116 return false;
117
Duncan Sands5ffc2982010-11-16 12:16:38 +0000118 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000119 if (DT) {
120 if (!DT->isReachableFromEntry(P->getParent()))
121 return true;
122 if (!DT->isReachableFromEntry(I->getParent()))
123 return false;
124 return DT->dominates(I, P);
125 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000126
David Majnemer8a1c45d2015-12-12 05:38:55 +0000127 // Otherwise, if the instruction is in the entry block and is not an invoke,
128 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000129 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000130 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000131 return true;
132
133 return false;
134}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000135
Sanjay Patel472cc782016-01-11 22:14:42 +0000136/// Simplify "A op (B op' C)" by distributing op over op', turning it into
137/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000138/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
139/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
140/// Returns the simplified value, or null if no simplification was performed.
141static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000142 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000143 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000144 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000145 // Recursion is always used, so bail out at once if we already hit the limit.
146 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000147 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000148
149 // Check whether the expression has the form "(A op' B) op C".
150 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
151 if (Op0->getOpcode() == OpcodeToExpand) {
152 // It does! Try turning it into "(A op C) op' (B op C)".
153 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
154 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000155 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
156 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000157 // They do! Return "L op' R" if it simplifies or is already available.
158 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000159 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
160 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000161 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000162 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000163 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000164 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000165 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000166 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000167 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000168 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000169 }
170 }
171
172 // Check whether the expression has the form "A op (B op' C)".
173 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
174 if (Op1->getOpcode() == OpcodeToExpand) {
175 // It does! Try turning it into "(A op B) op' (A op C)".
176 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
177 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000178 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
179 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000180 // They do! Return "L op' R" if it simplifies or is already available.
181 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000182 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
183 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000184 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000185 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000186 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000187 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000188 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000189 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000190 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000191 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000192 }
193 }
194
Craig Topper9f008862014-04-15 04:59:12 +0000195 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000196}
197
Sanjay Patel472cc782016-01-11 22:14:42 +0000198/// Generic simplifications for associative binary operations.
199/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000200static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000201 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000202 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000203 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
204
205 // Recursion is always used, so bail out at once if we already hit the limit.
206 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000207 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000208
209 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
210 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
211
212 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
213 if (Op0 && Op0->getOpcode() == Opcode) {
214 Value *A = Op0->getOperand(0);
215 Value *B = Op0->getOperand(1);
216 Value *C = RHS;
217
218 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000219 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000220 // It does! Return "A op V" if it simplifies or is already available.
221 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000222 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000223 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000224 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000225 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000227 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000228 }
229 }
230
231 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
232 if (Op1 && Op1->getOpcode() == Opcode) {
233 Value *A = LHS;
234 Value *B = Op1->getOperand(0);
235 Value *C = Op1->getOperand(1);
236
237 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000238 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000239 // It does! Return "V op C" if it simplifies or is already available.
240 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000241 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000242 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000243 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000244 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000245 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000246 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000247 }
248 }
249
250 // The remaining transforms require commutativity as well as associativity.
251 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000252 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000253
254 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
255 if (Op0 && Op0->getOpcode() == Opcode) {
256 Value *A = Op0->getOperand(0);
257 Value *B = Op0->getOperand(1);
258 Value *C = RHS;
259
260 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000261 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000262 // It does! Return "V op B" if it simplifies or is already available.
263 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000264 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000265 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000266 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000267 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000269 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000270 }
271 }
272
273 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
274 if (Op1 && Op1->getOpcode() == Opcode) {
275 Value *A = LHS;
276 Value *B = Op1->getOperand(0);
277 Value *C = Op1->getOperand(1);
278
279 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000280 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000281 // It does! Return "B op V" if it simplifies or is already available.
282 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000283 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000284 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000285 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000286 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000287 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000288 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000289 }
290 }
291
Craig Topper9f008862014-04-15 04:59:12 +0000292 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000293}
294
Sanjay Patel472cc782016-01-11 22:14:42 +0000295/// In the case of a binary operation with a select instruction as an operand,
296/// try to simplify the binop by seeing whether evaluating it on both branches
297/// of the select results in the same value. Returns the common value if so,
298/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000299static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000300 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000301 // Recursion is always used, so bail out at once if we already hit the limit.
302 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000303 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000304
Duncan Sandsb0579e92010-11-10 13:00:08 +0000305 SelectInst *SI;
306 if (isa<SelectInst>(LHS)) {
307 SI = cast<SelectInst>(LHS);
308 } else {
309 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
310 SI = cast<SelectInst>(RHS);
311 }
312
313 // Evaluate the BinOp on the true and false branches of the select.
314 Value *TV;
315 Value *FV;
316 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000317 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
318 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000319 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000320 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
321 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000322 }
323
Duncan Sandse3c53952011-01-01 16:12:09 +0000324 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000325 // If they both failed to simplify then return null.
326 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000327 return TV;
328
329 // If one branch simplified to undef, return the other one.
330 if (TV && isa<UndefValue>(TV))
331 return FV;
332 if (FV && isa<UndefValue>(FV))
333 return TV;
334
335 // If applying the operation did not change the true and false select values,
336 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000337 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000338 return SI;
339
340 // If one branch simplified and the other did not, and the simplified
341 // value is equal to the unsimplified one, return the simplified value.
342 // For example, select (cond, X, X & Z) & Z -> X & Z.
343 if ((FV && !TV) || (TV && !FV)) {
344 // Check that the simplified value has the form "X op Y" where "op" is the
345 // same as the original operation.
346 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
347 if (Simplified && Simplified->getOpcode() == Opcode) {
348 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
349 // We already know that "op" is the same as for the simplified value. See
350 // if the operands match too. If so, return the simplified value.
351 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
352 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
353 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000354 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
355 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000356 return Simplified;
357 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000358 Simplified->getOperand(1) == UnsimplifiedLHS &&
359 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000360 return Simplified;
361 }
362 }
363
Craig Topper9f008862014-04-15 04:59:12 +0000364 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000365}
366
Sanjay Patel472cc782016-01-11 22:14:42 +0000367/// In the case of a comparison with a select instruction, try to simplify the
368/// comparison by seeing whether both branches of the select result in the same
369/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000370static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000371 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000372 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000373 // Recursion is always used, so bail out at once if we already hit the limit.
374 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000375 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000376
Duncan Sandsb0579e92010-11-10 13:00:08 +0000377 // Make sure the select is on the LHS.
378 if (!isa<SelectInst>(LHS)) {
379 std::swap(LHS, RHS);
380 Pred = CmpInst::getSwappedPredicate(Pred);
381 }
382 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
383 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000384 Value *Cond = SI->getCondition();
385 Value *TV = SI->getTrueValue();
386 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000387
Duncan Sands06504022011-02-03 09:37:39 +0000388 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000389 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000390 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000391 if (TCmp == Cond) {
392 // It not only simplified, it simplified to the select condition. Replace
393 // it with 'true'.
394 TCmp = getTrue(Cond->getType());
395 } else if (!TCmp) {
396 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
397 // condition then we can replace it with 'true'. Otherwise give up.
398 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000399 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000400 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000401 }
402
Duncan Sands3d5692a2011-10-30 19:56:36 +0000403 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000404 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000405 if (FCmp == Cond) {
406 // It not only simplified, it simplified to the select condition. Replace
407 // it with 'false'.
408 FCmp = getFalse(Cond->getType());
409 } else if (!FCmp) {
410 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
411 // condition then we can replace it with 'false'. Otherwise give up.
412 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000413 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000414 FCmp = getFalse(Cond->getType());
415 }
416
417 // If both sides simplified to the same value, then use it as the result of
418 // the original comparison.
419 if (TCmp == FCmp)
420 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000421
422 // The remaining cases only make sense if the select condition has the same
423 // type as the result of the comparison, so bail out if this is not so.
424 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000425 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000426 // If the false value simplified to false, then the result of the compare
427 // is equal to "Cond && TCmp". This also catches the case when the false
428 // value simplified to false and the true value to true, returning "Cond".
429 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000430 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000431 return V;
432 // If the true value simplified to true, then the result of the compare
433 // is equal to "Cond || FCmp".
434 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000435 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000436 return V;
437 // Finally, if the false value simplified to true and the true value to
438 // false, then the result of the compare is equal to "!Cond".
439 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
440 if (Value *V =
441 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000442 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000443 return V;
444
Craig Topper9f008862014-04-15 04:59:12 +0000445 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000446}
447
Sanjay Patel472cc782016-01-11 22:14:42 +0000448/// In the case of a binary operation with an operand that is a PHI instruction,
449/// try to simplify the binop by seeing whether evaluating it on the incoming
450/// phi values yields the same result for every value. If so returns the common
451/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000452static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000453 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000454 // Recursion is always used, so bail out at once if we already hit the limit.
455 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000456 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000457
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000458 PHINode *PI;
459 if (isa<PHINode>(LHS)) {
460 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000461 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000462 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000463 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000464 } else {
465 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
466 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000467 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000468 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000469 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000470 }
471
472 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000473 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000474 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000475 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000476 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000477 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000478 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
479 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000480 // If the operation failed to simplify, or simplified to a different value
481 // to previously, then give up.
482 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000483 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000484 CommonValue = V;
485 }
486
487 return CommonValue;
488}
489
Sanjay Patel472cc782016-01-11 22:14:42 +0000490/// In the case of a comparison with a PHI instruction, try to simplify the
491/// comparison by seeing whether comparing with all of the incoming phi values
492/// yields the same result every time. If so returns the common result,
493/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000494static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000495 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000496 // Recursion is always used, so bail out at once if we already hit the limit.
497 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000498 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000499
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000500 // Make sure the phi is on the LHS.
501 if (!isa<PHINode>(LHS)) {
502 std::swap(LHS, RHS);
503 Pred = CmpInst::getSwappedPredicate(Pred);
504 }
505 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
506 PHINode *PI = cast<PHINode>(LHS);
507
Duncan Sands5ffc2982010-11-16 12:16:38 +0000508 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000509 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000510 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000511
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000512 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000513 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000514 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000515 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000516 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000517 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000518 // If the operation failed to simplify, or simplified to a different value
519 // to previously, then give up.
520 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000521 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000522 CommonValue = V;
523 }
524
525 return CommonValue;
526}
527
Sanjay Patel472cc782016-01-11 22:14:42 +0000528/// Given operands for an Add, see if we can fold the result.
529/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000530static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000531 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000532 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000533 if (Constant *CRHS = dyn_cast<Constant>(Op1))
534 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000535
Chris Lattner3d9823b2009-11-27 17:42:22 +0000536 // Canonicalize the constant to the RHS.
537 std::swap(Op0, Op1);
538 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000539
Duncan Sands0a2c41682010-12-15 14:07:39 +0000540 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000541 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000542 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000543
Duncan Sands0a2c41682010-12-15 14:07:39 +0000544 // X + 0 -> X
545 if (match(Op1, m_Zero()))
546 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000547
Duncan Sands0a2c41682010-12-15 14:07:39 +0000548 // X + (Y - X) -> Y
549 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000550 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000551 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000552 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
553 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000554 return Y;
555
556 // X + ~X -> -1 since ~X = -X-1
Duncan Sands772749a2011-01-01 20:08:02 +0000557 if (match(Op0, m_Not(m_Specific(Op1))) ||
558 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000559 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000560
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000561 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000562 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000563 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000564 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000565
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000566 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000567 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000568 MaxRecurse))
569 return V;
570
Duncan Sandsb238de02010-11-19 09:20:39 +0000571 // Threading Add over selects and phi nodes is pointless, so don't bother.
572 // Threading over the select in "A + select(cond, B, C)" means evaluating
573 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
574 // only if B and C are equal. If B and C are equal then (since we assume
575 // that operands have already been simplified) "select(cond, B, C)" should
576 // have been simplified to the common value of B and C already. Analysing
577 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
578 // for threading over phi nodes.
579
Craig Topper9f008862014-04-15 04:59:12 +0000580 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000581}
582
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000583Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000584 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000585 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000586 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000587 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
588 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000589}
590
Chandler Carrutha0796552012-03-12 11:19:31 +0000591/// \brief Compute the base pointer and cumulative constant offsets for V.
592///
593/// This strips all constant offsets off of V, leaving it the base pointer, and
594/// accumulates the total constant offset applied in the returned constant. It
595/// returns 0 if V is not a pointer, and returns the constant '0' if there are
596/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000597///
598/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
599/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
600/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000601static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000602 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000603 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000604
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000605 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000606 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000607
608 // Even though we don't look through PHI nodes, we could be called on an
609 // instruction in an unreachable block, which may be on a cycle.
610 SmallPtrSet<Value *, 4> Visited;
611 Visited.insert(V);
612 do {
613 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000614 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000615 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000616 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000617 V = GEP->getPointerOperand();
618 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000619 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000620 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000621 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000622 break;
623 V = GA->getAliasee();
624 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000625 if (auto CS = CallSite(V))
626 if (Value *RV = CS.getReturnedArgOperand()) {
627 V = RV;
628 continue;
629 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000630 break;
631 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000632 assert(V->getType()->getScalarType()->isPointerTy() &&
633 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000634 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000635
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000636 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
637 if (V->getType()->isVectorTy())
638 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
639 OffsetIntPtr);
640 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000641}
642
643/// \brief Compute the constant difference between two pointer values.
644/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
646 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000647 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
648 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000649
650 // If LHS and RHS are not related via constant offsets to the same base
651 // value, there is nothing we can do here.
652 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000653 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000654
655 // Otherwise, the difference of LHS - RHS can be computed as:
656 // LHS - RHS
657 // = (LHSOffset + Base) - (RHSOffset + Base)
658 // = LHSOffset - RHSOffset
659 return ConstantExpr::getSub(LHSOffset, RHSOffset);
660}
661
Sanjay Patel472cc782016-01-11 22:14:42 +0000662/// Given operands for a Sub, see if we can fold the result.
663/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000664static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000665 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000666 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000667 if (Constant *CRHS = dyn_cast<Constant>(Op1))
668 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000669
670 // X - undef -> undef
671 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000672 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000673 return UndefValue::get(Op0->getType());
674
675 // X - 0 -> X
676 if (match(Op1, m_Zero()))
677 return Op0;
678
679 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000680 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000681 return Constant::getNullValue(Op0->getType());
682
David Majnemer4efa9ff2014-11-22 07:15:16 +0000683 // 0 - X -> 0 if the sub is NUW.
684 if (isNUW && match(Op0, m_Zero()))
685 return Op0;
David Majnemercd4fbcd2014-07-31 04:49:18 +0000686
Duncan Sands99589d02011-01-18 11:50:19 +0000687 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
688 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000689 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000690 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
691 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000692 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000693 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000694 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000695 // It does, we successfully reassociated!
696 ++NumReassoc;
697 return W;
698 }
699 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000700 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000701 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000702 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000703 // It does, we successfully reassociated!
704 ++NumReassoc;
705 return W;
706 }
707 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000708
Duncan Sands99589d02011-01-18 11:50:19 +0000709 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
710 // For example, X - (X + 1) -> -1
711 X = Op0;
712 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
713 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000714 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000715 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000716 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000717 // It does, we successfully reassociated!
718 ++NumReassoc;
719 return W;
720 }
721 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000722 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000723 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000724 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000725 // It does, we successfully reassociated!
726 ++NumReassoc;
727 return W;
728 }
729 }
730
731 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
732 // For example, X - (X - Y) -> Y.
733 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000734 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
735 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000736 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000737 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000738 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000739 // It does, we successfully reassociated!
740 ++NumReassoc;
741 return W;
742 }
743
Duncan Sands395ac42d2012-03-13 14:07:05 +0000744 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
745 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
746 match(Op1, m_Trunc(m_Value(Y))))
747 if (X->getType() == Y->getType())
748 // See if "V === X - Y" simplifies.
749 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
750 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000751 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
752 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000753 // It does, return the simplified "trunc V".
754 return W;
755
756 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000757 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000758 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000759 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000760 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
761
Duncan Sands99589d02011-01-18 11:50:19 +0000762 // i1 sub -> xor.
763 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000764 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000765 return V;
766
Duncan Sands0a2c41682010-12-15 14:07:39 +0000767 // Threading Sub over selects and phi nodes is pointless, so don't bother.
768 // Threading over the select in "A - select(cond, B, C)" means evaluating
769 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
770 // only if B and C are equal. If B and C are equal then (since we assume
771 // that operands have already been simplified) "select(cond, B, C)" should
772 // have been simplified to the common value of B and C already. Analysing
773 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
774 // for threading over phi nodes.
775
Craig Topper9f008862014-04-15 04:59:12 +0000776 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000777}
778
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000779Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000780 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000781 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000782 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000783 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
784 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000785}
786
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000787/// Given operands for an FAdd, see if we can fold the result. If not, this
788/// returns null.
789static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
790 const Query &Q, unsigned MaxRecurse) {
791 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000792 if (Constant *CRHS = dyn_cast<Constant>(Op1))
793 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000794
795 // Canonicalize the constant to the RHS.
796 std::swap(Op0, Op1);
797 }
798
799 // fadd X, -0 ==> X
800 if (match(Op1, m_NegZero()))
801 return Op0;
802
803 // fadd X, 0 ==> X, when we know X is not -0
804 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000805 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000806 return Op0;
807
808 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
809 // where nnan and ninf have to occur at least once somewhere in this
810 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000811 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000812 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
813 SubOp = Op1;
814 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
815 SubOp = Op0;
816 if (SubOp) {
817 Instruction *FSub = cast<Instruction>(SubOp);
818 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
819 (FMF.noInfs() || FSub->hasNoInfs()))
820 return Constant::getNullValue(Op0->getType());
821 }
822
Craig Topper9f008862014-04-15 04:59:12 +0000823 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000824}
825
826/// Given operands for an FSub, see if we can fold the result. If not, this
827/// returns null.
828static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
829 const Query &Q, unsigned MaxRecurse) {
830 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000831 if (Constant *CRHS = dyn_cast<Constant>(Op1))
832 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000833 }
834
835 // fsub X, 0 ==> X
836 if (match(Op1, m_Zero()))
837 return Op0;
838
839 // fsub X, -0 ==> X, when we know X is not -0
840 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000841 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000842 return Op0;
843
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000844 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000845 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000846 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
847 return X;
848
849 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000850 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000851 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
852 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000853
Benjamin Kramer228680d2015-06-14 21:01:20 +0000854 // fsub nnan x, x ==> 0.0
855 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000856 return Constant::getNullValue(Op0->getType());
857
Craig Topper9f008862014-04-15 04:59:12 +0000858 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000859}
860
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000861/// Given the operands for an FMul, see if we can fold the result
862static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
863 FastMathFlags FMF,
864 const Query &Q,
865 unsigned MaxRecurse) {
866 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000867 if (Constant *CRHS = dyn_cast<Constant>(Op1))
868 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000869
870 // Canonicalize the constant to the RHS.
871 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000872 }
873
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000874 // fmul X, 1.0 ==> X
875 if (match(Op1, m_FPOne()))
876 return Op0;
877
878 // fmul nnan nsz X, 0 ==> 0
879 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
880 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000881
Craig Topper9f008862014-04-15 04:59:12 +0000882 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000883}
884
Sanjay Patel472cc782016-01-11 22:14:42 +0000885/// Given operands for a Mul, see if we can fold the result.
886/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000887static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
888 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000889 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000890 if (Constant *CRHS = dyn_cast<Constant>(Op1))
891 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000892
893 // Canonicalize the constant to the RHS.
894 std::swap(Op0, Op1);
895 }
896
897 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000898 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000899 return Constant::getNullValue(Op0->getType());
900
901 // X * 0 -> 0
902 if (match(Op1, m_Zero()))
903 return Op1;
904
905 // X * 1 -> X
906 if (match(Op1, m_One()))
907 return Op0;
908
Duncan Sandsb67edc62011-01-30 18:03:50 +0000909 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000910 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000911 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
912 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
913 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000914
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000915 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000916 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000917 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000918 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000919
920 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000921 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000922 MaxRecurse))
923 return V;
924
925 // Mul distributes over Add. Try some generic simplifications based on this.
926 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000927 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000928 return V;
929
930 // If the operation is with the result of a select instruction, check whether
931 // operating on either branch of the select always yields the same value.
932 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000933 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000934 MaxRecurse))
935 return V;
936
937 // If the operation is with the result of a phi instruction, check whether
938 // operating on all incoming values of the phi always yields the same value.
939 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000940 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000941 MaxRecurse))
942 return V;
943
Craig Topper9f008862014-04-15 04:59:12 +0000944 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000945}
946
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000947Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000948 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000949 const TargetLibraryInfo *TLI,
950 const DominatorTree *DT, AssumptionCache *AC,
951 const Instruction *CxtI) {
952 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000953 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000954}
955
956Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000957 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000958 const TargetLibraryInfo *TLI,
959 const DominatorTree *DT, AssumptionCache *AC,
960 const Instruction *CxtI) {
961 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000962 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000963}
964
Chandler Carruth66b31302015-01-04 12:03:27 +0000965Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000966 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000967 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000968 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000969 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000970 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000971 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000972}
973
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000974Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000975 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +0000976 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000977 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000978 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000979 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000980}
981
Sanjay Patel472cc782016-01-11 22:14:42 +0000982/// Given operands for an SDiv or UDiv, see if we can fold the result.
983/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +0000984static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000985 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000986 if (Constant *C0 = dyn_cast<Constant>(Op0))
987 if (Constant *C1 = dyn_cast<Constant>(Op1))
988 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +0000989
Duncan Sands65995fa2011-01-28 18:50:50 +0000990 bool isSigned = Opcode == Instruction::SDiv;
991
Duncan Sands771e82a2011-01-28 16:51:11 +0000992 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000993 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +0000994 return Op1;
995
David Majnemer71dc8fb2014-12-10 07:52:18 +0000996 // X / 0 -> undef, we don't need to preserve faults!
997 if (match(Op1, m_Zero()))
998 return UndefValue::get(Op1->getType());
999
Duncan Sands771e82a2011-01-28 16:51:11 +00001000 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001001 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001002 return Constant::getNullValue(Op0->getType());
1003
1004 // 0 / X -> 0, we don't need to preserve faults!
1005 if (match(Op0, m_Zero()))
1006 return Op0;
1007
1008 // X / 1 -> X
1009 if (match(Op1, m_One()))
1010 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001011
1012 if (Op0->getType()->isIntegerTy(1))
1013 // It can't be division by zero, hence it must be division by one.
1014 return Op0;
1015
1016 // X / X -> 1
1017 if (Op0 == Op1)
1018 return ConstantInt::get(Op0->getType(), 1);
1019
1020 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001021 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001022 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1023 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001024 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001025 // If the Mul knows it does not overflow, then we are good to go.
1026 if ((isSigned && Mul->hasNoSignedWrap()) ||
1027 (!isSigned && Mul->hasNoUnsignedWrap()))
1028 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001029 // If X has the form X = A / Y then X * Y cannot overflow.
1030 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1031 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1032 return X;
1033 }
1034
Duncan Sands65995fa2011-01-28 18:50:50 +00001035 // (X rem Y) / Y -> 0
1036 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1037 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1038 return Constant::getNullValue(Op0->getType());
1039
David Majnemercb9d5962014-10-11 10:20:01 +00001040 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1041 ConstantInt *C1, *C2;
1042 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1043 match(Op1, m_ConstantInt(C2))) {
1044 bool Overflow;
1045 C1->getValue().umul_ov(C2->getValue(), Overflow);
1046 if (Overflow)
1047 return Constant::getNullValue(Op0->getType());
1048 }
1049
Duncan Sands65995fa2011-01-28 18:50:50 +00001050 // If the operation is with the result of a select instruction, check whether
1051 // operating on either branch of the select always yields the same value.
1052 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001053 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001054 return V;
1055
1056 // If the operation is with the result of a phi instruction, check whether
1057 // operating on all incoming values of the phi always yields the same value.
1058 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001059 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001060 return V;
1061
Craig Topper9f008862014-04-15 04:59:12 +00001062 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001063}
1064
Sanjay Patel472cc782016-01-11 22:14:42 +00001065/// Given operands for an SDiv, see if we can fold the result.
1066/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001067static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1068 unsigned MaxRecurse) {
1069 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001070 return V;
1071
Craig Topper9f008862014-04-15 04:59:12 +00001072 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001073}
1074
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001075Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001076 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001077 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001078 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001079 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001080 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001081}
1082
Sanjay Patel472cc782016-01-11 22:14:42 +00001083/// Given operands for a UDiv, see if we can fold the result.
1084/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001085static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1086 unsigned MaxRecurse) {
1087 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001088 return V;
1089
Craig Topper9f008862014-04-15 04:59:12 +00001090 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001091}
1092
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001093Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001094 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001095 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001096 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001097 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001098 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001099}
1100
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001101static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1102 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001103 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001104 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001105 return Op0;
1106
1107 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001108 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001109 return Op1;
1110
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001111 // 0 / X -> 0
1112 // Requires that NaNs are off (X could be zero) and signed zeroes are
1113 // ignored (X could be positive or negative, so the output sign is unknown).
1114 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1115 return Op0;
1116
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001117 if (FMF.noNaNs()) {
1118 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001119 if (Op0 == Op1)
1120 return ConstantFP::get(Op0->getType(), 1.0);
1121
1122 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001123 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001124 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1125 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1126 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1127 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1128 BinaryOperator::getFNegArgument(Op1) == Op0))
1129 return ConstantFP::get(Op0->getType(), -1.0);
1130 }
1131
Craig Topper9f008862014-04-15 04:59:12 +00001132 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001133}
1134
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001135Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001136 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001137 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001138 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001139 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001140 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001141 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001142}
1143
Sanjay Patel472cc782016-01-11 22:14:42 +00001144/// Given operands for an SRem or URem, see if we can fold the result.
1145/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001146static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001147 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001148 if (Constant *C0 = dyn_cast<Constant>(Op0))
1149 if (Constant *C1 = dyn_cast<Constant>(Op1))
1150 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001151
Duncan Sandsa3e36992011-05-02 16:27:02 +00001152 // X % undef -> undef
1153 if (match(Op1, m_Undef()))
1154 return Op1;
1155
1156 // undef % X -> 0
1157 if (match(Op0, m_Undef()))
1158 return Constant::getNullValue(Op0->getType());
1159
1160 // 0 % X -> 0, we don't need to preserve faults!
1161 if (match(Op0, m_Zero()))
1162 return Op0;
1163
1164 // X % 0 -> undef, we don't need to preserve faults!
1165 if (match(Op1, m_Zero()))
1166 return UndefValue::get(Op0->getType());
1167
1168 // X % 1 -> 0
1169 if (match(Op1, m_One()))
1170 return Constant::getNullValue(Op0->getType());
1171
1172 if (Op0->getType()->isIntegerTy(1))
1173 // It can't be remainder by zero, hence it must be remainder by one.
1174 return Constant::getNullValue(Op0->getType());
1175
1176 // X % X -> 0
1177 if (Op0 == Op1)
1178 return Constant::getNullValue(Op0->getType());
1179
David Majnemerb435a422014-09-17 04:16:35 +00001180 // (X % Y) % Y -> X % Y
1181 if ((Opcode == Instruction::SRem &&
1182 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1183 (Opcode == Instruction::URem &&
1184 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001185 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001186
Duncan Sandsa3e36992011-05-02 16:27:02 +00001187 // If the operation is with the result of a select instruction, check whether
1188 // operating on either branch of the select always yields the same value.
1189 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001190 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001191 return V;
1192
1193 // If the operation is with the result of a phi instruction, check whether
1194 // operating on all incoming values of the phi always yields the same value.
1195 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001196 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001197 return V;
1198
Craig Topper9f008862014-04-15 04:59:12 +00001199 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001200}
1201
Sanjay Patel472cc782016-01-11 22:14:42 +00001202/// Given operands for an SRem, see if we can fold the result.
1203/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001204static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1205 unsigned MaxRecurse) {
1206 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001207 return V;
1208
Craig Topper9f008862014-04-15 04:59:12 +00001209 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001210}
1211
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001212Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001213 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001214 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001215 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001216 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001217 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001218}
1219
Sanjay Patel472cc782016-01-11 22:14:42 +00001220/// Given operands for a URem, see if we can fold the result.
1221/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001222static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001223 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001224 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001225 return V;
1226
Craig Topper9f008862014-04-15 04:59:12 +00001227 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001228}
1229
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001230Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001231 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001232 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001233 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001234 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001235 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001236}
1237
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001238static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1239 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001240 // undef % X -> undef (the undef could be a snan).
1241 if (match(Op0, m_Undef()))
1242 return Op0;
1243
1244 // X % undef -> undef
1245 if (match(Op1, m_Undef()))
1246 return Op1;
1247
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001248 // 0 % X -> 0
1249 // Requires that NaNs are off (X could be zero) and signed zeroes are
1250 // ignored (X could be positive or negative, so the output sign is unknown).
1251 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1252 return Op0;
1253
Craig Topper9f008862014-04-15 04:59:12 +00001254 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001255}
1256
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001257Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001258 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001259 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001260 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001261 const Instruction *CxtI) {
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001262 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001263 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001264}
1265
Sanjay Patel472cc782016-01-11 22:14:42 +00001266/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001267static bool isUndefShift(Value *Amount) {
1268 Constant *C = dyn_cast<Constant>(Amount);
1269 if (!C)
1270 return false;
1271
1272 // X shift by undef -> undef because it may shift by the bitwidth.
1273 if (isa<UndefValue>(C))
1274 return true;
1275
1276 // Shifting by the bitwidth or more is undefined.
1277 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1278 if (CI->getValue().getLimitedValue() >=
1279 CI->getType()->getScalarSizeInBits())
1280 return true;
1281
1282 // If all lanes of a vector shift are undefined the whole shift is.
1283 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1284 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1285 if (!isUndefShift(C->getAggregateElement(I)))
1286 return false;
1287 return true;
1288 }
1289
1290 return false;
1291}
1292
Sanjay Patel472cc782016-01-11 22:14:42 +00001293/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1294/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001295static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001296 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001297 if (Constant *C0 = dyn_cast<Constant>(Op0))
1298 if (Constant *C1 = dyn_cast<Constant>(Op1))
1299 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001300
Duncan Sands571fd9a2011-01-14 14:44:12 +00001301 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001302 if (match(Op0, m_Zero()))
1303 return Op0;
1304
Duncan Sands571fd9a2011-01-14 14:44:12 +00001305 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001306 if (match(Op1, m_Zero()))
1307 return Op0;
1308
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001309 // Fold undefined shifts.
1310 if (isUndefShift(Op1))
1311 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001312
Duncan Sands571fd9a2011-01-14 14:44:12 +00001313 // If the operation is with the result of a select instruction, check whether
1314 // operating on either branch of the select always yields the same value.
1315 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001316 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001317 return V;
1318
1319 // If the operation is with the result of a phi instruction, check whether
1320 // operating on all incoming values of the phi always yields the same value.
1321 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001322 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001323 return V;
1324
Sanjay Patel6786bc52016-05-10 20:46:54 +00001325 // If any bits in the shift amount make that value greater than or equal to
1326 // the number of bits in the type, the shift is undefined.
1327 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1328 APInt KnownZero(BitWidth, 0);
1329 APInt KnownOne(BitWidth, 0);
1330 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1331 if (KnownOne.getLimitedValue() >= BitWidth)
1332 return UndefValue::get(Op0->getType());
1333
1334 // If all valid bits in the shift amount are known zero, the first operand is
1335 // unchanged.
1336 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1337 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1338 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1339 return Op0;
1340
Craig Topper9f008862014-04-15 04:59:12 +00001341 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001342}
1343
David Majnemerbf7550e2014-11-05 00:59:59 +00001344/// \brief Given operands for an Shl, LShr or AShr, see if we can
1345/// fold the result. If not, this returns null.
1346static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1347 bool isExact, const Query &Q,
1348 unsigned MaxRecurse) {
1349 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1350 return V;
1351
1352 // X >> X -> 0
1353 if (Op0 == Op1)
1354 return Constant::getNullValue(Op0->getType());
1355
David Majnemer65c52ae2014-12-17 01:54:33 +00001356 // undef >> X -> 0
1357 // undef >> X -> undef (if it's exact)
1358 if (match(Op0, m_Undef()))
1359 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1360
David Majnemerbf7550e2014-11-05 00:59:59 +00001361 // The low bit cannot be shifted out of an exact shift if it is set.
1362 if (isExact) {
1363 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1364 APInt Op0KnownZero(BitWidth, 0);
1365 APInt Op0KnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00001366 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1367 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001368 if (Op0KnownOne[0])
1369 return Op0;
1370 }
1371
1372 return nullptr;
1373}
1374
Sanjay Patel472cc782016-01-11 22:14:42 +00001375/// Given operands for an Shl, see if we can fold the result.
1376/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001377static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001378 const Query &Q, unsigned MaxRecurse) {
1379 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001380 return V;
1381
1382 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001383 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001384 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001385 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001386
Chris Lattner9e4aa022011-02-09 17:15:04 +00001387 // (X >> A) << A -> X
1388 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001389 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001390 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001391 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001392}
1393
Chris Lattner9e4aa022011-02-09 17:15:04 +00001394Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001395 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001396 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001397 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001398 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001399 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001400}
1401
Sanjay Patel472cc782016-01-11 22:14:42 +00001402/// Given operands for an LShr, see if we can fold the result.
1403/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001404static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001405 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001406 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1407 MaxRecurse))
1408 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001409
Chris Lattner9e4aa022011-02-09 17:15:04 +00001410 // (X << A) >> A -> X
1411 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001412 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001413 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001414
Craig Topper9f008862014-04-15 04:59:12 +00001415 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001416}
1417
Chris Lattner9e4aa022011-02-09 17:15:04 +00001418Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001419 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001420 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001421 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001422 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001423 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001424 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001425}
1426
Sanjay Patel472cc782016-01-11 22:14:42 +00001427/// Given operands for an AShr, see if we can fold the result.
1428/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001429static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001430 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001431 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1432 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001433 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001434
1435 // all ones >>a X -> all ones
1436 if (match(Op0, m_AllOnes()))
1437 return Op0;
1438
Chris Lattner9e4aa022011-02-09 17:15:04 +00001439 // (X << A) >> A -> X
1440 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001441 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001442 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001443
Suyog Sarda68862412014-07-17 06:28:15 +00001444 // Arithmetic shifting an all-sign-bit value is a no-op.
Chandler Carruth66b31302015-01-04 12:03:27 +00001445 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001446 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1447 return Op0;
1448
Craig Topper9f008862014-04-15 04:59:12 +00001449 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001450}
1451
Chris Lattner9e4aa022011-02-09 17:15:04 +00001452Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001453 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001454 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001455 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001456 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001457 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001458 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001459}
1460
David Majnemer1af36e52014-12-06 10:51:40 +00001461static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1462 ICmpInst *UnsignedICmp, bool IsAnd) {
1463 Value *X, *Y;
1464
1465 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001466 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1467 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001468 return nullptr;
1469
1470 ICmpInst::Predicate UnsignedPred;
1471 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1472 ICmpInst::isUnsigned(UnsignedPred))
1473 ;
1474 else if (match(UnsignedICmp,
1475 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1476 ICmpInst::isUnsigned(UnsignedPred))
1477 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1478 else
1479 return nullptr;
1480
1481 // X < Y && Y != 0 --> X < Y
1482 // X < Y || Y != 0 --> Y != 0
1483 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1484 return IsAnd ? UnsignedICmp : ZeroICmp;
1485
1486 // X >= Y || Y != 0 --> true
1487 // X >= Y || Y == 0 --> X >= Y
1488 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1489 if (EqPred == ICmpInst::ICMP_NE)
1490 return getTrue(UnsignedICmp->getType());
1491 return UnsignedICmp;
1492 }
1493
David Majnemerd5b3aa42014-12-08 18:30:43 +00001494 // X < Y && Y == 0 --> false
1495 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1496 IsAnd)
1497 return getFalse(UnsignedICmp->getType());
1498
David Majnemer1af36e52014-12-06 10:51:40 +00001499 return nullptr;
1500}
1501
David Majnemera315bd82014-09-15 08:15:28 +00001502static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001503 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1504 return X;
1505
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001506 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001507 Type *ITy = Op0->getType();
1508 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001509 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001510 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001511 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1512 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1513 // Make a constant range that's the intersection of the two icmp ranges.
1514 // If the intersection is empty, we know that the result is false.
1515 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1516 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1517 if (Range0.intersectWith(Range1).isEmptySet())
1518 return getFalse(ITy);
1519 }
1520
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001521 // (icmp (add V, C0), C1) & (icmp V, C0)
1522 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001523 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001524
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001525 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001526 return nullptr;
1527
David Majnemera315bd82014-09-15 08:15:28 +00001528 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001529 if (AddInst->getOperand(1) != Op1->getOperand(1))
1530 return nullptr;
1531
David Majnemera315bd82014-09-15 08:15:28 +00001532 bool isNSW = AddInst->hasNoSignedWrap();
1533 bool isNUW = AddInst->hasNoUnsignedWrap();
1534
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001535 const APInt Delta = *C1 - *C0;
1536 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001537 if (Delta == 2) {
1538 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1539 return getFalse(ITy);
1540 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1541 return getFalse(ITy);
1542 }
1543 if (Delta == 1) {
1544 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1545 return getFalse(ITy);
1546 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1547 return getFalse(ITy);
1548 }
1549 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001550 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001551 if (Delta == 2)
1552 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1553 return getFalse(ITy);
1554 if (Delta == 1)
1555 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1556 return getFalse(ITy);
1557 }
1558
1559 return nullptr;
1560}
1561
Sanjay Patel472cc782016-01-11 22:14:42 +00001562/// Given operands for an And, see if we can fold the result.
1563/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001564static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001565 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001566 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001567 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1568 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001569
Chris Lattnera71e9d62009-11-10 00:55:12 +00001570 // Canonicalize the constant to the RHS.
1571 std::swap(Op0, Op1);
1572 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001573
Chris Lattnera71e9d62009-11-10 00:55:12 +00001574 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001575 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001576 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001577
Chris Lattnera71e9d62009-11-10 00:55:12 +00001578 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001579 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001580 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001581
Duncan Sandsc89ac072010-11-17 18:52:15 +00001582 // X & 0 = 0
1583 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001584 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001585
Duncan Sandsc89ac072010-11-17 18:52:15 +00001586 // X & -1 = X
1587 if (match(Op1, m_AllOnes()))
1588 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001589
Chris Lattnera71e9d62009-11-10 00:55:12 +00001590 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001591 if (match(Op0, m_Not(m_Specific(Op1))) ||
1592 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001593 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001594
Chris Lattnera71e9d62009-11-10 00:55:12 +00001595 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001596 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001597 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001598 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001599 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001600
Chris Lattnera71e9d62009-11-10 00:55:12 +00001601 // A & (A | ?) = A
1602 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001603 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001604 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001605
Duncan Sandsba286d72011-10-26 20:55:21 +00001606 // A & (-A) = A if A is a power of two or zero.
1607 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1608 match(Op1, m_Neg(m_Specific(Op0)))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001609 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1610 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001611 return Op0;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001612 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1613 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001614 return Op1;
1615 }
1616
David Majnemera315bd82014-09-15 08:15:28 +00001617 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1618 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1619 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1620 return V;
1621 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1622 return V;
1623 }
1624 }
1625
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001626 // The compares may be hidden behind casts. Look through those and try the
1627 // same folds as above.
1628 auto *Cast0 = dyn_cast<CastInst>(Op0);
1629 auto *Cast1 = dyn_cast<CastInst>(Op1);
1630 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1631 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1632 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1633 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1634 if (Cmp0 && Cmp1) {
1635 Instruction::CastOps CastOpc = Cast0->getOpcode();
1636 Type *ResultType = Cast0->getType();
1637 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1638 return ConstantExpr::getCast(CastOpc, V, ResultType);
1639 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1640 return ConstantExpr::getCast(CastOpc, V, ResultType);
1641 }
1642 }
1643
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001644 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001645 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1646 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001647 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001648
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001649 // And distributes over Or. Try some generic simplifications based on this.
1650 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001651 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001652 return V;
1653
1654 // And distributes over Xor. Try some generic simplifications based on this.
1655 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001656 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001657 return V;
1658
Duncan Sandsb0579e92010-11-10 13:00:08 +00001659 // If the operation is with the result of a select instruction, check whether
1660 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001661 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001662 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1663 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001664 return V;
1665
1666 // If the operation is with the result of a phi instruction, check whether
1667 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001668 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001669 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001670 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001671 return V;
1672
Craig Topper9f008862014-04-15 04:59:12 +00001673 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001674}
1675
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001676Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001677 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001678 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001679 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001680 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001681 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001682}
1683
Sanjay Patel472cc782016-01-11 22:14:42 +00001684/// Simplify (or (icmp ...) (icmp ...)) to true when we can tell that the union
1685/// contains all possible values.
David Majnemera315bd82014-09-15 08:15:28 +00001686static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001687 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1688 return X;
1689
Sanjay Patel220a8732016-09-28 14:27:21 +00001690 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001691 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001692 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001693 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001694 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001695 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001696
Sanjay Patel220a8732016-09-28 14:27:21 +00001697 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1698 return nullptr;
1699
1700 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1701 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001702 return nullptr;
1703
1704 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001705 bool isNSW = AddInst->hasNoSignedWrap();
1706 bool isNUW = AddInst->hasNoUnsignedWrap();
1707
Sanjay Patel220a8732016-09-28 14:27:21 +00001708 const APInt Delta = *C1 - *C0;
1709 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001710 if (Delta == 2) {
1711 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1712 return getTrue(ITy);
1713 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1714 return getTrue(ITy);
1715 }
1716 if (Delta == 1) {
1717 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1718 return getTrue(ITy);
1719 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1720 return getTrue(ITy);
1721 }
1722 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001723 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001724 if (Delta == 2)
1725 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1726 return getTrue(ITy);
1727 if (Delta == 1)
1728 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1729 return getTrue(ITy);
1730 }
1731
1732 return nullptr;
1733}
1734
Sanjay Patel472cc782016-01-11 22:14:42 +00001735/// Given operands for an Or, see if we can fold the result.
1736/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001737static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1738 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001739 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001740 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1741 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001742
Chris Lattnera71e9d62009-11-10 00:55:12 +00001743 // Canonicalize the constant to the RHS.
1744 std::swap(Op0, Op1);
1745 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001746
Chris Lattnera71e9d62009-11-10 00:55:12 +00001747 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001748 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001749 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001750
Chris Lattnera71e9d62009-11-10 00:55:12 +00001751 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001752 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001753 return Op0;
1754
Duncan Sandsc89ac072010-11-17 18:52:15 +00001755 // X | 0 = X
1756 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001757 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001758
Duncan Sandsc89ac072010-11-17 18:52:15 +00001759 // X | -1 = -1
1760 if (match(Op1, m_AllOnes()))
1761 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001762
Chris Lattnera71e9d62009-11-10 00:55:12 +00001763 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001764 if (match(Op0, m_Not(m_Specific(Op1))) ||
1765 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001766 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001767
Chris Lattnera71e9d62009-11-10 00:55:12 +00001768 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001769 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001770 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001771 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001772 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001773
Chris Lattnera71e9d62009-11-10 00:55:12 +00001774 // A | (A & ?) = A
1775 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001776 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001777 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001778
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001779 // ~(A & ?) | A = -1
1780 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1781 (A == Op1 || B == Op1))
1782 return Constant::getAllOnesValue(Op1->getType());
1783
1784 // A | ~(A & ?) = -1
1785 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1786 (A == Op0 || B == Op0))
1787 return Constant::getAllOnesValue(Op0->getType());
1788
David Majnemera315bd82014-09-15 08:15:28 +00001789 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1790 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1791 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1792 return V;
1793 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1794 return V;
1795 }
1796 }
1797
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001798 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001799 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1800 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001801 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001802
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001803 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001804 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1805 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001806 return V;
1807
Duncan Sandsb0579e92010-11-10 13:00:08 +00001808 // If the operation is with the result of a select instruction, check whether
1809 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001810 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001811 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001812 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001813 return V;
1814
Nick Lewycky8561a492014-06-19 03:51:46 +00001815 // (A & C)|(B & D)
1816 Value *C = nullptr, *D = nullptr;
1817 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1818 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1819 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1820 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1821 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1822 // (A & C1)|(B & C2)
1823 // If we have: ((V + N) & C1) | (V & C2)
1824 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1825 // replace with V+N.
1826 Value *V1, *V2;
1827 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1828 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1829 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001830 if (V1 == B &&
1831 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001832 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001833 if (V2 == B &&
1834 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001835 return A;
1836 }
1837 // Or commutes, try both ways.
1838 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1839 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1840 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001841 if (V1 == A &&
1842 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001843 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001844 if (V2 == A &&
1845 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001846 return B;
1847 }
1848 }
1849 }
1850
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001851 // If the operation is with the result of a phi instruction, check whether
1852 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001853 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001854 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001855 return V;
1856
Craig Topper9f008862014-04-15 04:59:12 +00001857 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001858}
1859
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001860Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001861 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001862 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001863 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001864 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001865 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001866}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001867
Sanjay Patel472cc782016-01-11 22:14:42 +00001868/// Given operands for a Xor, see if we can fold the result.
1869/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001870static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1871 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001872 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001873 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1874 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001875
1876 // Canonicalize the constant to the RHS.
1877 std::swap(Op0, Op1);
1878 }
1879
1880 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001881 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001882 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001883
1884 // A ^ 0 = A
1885 if (match(Op1, m_Zero()))
1886 return Op0;
1887
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001888 // A ^ A = 0
1889 if (Op0 == Op1)
1890 return Constant::getNullValue(Op0->getType());
1891
Duncan Sandsc89ac072010-11-17 18:52:15 +00001892 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001893 if (match(Op0, m_Not(m_Specific(Op1))) ||
1894 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001895 return Constant::getAllOnesValue(Op0->getType());
1896
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001897 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001898 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1899 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001900 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001901
Duncan Sandsb238de02010-11-19 09:20:39 +00001902 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1903 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1904 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1905 // only if B and C are equal. If B and C are equal then (since we assume
1906 // that operands have already been simplified) "select(cond, B, C)" should
1907 // have been simplified to the common value of B and C already. Analysing
1908 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1909 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001910
Craig Topper9f008862014-04-15 04:59:12 +00001911 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001912}
1913
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001914Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001915 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00001916 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001917 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00001918 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001919 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001920}
1921
Chris Lattner229907c2011-07-18 04:54:35 +00001922static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001923 return CmpInst::makeCmpResultType(Op->getType());
1924}
1925
Sanjay Patel472cc782016-01-11 22:14:42 +00001926/// Rummage around inside V looking for something equivalent to the comparison
1927/// "LHS Pred RHS". Return such a value if found, otherwise return null.
1928/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00001929static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1930 Value *LHS, Value *RHS) {
1931 SelectInst *SI = dyn_cast<SelectInst>(V);
1932 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001933 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001934 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1935 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001936 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001937 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1938 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1939 return Cmp;
1940 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1941 LHS == CmpRHS && RHS == CmpLHS)
1942 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001943 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001944}
1945
Dan Gohman9631d902013-02-01 00:49:06 +00001946// A significant optimization not implemented here is assuming that alloca
1947// addresses are not equal to incoming argument values. They don't *alias*,
1948// as we say, but that doesn't mean they aren't equal, so we take a
1949// conservative approach.
1950//
1951// This is inspired in part by C++11 5.10p1:
1952// "Two pointers of the same type compare equal if and only if they are both
1953// null, both point to the same function, or both represent the same
1954// address."
1955//
1956// This is pretty permissive.
1957//
1958// It's also partly due to C11 6.5.9p6:
1959// "Two pointers compare equal if and only if both are null pointers, both are
1960// pointers to the same object (including a pointer to an object and a
1961// subobject at its beginning) or function, both are pointers to one past the
1962// last element of the same array object, or one is a pointer to one past the
1963// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001964// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001965// object in the address space.)
1966//
1967// C11's version is more restrictive, however there's no reason why an argument
1968// couldn't be a one-past-the-end value for a stack object in the caller and be
1969// equal to the beginning of a stack object in the callee.
1970//
1971// If the C and C++ standards are ever made sufficiently restrictive in this
1972// area, it may be possible to update LLVM's semantics accordingly and reinstate
1973// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00001974static Constant *
1975computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
1976 const DominatorTree *DT, CmpInst::Predicate Pred,
1977 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001978 // First, skip past any trivial no-ops.
1979 LHS = LHS->stripPointerCasts();
1980 RHS = RHS->stripPointerCasts();
1981
1982 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00001983 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00001984 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1985 return ConstantInt::get(GetCompareTy(LHS),
1986 !CmpInst::isTrueWhenEqual(Pred));
1987
Chandler Carruth8059c842012-03-25 21:28:14 +00001988 // We can only fold certain predicates on pointer comparisons.
1989 switch (Pred) {
1990 default:
Craig Topper9f008862014-04-15 04:59:12 +00001991 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00001992
1993 // Equality comaprisons are easy to fold.
1994 case CmpInst::ICMP_EQ:
1995 case CmpInst::ICMP_NE:
1996 break;
1997
1998 // We can only handle unsigned relational comparisons because 'inbounds' on
1999 // a GEP only protects against unsigned wrapping.
2000 case CmpInst::ICMP_UGT:
2001 case CmpInst::ICMP_UGE:
2002 case CmpInst::ICMP_ULT:
2003 case CmpInst::ICMP_ULE:
2004 // However, we have to switch them to their signed variants to handle
2005 // negative indices from the base pointer.
2006 Pred = ICmpInst::getSignedPredicate(Pred);
2007 break;
2008 }
2009
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002010 // Strip off any constant offsets so that we can reason about them.
2011 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2012 // here and compare base addresses like AliasAnalysis does, however there are
2013 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2014 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2015 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002016 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2017 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002018
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002019 // If LHS and RHS are related via constant offsets to the same base
2020 // value, we can replace it with an icmp which just compares the offsets.
2021 if (LHS == RHS)
2022 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002023
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002024 // Various optimizations for (in)equality comparisons.
2025 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2026 // Different non-empty allocations that exist at the same time have
2027 // different addresses (if the program can tell). Global variables always
2028 // exist, so they always exist during the lifetime of each other and all
2029 // allocas. Two different allocas usually have different addresses...
2030 //
2031 // However, if there's an @llvm.stackrestore dynamically in between two
2032 // allocas, they may have the same address. It's tempting to reduce the
2033 // scope of the problem by only looking at *static* allocas here. That would
2034 // cover the majority of allocas while significantly reducing the likelihood
2035 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2036 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2037 // an entry block. Also, if we have a block that's not attached to a
2038 // function, we can't tell if it's "static" under the current definition.
2039 // Theoretically, this problem could be fixed by creating a new kind of
2040 // instruction kind specifically for static allocas. Such a new instruction
2041 // could be required to be at the top of the entry block, thus preventing it
2042 // from being subject to a @llvm.stackrestore. Instcombine could even
2043 // convert regular allocas into these special allocas. It'd be nifty.
2044 // However, until then, this problem remains open.
2045 //
2046 // So, we'll assume that two non-empty allocas have different addresses
2047 // for now.
2048 //
2049 // With all that, if the offsets are within the bounds of their allocations
2050 // (and not one-past-the-end! so we can't use inbounds!), and their
2051 // allocations aren't the same, the pointers are not equal.
2052 //
2053 // Note that it's not necessary to check for LHS being a global variable
2054 // address, due to canonicalization and constant folding.
2055 if (isa<AllocaInst>(LHS) &&
2056 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002057 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2058 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002059 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002060 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002061 getObjectSize(LHS, LHSSize, DL, TLI) &&
2062 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002063 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2064 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002065 if (!LHSOffsetValue.isNegative() &&
2066 !RHSOffsetValue.isNegative() &&
2067 LHSOffsetValue.ult(LHSSize) &&
2068 RHSOffsetValue.ult(RHSSize)) {
2069 return ConstantInt::get(GetCompareTy(LHS),
2070 !CmpInst::isTrueWhenEqual(Pred));
2071 }
2072 }
2073
2074 // Repeat the above check but this time without depending on DataLayout
2075 // or being able to compute a precise size.
2076 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2077 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2078 LHSOffset->isNullValue() &&
2079 RHSOffset->isNullValue())
2080 return ConstantInt::get(GetCompareTy(LHS),
2081 !CmpInst::isTrueWhenEqual(Pred));
2082 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002083
2084 // Even if an non-inbounds GEP occurs along the path we can still optimize
2085 // equality comparisons concerning the result. We avoid walking the whole
2086 // chain again by starting where the last calls to
2087 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002088 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2089 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002090 if (LHS == RHS)
2091 return ConstantExpr::getICmp(Pred,
2092 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2093 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002094
2095 // If one side of the equality comparison must come from a noalias call
2096 // (meaning a system memory allocation function), and the other side must
2097 // come from a pointer that cannot overlap with dynamically-allocated
2098 // memory within the lifetime of the current function (allocas, byval
2099 // arguments, globals), then determine the comparison result here.
2100 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2101 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2102 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2103
2104 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002105 auto IsNAC = [](ArrayRef<Value *> Objects) {
2106 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002107 };
2108
2109 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002110 // noalias calls. For allocas, we consider only static ones (dynamic
2111 // allocas might be transformed into calls to malloc not simultaneously
2112 // live with the compared-to allocation). For globals, we exclude symbols
2113 // that might be resolve lazily to symbols in another dynamically-loaded
2114 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002115 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2116 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002117 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2118 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2119 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2120 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002121 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002122 !GV->isThreadLocal();
2123 if (const Argument *A = dyn_cast<Argument>(V))
2124 return A->hasByValAttr();
2125 return false;
2126 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002127 };
2128
2129 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2130 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2131 return ConstantInt::get(GetCompareTy(LHS),
2132 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002133
2134 // Fold comparisons for non-escaping pointer even if the allocation call
2135 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2136 // dynamic allocation call could be either of the operands.
2137 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002138 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002139 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002140 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002141 MI = RHS;
2142 // FIXME: We should also fold the compare when the pointer escapes, but the
2143 // compare dominates the pointer escape
2144 if (MI && !PointerMayBeCaptured(MI, true, true))
2145 return ConstantInt::get(GetCompareTy(LHS),
2146 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002147 }
2148
2149 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002150 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002151}
Chris Lattner01990f02012-02-24 19:01:58 +00002152
Sanjay Patel67bde282016-08-22 23:12:02 +00002153static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2154 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002155 const APInt *C;
2156 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002157 return nullptr;
2158
2159 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002160 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002161 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002162 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002163 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002164 return ConstantInt::getTrue(GetCompareTy(RHS));
2165
Sanjay Patel67bde282016-08-22 23:12:02 +00002166 // Many binary operators with constant RHS have easy to compute constant
2167 // range. Use them to check whether the comparison is a tautology.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002168 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002169 APInt Lower = APInt(Width, 0);
2170 APInt Upper = APInt(Width, 0);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002171 const APInt *C2;
2172 if (match(LHS, m_URem(m_Value(), m_APInt(C2)))) {
2173 // 'urem x, C2' produces [0, C2).
2174 Upper = *C2;
2175 } else if (match(LHS, m_SRem(m_Value(), m_APInt(C2)))) {
2176 // 'srem x, C2' produces (-|C2|, |C2|).
2177 Upper = C2->abs();
Sanjay Patel67bde282016-08-22 23:12:02 +00002178 Lower = (-Upper) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002179 } else if (match(LHS, m_UDiv(m_APInt(C2), m_Value()))) {
2180 // 'udiv C2, x' produces [0, C2].
2181 Upper = *C2 + 1;
2182 } else if (match(LHS, m_UDiv(m_Value(), m_APInt(C2)))) {
2183 // 'udiv x, C2' produces [0, UINT_MAX / C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002184 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002185 if (*C2 != 0)
2186 Upper = NegOne.udiv(*C2) + 1;
2187 } else if (match(LHS, m_SDiv(m_APInt(C2), m_Value()))) {
2188 if (C2->isMinSignedValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002189 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002190 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002191 Upper = Lower.lshr(1) + 1;
2192 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002193 // 'sdiv C2, x' produces [-|C2|, |C2|].
2194 Upper = C2->abs() + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002195 Lower = (-Upper) + 1;
2196 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002197 } else if (match(LHS, m_SDiv(m_Value(), m_APInt(C2)))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002198 APInt IntMin = APInt::getSignedMinValue(Width);
2199 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002200 if (C2->isAllOnesValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002201 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002202 // where C2 != -1 and C2 != 0 and C2 != 1
Sanjay Patel67bde282016-08-22 23:12:02 +00002203 Lower = IntMin + 1;
2204 Upper = IntMax + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002205 } else if (C2->countLeadingZeros() < Width - 1) {
2206 // 'sdiv x, C2' produces [INT_MIN / C2, INT_MAX / C2]
2207 // where C2 != -1 and C2 != 0 and C2 != 1
2208 Lower = IntMin.sdiv(*C2);
2209 Upper = IntMax.sdiv(*C2);
Sanjay Patel67bde282016-08-22 23:12:02 +00002210 if (Lower.sgt(Upper))
2211 std::swap(Lower, Upper);
2212 Upper = Upper + 1;
2213 assert(Upper != Lower && "Upper part of range has wrapped!");
2214 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002215 } else if (match(LHS, m_NUWShl(m_APInt(C2), m_Value()))) {
2216 // 'shl nuw C2, x' produces [C2, C2 << CLZ(C2)]
2217 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002218 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002219 } else if (match(LHS, m_NSWShl(m_APInt(C2), m_Value()))) {
2220 if (C2->isNegative()) {
2221 // 'shl nsw C2, x' produces [C2 << CLO(C2)-1, C2]
2222 unsigned ShiftAmount = C2->countLeadingOnes() - 1;
2223 Lower = C2->shl(ShiftAmount);
2224 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002225 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002226 // 'shl nsw C2, x' produces [C2, C2 << CLZ(C2)-1]
2227 unsigned ShiftAmount = C2->countLeadingZeros() - 1;
2228 Lower = *C2;
2229 Upper = C2->shl(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002230 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002231 } else if (match(LHS, m_LShr(m_Value(), m_APInt(C2)))) {
2232 // 'lshr x, C2' produces [0, UINT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002233 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002234 if (C2->ult(Width))
2235 Upper = NegOne.lshr(*C2) + 1;
2236 } else if (match(LHS, m_LShr(m_APInt(C2), m_Value()))) {
2237 // 'lshr C2, x' produces [C2 >> (Width-1), C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002238 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002239 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2240 ShiftAmount = C2->countTrailingZeros();
2241 Lower = C2->lshr(ShiftAmount);
2242 Upper = *C2 + 1;
2243 } else if (match(LHS, m_AShr(m_Value(), m_APInt(C2)))) {
2244 // 'ashr x, C2' produces [INT_MIN >> C2, INT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002245 APInt IntMin = APInt::getSignedMinValue(Width);
2246 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002247 if (C2->ult(Width)) {
2248 Lower = IntMin.ashr(*C2);
2249 Upper = IntMax.ashr(*C2) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002250 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002251 } else if (match(LHS, m_AShr(m_APInt(C2), m_Value()))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002252 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002253 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2254 ShiftAmount = C2->countTrailingZeros();
2255 if (C2->isNegative()) {
2256 // 'ashr C2, x' produces [C2, C2 >> (Width-1)]
2257 Lower = *C2;
2258 Upper = C2->ashr(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002259 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002260 // 'ashr C2, x' produces [C2 >> (Width-1), C2]
2261 Lower = C2->ashr(ShiftAmount);
2262 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002263 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002264 } else if (match(LHS, m_Or(m_Value(), m_APInt(C2)))) {
2265 // 'or x, C2' produces [C2, UINT_MAX].
2266 Lower = *C2;
2267 } else if (match(LHS, m_And(m_Value(), m_APInt(C2)))) {
2268 // 'and x, C2' produces [0, C2].
2269 Upper = *C2 + 1;
2270 } else if (match(LHS, m_NUWAdd(m_Value(), m_APInt(C2)))) {
2271 // 'add nuw x, C2' produces [C2, UINT_MAX].
2272 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002273 }
2274
2275 ConstantRange LHS_CR =
2276 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2277
2278 if (auto *I = dyn_cast<Instruction>(LHS))
2279 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2280 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2281
2282 if (!LHS_CR.isFullSet()) {
2283 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002284 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002285 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002286 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002287 }
2288
2289 return nullptr;
2290}
2291
Sanjay Patel472cc782016-01-11 22:14:42 +00002292/// Given operands for an ICmpInst, see if we can fold the result.
2293/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00002294static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00002295 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00002296 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00002297 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00002298
Chris Lattnera71e9d62009-11-10 00:55:12 +00002299 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00002300 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002301 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00002302
2303 // If we have a constant, make sure it is on the RHS.
2304 std::swap(LHS, RHS);
2305 Pred = CmpInst::getSwappedPredicate(Pred);
2306 }
Duncan Sands7e800d62010-11-14 11:23:23 +00002307
Chris Lattner229907c2011-07-18 04:54:35 +00002308 Type *ITy = GetCompareTy(LHS); // The return type.
2309 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands7e800d62010-11-14 11:23:23 +00002310
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002311 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00002312 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
2313 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00002314 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002315 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00002316
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002317 // Special case logic when the operands have i1 type.
Nick Lewyckye659b842011-12-01 02:39:36 +00002318 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002319 switch (Pred) {
2320 default: break;
2321 case ICmpInst::ICMP_EQ:
2322 // X == 1 -> X
2323 if (match(RHS, m_One()))
2324 return LHS;
2325 break;
2326 case ICmpInst::ICMP_NE:
2327 // X != 0 -> X
2328 if (match(RHS, m_Zero()))
2329 return LHS;
2330 break;
2331 case ICmpInst::ICMP_UGT:
2332 // X >u 0 -> X
2333 if (match(RHS, m_Zero()))
2334 return LHS;
2335 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002336 case ICmpInst::ICMP_UGE: {
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002337 // X >=u 1 -> X
2338 if (match(RHS, m_One()))
2339 return LHS;
Chad Rosier41dd31f2016-04-20 19:15:26 +00002340 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002341 return getTrue(ITy);
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002342 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002343 }
2344 case ICmpInst::ICMP_SGE: {
Junmo Park53470fc2016-04-05 21:14:31 +00002345 /// For signed comparison, the values for an i1 are 0 and -1
Philip Reamesdbbd7792015-10-29 03:19:10 +00002346 /// respectively. This maps into a truth table of:
2347 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2348 /// 0 | 0 | 1 (0 >= 0) | 1
2349 /// 0 | 1 | 1 (0 >= -1) | 1
2350 /// 1 | 0 | 0 (-1 >= 0) | 0
2351 /// 1 | 1 | 1 (-1 >= -1) | 1
Chad Rosier41dd31f2016-04-20 19:15:26 +00002352 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reamesdbbd7792015-10-29 03:19:10 +00002353 return getTrue(ITy);
2354 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002355 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002356 case ICmpInst::ICMP_SLT:
2357 // X <s 0 -> X
2358 if (match(RHS, m_Zero()))
2359 return LHS;
2360 break;
2361 case ICmpInst::ICMP_SLE:
2362 // X <=s -1 -> X
2363 if (match(RHS, m_One()))
2364 return LHS;
2365 break;
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002366 case ICmpInst::ICMP_ULE: {
Chad Rosier41dd31f2016-04-20 19:15:26 +00002367 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
Philip Reames13f023c2015-09-28 17:14:24 +00002368 return getTrue(ITy);
2369 break;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002370 }
Chad Rosierb7dfbb42016-04-19 17:19:14 +00002371 }
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002372 }
2373
Duncan Sandsd3951082011-01-25 09:38:29 +00002374 // If we are comparing with zero then try hard since this is a common case.
2375 if (match(RHS, m_Zero())) {
2376 bool LHSKnownNonNegative, LHSKnownNegative;
2377 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002378 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd3951082011-01-25 09:38:29 +00002379 case ICmpInst::ICMP_ULT:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002380 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002381 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002382 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002383 case ICmpInst::ICMP_EQ:
2384 case ICmpInst::ICMP_ULE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002385 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002386 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002387 break;
2388 case ICmpInst::ICMP_NE:
2389 case ICmpInst::ICMP_UGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002390 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002391 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002392 break;
2393 case ICmpInst::ICMP_SLT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002394 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2395 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002396 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002397 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002398 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002399 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002400 break;
2401 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002402 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2403 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002404 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002405 return getTrue(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002406 if (LHSKnownNonNegative &&
2407 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002408 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002409 break;
2410 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002411 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2412 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002413 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002414 return getFalse(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002415 if (LHSKnownNonNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002416 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002417 break;
2418 case ICmpInst::ICMP_SGT:
Chandler Carruth66b31302015-01-04 12:03:27 +00002419 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2420 Q.CxtI, Q.DT);
Duncan Sandsd3951082011-01-25 09:38:29 +00002421 if (LHSKnownNegative)
Duncan Sandsc1c92712011-07-26 15:03:53 +00002422 return getFalse(ITy);
Chandler Carruth66b31302015-01-04 12:03:27 +00002423 if (LHSKnownNonNegative &&
2424 isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Duncan Sandsc1c92712011-07-26 15:03:53 +00002425 return getTrue(ITy);
Duncan Sandsd3951082011-01-25 09:38:29 +00002426 break;
2427 }
2428 }
2429
Sanjay Patel67bde282016-08-22 23:12:02 +00002430 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
2431 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00002432
Chen Li7452d952015-09-26 03:26:47 +00002433 // If both operands have range metadata, use the metadata
2434 // to simplify the comparison.
2435 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
2436 auto RHS_Instr = dyn_cast<Instruction>(RHS);
2437 auto LHS_Instr = dyn_cast<Instruction>(LHS);
2438
2439 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
2440 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00002441 auto RHS_CR = getConstantRangeFromMetadata(
2442 *RHS_Instr->getMetadata(LLVMContext::MD_range));
2443 auto LHS_CR = getConstantRangeFromMetadata(
2444 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00002445
2446 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
2447 if (Satisfied_CR.contains(LHS_CR))
2448 return ConstantInt::getTrue(RHS->getContext());
2449
2450 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
2451 CmpInst::getInversePredicate(Pred), RHS_CR);
2452 if (InversedSatisfied_CR.contains(LHS_CR))
2453 return ConstantInt::getFalse(RHS->getContext());
2454 }
2455 }
2456
Duncan Sands8fb2c382011-01-20 13:21:55 +00002457 // Compare of cast, for example (zext X) != 0 -> X != 0
2458 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2459 Instruction *LI = cast<CastInst>(LHS);
2460 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00002461 Type *SrcTy = SrcOp->getType();
2462 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00002463
2464 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2465 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002466 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
2467 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00002468 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2469 // Transfer the cast to the constant.
2470 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2471 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002472 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002473 return V;
2474 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2475 if (RI->getOperand(0)->getType() == SrcTy)
2476 // Compare without the cast.
2477 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002478 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002479 return V;
2480 }
2481 }
2482
2483 if (isa<ZExtInst>(LHS)) {
2484 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2485 // same type.
2486 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2487 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2488 // Compare X and Y. Note that signed predicates become unsigned.
2489 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002490 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00002491 MaxRecurse-1))
2492 return V;
2493 }
2494 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2495 // too. If not, then try to deduce the result of the comparison.
2496 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2497 // Compute the constant that would happen if we truncated to SrcTy then
2498 // reextended to DstTy.
2499 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2500 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2501
2502 // If the re-extended constant didn't change then this is effectively
2503 // also a case of comparing two zero-extended values.
2504 if (RExt == CI && MaxRecurse)
2505 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002506 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002507 return V;
2508
2509 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2510 // there. Use this to work out the result of the comparison.
2511 if (RExt != CI) {
2512 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002513 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002514 // LHS <u RHS.
2515 case ICmpInst::ICMP_EQ:
2516 case ICmpInst::ICMP_UGT:
2517 case ICmpInst::ICMP_UGE:
2518 return ConstantInt::getFalse(CI->getContext());
2519
2520 case ICmpInst::ICMP_NE:
2521 case ICmpInst::ICMP_ULT:
2522 case ICmpInst::ICMP_ULE:
2523 return ConstantInt::getTrue(CI->getContext());
2524
2525 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2526 // is non-negative then LHS <s RHS.
2527 case ICmpInst::ICMP_SGT:
2528 case ICmpInst::ICMP_SGE:
2529 return CI->getValue().isNegative() ?
2530 ConstantInt::getTrue(CI->getContext()) :
2531 ConstantInt::getFalse(CI->getContext());
2532
2533 case ICmpInst::ICMP_SLT:
2534 case ICmpInst::ICMP_SLE:
2535 return CI->getValue().isNegative() ?
2536 ConstantInt::getFalse(CI->getContext()) :
2537 ConstantInt::getTrue(CI->getContext());
2538 }
2539 }
2540 }
2541 }
2542
2543 if (isa<SExtInst>(LHS)) {
2544 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2545 // same type.
2546 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2547 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2548 // Compare X and Y. Note that the predicate does not change.
2549 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002550 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002551 return V;
2552 }
2553 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2554 // too. If not, then try to deduce the result of the comparison.
2555 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2556 // Compute the constant that would happen if we truncated to SrcTy then
2557 // reextended to DstTy.
2558 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2559 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2560
2561 // If the re-extended constant didn't change then this is effectively
2562 // also a case of comparing two sign-extended values.
2563 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002564 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002565 return V;
2566
2567 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2568 // bits there. Use this to work out the result of the comparison.
2569 if (RExt != CI) {
2570 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00002571 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00002572 case ICmpInst::ICMP_EQ:
2573 return ConstantInt::getFalse(CI->getContext());
2574 case ICmpInst::ICMP_NE:
2575 return ConstantInt::getTrue(CI->getContext());
2576
2577 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2578 // LHS >s RHS.
2579 case ICmpInst::ICMP_SGT:
2580 case ICmpInst::ICMP_SGE:
2581 return CI->getValue().isNegative() ?
2582 ConstantInt::getTrue(CI->getContext()) :
2583 ConstantInt::getFalse(CI->getContext());
2584 case ICmpInst::ICMP_SLT:
2585 case ICmpInst::ICMP_SLE:
2586 return CI->getValue().isNegative() ?
2587 ConstantInt::getFalse(CI->getContext()) :
2588 ConstantInt::getTrue(CI->getContext());
2589
2590 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2591 // LHS >u RHS.
2592 case ICmpInst::ICMP_UGT:
2593 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002594 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002595 if (MaxRecurse)
2596 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2597 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002598 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002599 return V;
2600 break;
2601 case ICmpInst::ICMP_ULT:
2602 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002603 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00002604 if (MaxRecurse)
2605 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2606 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002607 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00002608 return V;
2609 break;
2610 }
2611 }
2612 }
2613 }
2614 }
2615
James Molloy1d88d6f2015-10-22 13:18:42 +00002616 // icmp eq|ne X, Y -> false|true if X != Y
2617 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
2618 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
2619 LLVMContext &Ctx = LHS->getType()->getContext();
2620 return Pred == ICmpInst::ICMP_NE ?
2621 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
2622 }
Junmo Park53470fc2016-04-05 21:14:31 +00002623
Duncan Sandsd114ab32011-02-13 17:15:40 +00002624 // Special logic for binary operators.
2625 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2626 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2627 if (MaxRecurse && (LBO || RBO)) {
Duncan Sandsd114ab32011-02-13 17:15:40 +00002628 // Analyze the case when either LHS or RHS is an add instruction.
Craig Topper9f008862014-04-15 04:59:12 +00002629 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
Duncan Sandsd114ab32011-02-13 17:15:40 +00002630 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2631 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2632 if (LBO && LBO->getOpcode() == Instruction::Add) {
2633 A = LBO->getOperand(0); B = LBO->getOperand(1);
2634 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2635 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2636 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2637 }
2638 if (RBO && RBO->getOpcode() == Instruction::Add) {
2639 C = RBO->getOperand(0); D = RBO->getOperand(1);
2640 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2641 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2642 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2643 }
2644
2645 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2646 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2647 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2648 Constant::getNullValue(RHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002649 Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002650 return V;
2651
2652 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2653 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2654 if (Value *V = SimplifyICmpInst(Pred,
2655 Constant::getNullValue(LHS->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002656 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002657 return V;
2658
2659 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2660 if (A && C && (A == C || A == D || B == C || B == D) &&
2661 NoLHSWrapProblem && NoRHSWrapProblem) {
2662 // Determine Y and Z in the form icmp (X+Y), (X+Z).
Duncan Sandsc41076c2012-11-16 19:41:26 +00002663 Value *Y, *Z;
2664 if (A == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002665 // C + B == C + D -> B == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002666 Y = B;
2667 Z = D;
2668 } else if (A == D) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002669 // D + B == C + D -> B == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002670 Y = B;
2671 Z = C;
2672 } else if (B == C) {
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002673 // A + C == C + D -> A == D
Duncan Sandsc41076c2012-11-16 19:41:26 +00002674 Y = A;
2675 Z = D;
Duncan Sandsd7d8c092012-11-16 20:53:08 +00002676 } else {
2677 assert(B == D);
2678 // A + D == C + D -> A == C
Duncan Sandsc41076c2012-11-16 19:41:26 +00002679 Y = A;
2680 Z = C;
2681 }
Duncan Sandsb8cee002012-03-13 11:42:19 +00002682 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sandsd114ab32011-02-13 17:15:40 +00002683 return V;
2684 }
2685 }
2686
Nick Lewycky762f8a82016-04-21 00:53:14 +00002687 {
2688 Value *Y = nullptr;
2689 // icmp pred (or X, Y), X
2690 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2691 if (Pred == ICmpInst::ICMP_ULT)
2692 return getFalse(ITy);
2693 if (Pred == ICmpInst::ICMP_UGE)
2694 return getTrue(ITy);
2695
2696 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2697 bool RHSKnownNonNegative, RHSKnownNegative;
2698 bool YKnownNonNegative, YKnownNegative;
2699 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
2700 Q.AC, Q.CxtI, Q.DT);
2701 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2702 Q.CxtI, Q.DT);
2703 if (RHSKnownNonNegative && YKnownNegative)
2704 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2705 if (RHSKnownNegative || YKnownNonNegative)
2706 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2707 }
2708 }
2709 // icmp pred X, (or X, Y)
2710 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2711 if (Pred == ICmpInst::ICMP_ULE)
2712 return getTrue(ITy);
2713 if (Pred == ICmpInst::ICMP_UGT)
2714 return getFalse(ITy);
2715
2716 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2717 bool LHSKnownNonNegative, LHSKnownNegative;
2718 bool YKnownNonNegative, YKnownNegative;
2719 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
2720 Q.AC, Q.CxtI, Q.DT);
2721 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
2722 Q.CxtI, Q.DT);
2723 if (LHSKnownNonNegative && YKnownNegative)
2724 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2725 if (LHSKnownNegative || YKnownNonNegative)
2726 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2727 }
2728 }
David Majnemerbd9ce4e2014-11-25 02:55:48 +00002729 }
2730
2731 // icmp pred (and X, Y), X
2732 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2733 m_And(m_Specific(RHS), m_Value())))) {
2734 if (Pred == ICmpInst::ICMP_UGT)
2735 return getFalse(ITy);
2736 if (Pred == ICmpInst::ICMP_ULE)
2737 return getTrue(ITy);
2738 }
2739 // icmp pred X, (and X, Y)
2740 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2741 m_And(m_Specific(LHS), m_Value())))) {
2742 if (Pred == ICmpInst::ICMP_UGE)
2743 return getTrue(ITy);
2744 if (Pred == ICmpInst::ICMP_ULT)
2745 return getFalse(ITy);
2746 }
2747
David Majnemer2d6c0232014-05-14 20:16:28 +00002748 // 0 - (zext X) pred C
2749 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2750 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2751 if (RHSC->getValue().isStrictlyPositive()) {
2752 if (Pred == ICmpInst::ICMP_SLT)
2753 return ConstantInt::getTrue(RHSC->getContext());
2754 if (Pred == ICmpInst::ICMP_SGE)
2755 return ConstantInt::getFalse(RHSC->getContext());
2756 if (Pred == ICmpInst::ICMP_EQ)
2757 return ConstantInt::getFalse(RHSC->getContext());
2758 if (Pred == ICmpInst::ICMP_NE)
2759 return ConstantInt::getTrue(RHSC->getContext());
2760 }
2761 if (RHSC->getValue().isNonNegative()) {
2762 if (Pred == ICmpInst::ICMP_SLE)
2763 return ConstantInt::getTrue(RHSC->getContext());
2764 if (Pred == ICmpInst::ICMP_SGT)
2765 return ConstantInt::getFalse(RHSC->getContext());
2766 }
2767 }
2768 }
2769
Nick Lewycky35aeea92013-07-12 23:42:57 +00002770 // icmp pred (urem X, Y), Y
Nick Lewycky980104d2011-03-09 06:26:03 +00002771 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002772 bool KnownNonNegative, KnownNegative;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002773 switch (Pred) {
2774 default:
2775 break;
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002776 case ICmpInst::ICMP_SGT:
2777 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002778 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2779 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002780 if (!KnownNonNegative)
2781 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002782 LLVM_FALLTHROUGH;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002783 case ICmpInst::ICMP_EQ:
2784 case ICmpInst::ICMP_UGT:
2785 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002786 return getFalse(ITy);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002787 case ICmpInst::ICMP_SLT:
2788 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002789 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2790 Q.CxtI, Q.DT);
Nick Lewycky8e3a79d2011-03-04 10:06:52 +00002791 if (!KnownNonNegative)
2792 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002793 LLVM_FALLTHROUGH;
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002794 case ICmpInst::ICMP_NE:
2795 case ICmpInst::ICMP_ULT:
2796 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002797 return getTrue(ITy);
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002798 }
2799 }
Nick Lewycky35aeea92013-07-12 23:42:57 +00002800
2801 // icmp pred X, (urem Y, X)
Nick Lewycky980104d2011-03-09 06:26:03 +00002802 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2803 bool KnownNonNegative, KnownNegative;
2804 switch (Pred) {
2805 default:
2806 break;
2807 case ICmpInst::ICMP_SGT:
2808 case ICmpInst::ICMP_SGE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002809 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2810 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002811 if (!KnownNonNegative)
2812 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002813 LLVM_FALLTHROUGH;
Nick Lewycky774647d2011-03-09 08:20:06 +00002814 case ICmpInst::ICMP_NE:
Nick Lewycky980104d2011-03-09 06:26:03 +00002815 case ICmpInst::ICMP_UGT:
2816 case ICmpInst::ICMP_UGE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002817 return getTrue(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002818 case ICmpInst::ICMP_SLT:
2819 case ICmpInst::ICMP_SLE:
Chandler Carruth66b31302015-01-04 12:03:27 +00002820 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2821 Q.CxtI, Q.DT);
Nick Lewycky980104d2011-03-09 06:26:03 +00002822 if (!KnownNonNegative)
2823 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002824 LLVM_FALLTHROUGH;
Nick Lewycky774647d2011-03-09 08:20:06 +00002825 case ICmpInst::ICMP_EQ:
Nick Lewycky980104d2011-03-09 06:26:03 +00002826 case ICmpInst::ICMP_ULT:
2827 case ICmpInst::ICMP_ULE:
Duncan Sandsc1c92712011-07-26 15:03:53 +00002828 return getFalse(ITy);
Nick Lewycky980104d2011-03-09 06:26:03 +00002829 }
2830 }
Nick Lewyckyc9d20062011-03-01 08:15:50 +00002831
David Majnemer3af5bf32016-01-21 18:55:54 +00002832 // x >> y <=u x
Duncan Sands92af0a82011-10-28 18:17:44 +00002833 // x udiv y <=u x.
David Majnemer3af5bf32016-01-21 18:55:54 +00002834 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2835 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2836 // icmp pred (X op Y), X
Duncan Sands92af0a82011-10-28 18:17:44 +00002837 if (Pred == ICmpInst::ICMP_UGT)
2838 return getFalse(ITy);
2839 if (Pred == ICmpInst::ICMP_ULE)
2840 return getTrue(ITy);
2841 }
2842
David Majnemer76d06bc2014-08-28 03:34:28 +00002843 // handle:
2844 // CI2 << X == CI
2845 // CI2 << X != CI
2846 //
2847 // where CI2 is a power of 2 and CI isn't
2848 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2849 const APInt *CI2Val, *CIVal = &CI->getValue();
2850 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2851 CI2Val->isPowerOf2()) {
2852 if (!CIVal->isPowerOf2()) {
2853 // CI2 << X can equal zero in some circumstances,
2854 // this simplification is unsafe if CI is zero.
2855 //
2856 // We know it is safe if:
2857 // - The shift is nsw, we can't shift out the one bit.
2858 // - The shift is nuw, we can't shift out the one bit.
2859 // - CI2 is one
2860 // - CI isn't zero
2861 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2862 *CI2Val == 1 || !CI->isZero()) {
2863 if (Pred == ICmpInst::ICMP_EQ)
2864 return ConstantInt::getFalse(RHS->getContext());
2865 if (Pred == ICmpInst::ICMP_NE)
2866 return ConstantInt::getTrue(RHS->getContext());
2867 }
2868 }
2869 if (CIVal->isSignBit() && *CI2Val == 1) {
2870 if (Pred == ICmpInst::ICMP_UGT)
2871 return ConstantInt::getFalse(RHS->getContext());
2872 if (Pred == ICmpInst::ICMP_ULE)
2873 return ConstantInt::getTrue(RHS->getContext());
2874 }
2875 }
2876 }
2877
Nick Lewycky9719a712011-03-05 05:19:11 +00002878 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2879 LBO->getOperand(1) == RBO->getOperand(1)) {
2880 switch (LBO->getOpcode()) {
2881 default: break;
2882 case Instruction::UDiv:
2883 case Instruction::LShr:
2884 if (ICmpInst::isSigned(Pred))
2885 break;
Justin Bognerb03fd122016-08-17 05:10:15 +00002886 LLVM_FALLTHROUGH;
Nick Lewycky9719a712011-03-05 05:19:11 +00002887 case Instruction::SDiv:
2888 case Instruction::AShr:
Eli Friedman8a20e662011-05-05 21:59:18 +00002889 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky9719a712011-03-05 05:19:11 +00002890 break;
2891 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002892 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002893 return V;
2894 break;
2895 case Instruction::Shl: {
Duncan Sands020c1942011-08-04 10:02:21 +00002896 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky9719a712011-03-05 05:19:11 +00002897 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2898 if (!NUW && !NSW)
2899 break;
2900 if (!NSW && ICmpInst::isSigned(Pred))
2901 break;
2902 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00002903 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky9719a712011-03-05 05:19:11 +00002904 return V;
2905 break;
2906 }
2907 }
2908 }
2909
Duncan Sands0a9c1242011-05-03 19:53:10 +00002910 // Simplify comparisons involving max/min.
2911 Value *A, *B;
2912 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002913 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002914
Duncan Sandsa2287852011-05-04 16:05:05 +00002915 // Signed variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002916 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2917 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002918 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002919 // We analyze this as smax(A, B) pred A.
2920 P = Pred;
2921 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2922 (A == LHS || B == LHS)) {
2923 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002924 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002925 // We analyze this as smax(A, B) swapped-pred A.
2926 P = CmpInst::getSwappedPredicate(Pred);
2927 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2928 (A == RHS || B == RHS)) {
2929 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002930 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002931 // We analyze this as smax(-A, -B) swapped-pred -A.
2932 // Note that we do not need to actually form -A or -B thanks to EqP.
2933 P = CmpInst::getSwappedPredicate(Pred);
2934 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2935 (A == LHS || B == LHS)) {
2936 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002937 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002938 // We analyze this as smax(-A, -B) pred -A.
2939 // Note that we do not need to actually form -A or -B thanks to EqP.
2940 P = Pred;
2941 }
2942 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2943 // Cases correspond to "max(A, B) p A".
2944 switch (P) {
2945 default:
2946 break;
2947 case CmpInst::ICMP_EQ:
2948 case CmpInst::ICMP_SLE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002949 // Equivalent to "A EqP B". This may be the same as the condition tested
2950 // in the max/min; if so, we can just return that.
2951 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2952 return V;
2953 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2954 return V;
2955 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002956 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002957 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002958 return V;
2959 break;
2960 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00002961 case CmpInst::ICMP_SGT: {
2962 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2963 // Equivalent to "A InvEqP B". This may be the same as the condition
2964 // tested in the max/min; if so, we can just return that.
2965 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2966 return V;
2967 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2968 return V;
2969 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00002970 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00002971 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00002972 return V;
2973 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00002974 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00002975 case CmpInst::ICMP_SGE:
2976 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002977 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002978 case CmpInst::ICMP_SLT:
2979 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00002980 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00002981 }
2982 }
2983
Duncan Sandsa2287852011-05-04 16:05:05 +00002984 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002985 P = CmpInst::BAD_ICMP_PREDICATE;
2986 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2987 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002988 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002989 // We analyze this as umax(A, B) pred A.
2990 P = Pred;
2991 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2992 (A == LHS || B == LHS)) {
2993 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00002994 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00002995 // We analyze this as umax(A, B) swapped-pred A.
2996 P = CmpInst::getSwappedPredicate(Pred);
2997 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2998 (A == RHS || B == RHS)) {
2999 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003000 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003001 // We analyze this as umax(-A, -B) swapped-pred -A.
3002 // Note that we do not need to actually form -A or -B thanks to EqP.
3003 P = CmpInst::getSwappedPredicate(Pred);
3004 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3005 (A == LHS || B == LHS)) {
3006 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003007 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
Duncan Sands0a9c1242011-05-03 19:53:10 +00003008 // We analyze this as umax(-A, -B) pred -A.
3009 // Note that we do not need to actually form -A or -B thanks to EqP.
3010 P = Pred;
3011 }
3012 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3013 // Cases correspond to "max(A, B) p A".
3014 switch (P) {
3015 default:
3016 break;
3017 case CmpInst::ICMP_EQ:
3018 case CmpInst::ICMP_ULE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003019 // Equivalent to "A EqP B". This may be the same as the condition tested
3020 // in the max/min; if so, we can just return that.
3021 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3022 return V;
3023 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3024 return V;
3025 // Otherwise, see if "A EqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003026 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003027 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003028 return V;
3029 break;
3030 case CmpInst::ICMP_NE:
Duncan Sandsaf327282011-05-07 16:56:49 +00003031 case CmpInst::ICMP_UGT: {
3032 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3033 // Equivalent to "A InvEqP B". This may be the same as the condition
3034 // tested in the max/min; if so, we can just return that.
3035 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3036 return V;
3037 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3038 return V;
3039 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sands0a9c1242011-05-03 19:53:10 +00003040 if (MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003041 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sands0a9c1242011-05-03 19:53:10 +00003042 return V;
3043 break;
Duncan Sandsaf327282011-05-07 16:56:49 +00003044 }
Duncan Sands0a9c1242011-05-03 19:53:10 +00003045 case CmpInst::ICMP_UGE:
3046 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003047 return getTrue(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003048 case CmpInst::ICMP_ULT:
3049 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003050 return getFalse(ITy);
Duncan Sands0a9c1242011-05-03 19:53:10 +00003051 }
3052 }
3053
Duncan Sandsa2287852011-05-04 16:05:05 +00003054 // Variants on "max(x,y) >= min(x,z)".
3055 Value *C, *D;
3056 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3057 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3058 (A == C || A == D || B == C || B == D)) {
3059 // max(x, ?) pred min(x, ?).
3060 if (Pred == CmpInst::ICMP_SGE)
3061 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003062 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003063 if (Pred == CmpInst::ICMP_SLT)
3064 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003065 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003066 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3067 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3068 (A == C || A == D || B == C || B == D)) {
3069 // min(x, ?) pred max(x, ?).
3070 if (Pred == CmpInst::ICMP_SLE)
3071 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003072 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003073 if (Pred == CmpInst::ICMP_SGT)
3074 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003075 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003076 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3077 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3078 (A == C || A == D || B == C || B == D)) {
3079 // max(x, ?) pred min(x, ?).
3080 if (Pred == CmpInst::ICMP_UGE)
3081 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003082 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003083 if (Pred == CmpInst::ICMP_ULT)
3084 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003085 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003086 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3087 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3088 (A == C || A == D || B == C || B == D)) {
3089 // min(x, ?) pred max(x, ?).
3090 if (Pred == CmpInst::ICMP_ULE)
3091 // Always true.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003092 return getTrue(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003093 if (Pred == CmpInst::ICMP_UGT)
3094 // Always false.
Duncan Sandsc1c92712011-07-26 15:03:53 +00003095 return getFalse(ITy);
Duncan Sandsa2287852011-05-04 16:05:05 +00003096 }
3097
Chandler Carruth8059c842012-03-25 21:28:14 +00003098 // Simplify comparisons of related pointers using a powerful, recursive
3099 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003100 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003101 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003102 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003103 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3104 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3105 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3106 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3107 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3108 Q.DL.getTypeSizeInBits(CRHS->getType()))
3109 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3110 CLHS->getPointerOperand(),
3111 CRHS->getPointerOperand()))
3112 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003113
Nick Lewycky3db143e2012-02-26 02:09:49 +00003114 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3115 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3116 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3117 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3118 (ICmpInst::isEquality(Pred) ||
3119 (GLHS->isInBounds() && GRHS->isInBounds() &&
3120 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3121 // The bases are equal and the indices are constant. Build a constant
3122 // expression GEP with the same indices and a null base pointer to see
3123 // what constant folding can make out of it.
3124 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3125 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003126 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3127 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003128
3129 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003130 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3131 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003132 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3133 }
3134 }
3135 }
3136
David Majnemer5854e9f2014-11-16 02:20:08 +00003137 // If a bit is known to be zero for A and known to be one for B,
3138 // then A and B cannot be equal.
3139 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003140 const APInt *RHSVal;
3141 if (match(RHS, m_APInt(RHSVal))) {
3142 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003143 APInt LHSKnownZero(BitWidth, 0);
3144 APInt LHSKnownOne(BitWidth, 0);
Chandler Carruth66b31302015-01-04 12:03:27 +00003145 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003146 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003147 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3148 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3149 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003150 }
3151 }
3152
Duncan Sandsf532d312010-11-07 16:12:23 +00003153 // If the comparison is with the result of a select instruction, check whether
3154 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003155 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003156 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003157 return V;
3158
3159 // If the comparison is with the result of a phi instruction, check whether
3160 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003161 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003162 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003163 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003164
Craig Topper9f008862014-04-15 04:59:12 +00003165 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003166}
3167
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003168Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003169 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003170 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003171 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003172 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003173 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003174 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003175}
3176
Sanjay Patel472cc782016-01-11 22:14:42 +00003177/// Given operands for an FCmpInst, see if we can fold the result.
3178/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003179static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003180 FastMathFlags FMF, const Query &Q,
3181 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003182 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3183 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3184
Chris Lattnera71e9d62009-11-10 00:55:12 +00003185 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003186 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003187 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003188
Chris Lattnera71e9d62009-11-10 00:55:12 +00003189 // If we have a constant, make sure it is on the RHS.
3190 std::swap(LHS, RHS);
3191 Pred = CmpInst::getSwappedPredicate(Pred);
3192 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003193
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003194 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003195 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003196 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003197 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003198 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003199 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003200
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003201 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3202 if (FMF.noNaNs()) {
3203 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003204 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003205 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003206 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003207 }
3208
Mehdi Aminieb242a52015-03-09 03:20:25 +00003209 // fcmp pred x, undef and fcmp pred undef, x
3210 // fold to true if unordered, false if ordered
3211 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3212 // Choosing NaN for the undef will always make unordered comparison succeed
3213 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003214 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003215 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003216
3217 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003218 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003219 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003220 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003221 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003222 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003223 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003224
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003225 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003226 const ConstantFP *CFP = nullptr;
3227 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3228 if (RHS->getType()->isVectorTy())
3229 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3230 else
3231 CFP = dyn_cast<ConstantFP>(RHSC);
3232 }
3233 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003234 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003235 if (CFP->getValueAPF().isNaN()) {
3236 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003237 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003238 assert(FCmpInst::isUnordered(Pred) &&
3239 "Comparison must be either ordered or unordered!");
3240 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003241 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003242 }
3243 // Check whether the constant is an infinity.
3244 if (CFP->getValueAPF().isInfinity()) {
3245 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003246 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003247 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003248 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003249 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003250 case FCmpInst::FCMP_UGE:
3251 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003252 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003253 default:
3254 break;
3255 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003256 } else {
3257 switch (Pred) {
3258 case FCmpInst::FCMP_OGT:
3259 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003260 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003261 case FCmpInst::FCMP_ULE:
3262 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003263 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003264 default:
3265 break;
3266 }
3267 }
3268 }
3269 if (CFP->getValueAPF().isZero()) {
3270 switch (Pred) {
3271 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003272 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003273 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003274 break;
3275 case FCmpInst::FCMP_OLT:
3276 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003277 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003278 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003279 break;
3280 default:
3281 break;
3282 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003283 }
3284 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003285
Duncan Sandsa620bd12010-11-07 16:46:25 +00003286 // If the comparison is with the result of a select instruction, check whether
3287 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003288 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003289 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003290 return V;
3291
3292 // If the comparison is with the result of a phi instruction, check whether
3293 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003294 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003295 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003296 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003297
Craig Topper9f008862014-04-15 04:59:12 +00003298 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003299}
3300
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003301Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003302 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003303 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003304 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003305 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003306 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
3307 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003308}
3309
Sanjay Patel472cc782016-01-11 22:14:42 +00003310/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003311static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3312 const Query &Q,
3313 unsigned MaxRecurse) {
3314 // Trivial replacement.
3315 if (V == Op)
3316 return RepOp;
3317
3318 auto *I = dyn_cast<Instruction>(V);
3319 if (!I)
3320 return nullptr;
3321
3322 // If this is a binary operator, try to simplify it with the replaced op.
3323 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3324 // Consider:
3325 // %cmp = icmp eq i32 %x, 2147483647
3326 // %add = add nsw i32 %x, 1
3327 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3328 //
3329 // We can't replace %sel with %add unless we strip away the flags.
3330 if (isa<OverflowingBinaryOperator>(B))
3331 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3332 return nullptr;
3333 if (isa<PossiblyExactOperator>(B))
3334 if (B->isExact())
3335 return nullptr;
3336
3337 if (MaxRecurse) {
3338 if (B->getOperand(0) == Op)
3339 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3340 MaxRecurse - 1);
3341 if (B->getOperand(1) == Op)
3342 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3343 MaxRecurse - 1);
3344 }
3345 }
3346
3347 // Same for CmpInsts.
3348 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3349 if (MaxRecurse) {
3350 if (C->getOperand(0) == Op)
3351 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3352 MaxRecurse - 1);
3353 if (C->getOperand(1) == Op)
3354 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3355 MaxRecurse - 1);
3356 }
3357 }
3358
3359 // TODO: We could hand off more cases to instsimplify here.
3360
3361 // If all operands are constant after substituting Op for RepOp then we can
3362 // constant fold the instruction.
3363 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3364 // Build a list of all constant operands.
3365 SmallVector<Constant *, 8> ConstOps;
3366 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3367 if (I->getOperand(i) == Op)
3368 ConstOps.push_back(CRepOp);
3369 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3370 ConstOps.push_back(COp);
3371 else
3372 break;
3373 }
3374
3375 // All operands were constants, fold it.
3376 if (ConstOps.size() == I->getNumOperands()) {
3377 if (CmpInst *C = dyn_cast<CmpInst>(I))
3378 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3379 ConstOps[1], Q.DL, Q.TLI);
3380
3381 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3382 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003383 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003384
Manuel Jacobe9024592016-01-21 06:33:22 +00003385 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003386 }
3387 }
3388
3389 return nullptr;
3390}
3391
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003392/// Try to simplify a select instruction when its condition operand is an
3393/// integer comparison where one operand of the compare is a constant.
3394static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3395 const APInt *Y, bool TrueWhenUnset) {
3396 const APInt *C;
3397
3398 // (X & Y) == 0 ? X & ~Y : X --> X
3399 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3400 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3401 *Y == ~*C)
3402 return TrueWhenUnset ? FalseVal : TrueVal;
3403
3404 // (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)
3408 return TrueWhenUnset ? FalseVal : TrueVal;
3409
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)
3415 return TrueWhenUnset ? TrueVal : FalseVal;
3416
3417 // (X & Y) == 0 ? X : X | Y --> X
3418 // (X & Y) != 0 ? X : X | Y --> X | Y
3419 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3420 *Y == *C)
3421 return TrueWhenUnset ? TrueVal : FalseVal;
3422 }
3423
3424 return nullptr;
3425}
3426
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003427/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3428/// eq/ne.
3429static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3430 Value *FalseVal,
3431 bool TrueWhenUnset) {
3432 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003433 if (!BitWidth)
3434 return nullptr;
3435
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003436 APInt MinSignedValue;
3437 Value *X;
3438 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3439 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3440 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3441 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3442 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3443 } else {
3444 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3445 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3446 X = CmpLHS;
3447 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3448 }
3449
3450 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3451 TrueWhenUnset))
3452 return V;
3453
3454 return nullptr;
3455}
3456
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003457/// Try to simplify a select instruction when its condition operand is an
3458/// integer comparison.
3459static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3460 Value *FalseVal, const Query &Q,
3461 unsigned MaxRecurse) {
3462 ICmpInst::Predicate Pred;
3463 Value *CmpLHS, *CmpRHS;
3464 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3465 return nullptr;
3466
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003467 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3468 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003469 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3470 Value *X;
3471 const APInt *Y;
3472 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3473 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3474 Pred == ICmpInst::ICMP_EQ))
3475 return V;
3476 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003477 // Comparing signed-less-than 0 checks if the sign bit is set.
3478 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3479 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003480 return V;
3481 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003482 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3483 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3484 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003485 return V;
3486 }
3487
3488 if (CondVal->hasOneUse()) {
3489 const APInt *C;
3490 if (match(CmpRHS, m_APInt(C))) {
3491 // X < MIN ? T : F --> F
3492 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3493 return FalseVal;
3494 // X < MIN ? T : F --> F
3495 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3496 return FalseVal;
3497 // X > MAX ? T : F --> F
3498 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3499 return FalseVal;
3500 // X > MAX ? T : F --> F
3501 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3502 return FalseVal;
3503 }
3504 }
3505
3506 // If we have an equality comparison, then we know the value in one of the
3507 // arms of the select. See if substituting this value into the arm and
3508 // simplifying the result yields the same value as the other arm.
3509 if (Pred == ICmpInst::ICMP_EQ) {
3510 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3511 TrueVal ||
3512 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3513 TrueVal)
3514 return FalseVal;
3515 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3516 FalseVal ||
3517 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3518 FalseVal)
3519 return FalseVal;
3520 } else if (Pred == ICmpInst::ICMP_NE) {
3521 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3522 FalseVal ||
3523 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3524 FalseVal)
3525 return TrueVal;
3526 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3527 TrueVal ||
3528 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3529 TrueVal)
3530 return TrueVal;
3531 }
3532
3533 return nullptr;
3534}
3535
Sanjay Patel472cc782016-01-11 22:14:42 +00003536/// Given operands for a SelectInst, see if we can fold the result.
3537/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003538static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3539 Value *FalseVal, const Query &Q,
3540 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003541 // select true, X, Y -> X
3542 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003543 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3544 if (CB->isAllOnesValue())
3545 return TrueVal;
3546 if (CB->isNullValue())
3547 return FalseVal;
3548 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003549
Chris Lattnerc707fa92010-04-20 05:32:14 +00003550 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003551 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003552 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003553
Chris Lattnerc707fa92010-04-20 05:32:14 +00003554 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3555 if (isa<Constant>(TrueVal))
3556 return TrueVal;
3557 return FalseVal;
3558 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003559 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3560 return FalseVal;
3561 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3562 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003563
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003564 if (Value *V =
3565 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3566 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003567
Craig Topper9f008862014-04-15 04:59:12 +00003568 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003569}
3570
Duncan Sandsb8cee002012-03-13 11:42:19 +00003571Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003572 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003573 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003574 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003575 const Instruction *CxtI) {
3576 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Chandler Carruth66b31302015-01-04 12:03:27 +00003577 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003578}
3579
Sanjay Patel472cc782016-01-11 22:14:42 +00003580/// Given operands for an GetElementPtrInst, see if we can fold the result.
3581/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003582static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3583 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003584 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003585 unsigned AS =
3586 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003587
Chris Lattner8574aba2009-11-27 00:29:05 +00003588 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003589 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003590 return Ops[0];
3591
Nico Weber48c82402014-08-27 20:06:19 +00003592 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003593 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003594 Type *GEPTy = PointerType::get(LastType, AS);
3595 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3596 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3597
3598 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003599 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003600
Jay Foadb992a632011-07-19 15:07:52 +00003601 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003602 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003603 if (match(Ops[1], m_Zero()))
3604 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003605
David Blaikie4a2e73b2015-04-02 18:55:32 +00003606 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003607 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003608 Value *P;
3609 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003610 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003611 // getelementptr P, N -> P if P points to a type of zero size.
3612 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003613 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003614
3615 // The following transforms are only safe if the ptrtoint cast
3616 // doesn't truncate the pointers.
3617 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003618 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003619 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3620 if (match(P, m_Zero()))
3621 return Constant::getNullValue(GEPTy);
3622 Value *Temp;
3623 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003624 if (Temp->getType() == GEPTy)
3625 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003626 return nullptr;
3627 };
3628
3629 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3630 if (TyAllocSize == 1 &&
3631 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3632 if (Value *R = PtrToIntOrZero(P))
3633 return R;
3634
3635 // getelementptr V, (ashr (sub P, V), C) -> Q
3636 // if P points to a type of size 1 << C.
3637 if (match(Ops[1],
3638 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3639 m_ConstantInt(C))) &&
3640 TyAllocSize == 1ULL << C)
3641 if (Value *R = PtrToIntOrZero(P))
3642 return R;
3643
3644 // getelementptr V, (sdiv (sub P, V), C) -> Q
3645 // if P points to a type of size C.
3646 if (match(Ops[1],
3647 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3648 m_SpecificInt(TyAllocSize))))
3649 if (Value *R = PtrToIntOrZero(P))
3650 return R;
3651 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003652 }
3653 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003654
David Majnemerd1501372016-08-07 07:58:12 +00003655 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3656 all_of(Ops.slice(1).drop_back(1),
3657 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3658 unsigned PtrWidth =
3659 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3660 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3661 APInt BasePtrOffset(PtrWidth, 0);
3662 Value *StrippedBasePtr =
3663 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3664 BasePtrOffset);
3665
David Majnemer5c5df622016-08-16 06:13:46 +00003666 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003667 if (match(Ops.back(),
3668 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3669 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3670 return ConstantExpr::getIntToPtr(CI, GEPTy);
3671 }
David Majnemer5c5df622016-08-16 06:13:46 +00003672 // gep (gep V, C), (xor V, -1) -> C-1
3673 if (match(Ops.back(),
3674 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3675 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3676 return ConstantExpr::getIntToPtr(CI, GEPTy);
3677 }
David Majnemerd1501372016-08-07 07:58:12 +00003678 }
3679 }
3680
Chris Lattner8574aba2009-11-27 00:29:05 +00003681 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003682 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003683 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003684 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003685
David Blaikie4a2e73b2015-04-02 18:55:32 +00003686 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3687 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003688}
3689
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003690Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3691 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003692 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003693 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003694 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003695 return ::SimplifyGEPInst(SrcTy, Ops,
3696 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003697}
3698
Sanjay Patel472cc782016-01-11 22:14:42 +00003699/// Given operands for an InsertValueInst, see if we can fold the result.
3700/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003701static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3702 ArrayRef<unsigned> Idxs, const Query &Q,
3703 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003704 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3705 if (Constant *CVal = dyn_cast<Constant>(Val))
3706 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3707
3708 // insertvalue x, undef, n -> x
3709 if (match(Val, m_Undef()))
3710 return Agg;
3711
3712 // insertvalue x, (extractvalue y, n), n
3713 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003714 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3715 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003716 // insertvalue undef, (extractvalue y, n), n -> y
3717 if (match(Agg, m_Undef()))
3718 return EV->getAggregateOperand();
3719
3720 // insertvalue y, (extractvalue y, n), n -> y
3721 if (Agg == EV->getAggregateOperand())
3722 return Agg;
3723 }
3724
Craig Topper9f008862014-04-15 04:59:12 +00003725 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003726}
3727
Chandler Carruth66b31302015-01-04 12:03:27 +00003728Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003729 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00003730 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
3731 const Instruction *CxtI) {
3732 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003733 RecursionLimit);
3734}
3735
Sanjay Patel472cc782016-01-11 22:14:42 +00003736/// Given operands for an ExtractValueInst, see if we can fold the result.
3737/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003738static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3739 const Query &, unsigned) {
3740 if (auto *CAgg = dyn_cast<Constant>(Agg))
3741 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3742
3743 // extractvalue x, (insertvalue y, elt, n), n -> elt
3744 unsigned NumIdxs = Idxs.size();
3745 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3746 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3747 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3748 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3749 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3750 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3751 Idxs.slice(0, NumCommonIdxs)) {
3752 if (NumIdxs == NumInsertValueIdxs)
3753 return IVI->getInsertedValueOperand();
3754 break;
3755 }
3756 }
3757
3758 return nullptr;
3759}
3760
3761Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3762 const DataLayout &DL,
3763 const TargetLibraryInfo *TLI,
3764 const DominatorTree *DT,
3765 AssumptionCache *AC,
3766 const Instruction *CxtI) {
3767 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
3768 RecursionLimit);
3769}
3770
Sanjay Patel472cc782016-01-11 22:14:42 +00003771/// Given operands for an ExtractElementInst, see if we can fold the result.
3772/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003773static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3774 unsigned) {
3775 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3776 if (auto *CIdx = dyn_cast<Constant>(Idx))
3777 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3778
3779 // The index is not relevant if our vector is a splat.
3780 if (auto *Splat = CVec->getSplatValue())
3781 return Splat;
3782
3783 if (isa<UndefValue>(Vec))
3784 return UndefValue::get(Vec->getType()->getVectorElementType());
3785 }
3786
3787 // If extracting a specified index from the vector, see if we can recursively
3788 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003789 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3790 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003791 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003792
3793 return nullptr;
3794}
3795
3796Value *llvm::SimplifyExtractElementInst(
3797 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
3798 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
3799 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
3800 RecursionLimit);
3801}
3802
Sanjay Patel472cc782016-01-11 22:14:42 +00003803/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003804static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003805 // If all of the PHI's incoming values are the same then replace the PHI node
3806 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003807 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003808 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003809 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003810 // If the incoming value is the phi node itself, it can safely be skipped.
3811 if (Incoming == PN) continue;
3812 if (isa<UndefValue>(Incoming)) {
3813 // Remember that we saw an undef value, but otherwise ignore them.
3814 HasUndefInput = true;
3815 continue;
3816 }
3817 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003818 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003819 CommonValue = Incoming;
3820 }
3821
3822 // If CommonValue is null then all of the incoming values were either undef or
3823 // equal to the phi node itself.
3824 if (!CommonValue)
3825 return UndefValue::get(PN->getType());
3826
3827 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3828 // instruction, we cannot return X as the result of the PHI node unless it
3829 // dominates the PHI block.
3830 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003831 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003832
3833 return CommonValue;
3834}
3835
David Majnemer6774d612016-07-26 17:58:05 +00003836static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
3837 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00003838 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00003839 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003840
David Majnemer6774d612016-07-26 17:58:05 +00003841 if (auto *CI = dyn_cast<CastInst>(Op)) {
3842 auto *Src = CI->getOperand(0);
3843 Type *SrcTy = Src->getType();
3844 Type *MidTy = CI->getType();
3845 Type *DstTy = Ty;
3846 if (Src->getType() == Ty) {
3847 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
3848 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
3849 Type *SrcIntPtrTy =
3850 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
3851 Type *MidIntPtrTy =
3852 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
3853 Type *DstIntPtrTy =
3854 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
3855 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
3856 SrcIntPtrTy, MidIntPtrTy,
3857 DstIntPtrTy) == Instruction::BitCast)
3858 return Src;
3859 }
3860 }
David Majnemera90a6212016-07-26 05:52:29 +00003861
3862 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00003863 if (CastOpc == Instruction::BitCast)
3864 if (Op->getType() == Ty)
3865 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00003866
3867 return nullptr;
3868}
3869
David Majnemer6774d612016-07-26 17:58:05 +00003870Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
3871 const DataLayout &DL,
3872 const TargetLibraryInfo *TLI,
3873 const DominatorTree *DT, AssumptionCache *AC,
3874 const Instruction *CxtI) {
3875 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
3876 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00003877}
3878
Chris Lattnera71e9d62009-11-10 00:55:12 +00003879//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00003880
Sanjay Patel472cc782016-01-11 22:14:42 +00003881/// Given operands for a BinaryOperator, see if we can fold the result.
3882/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003883static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003884 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00003885 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00003886 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003887 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003888 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003889 case Instruction::FAdd:
3890 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3891
Chris Lattner9e4aa022011-02-09 17:15:04 +00003892 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003893 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003894 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003895 case Instruction::FSub:
3896 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3897
Duncan Sandsb8cee002012-03-13 11:42:19 +00003898 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00003899 case Instruction::FMul:
3900 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003901 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3902 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003903 case Instruction::FDiv:
3904 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003905 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3906 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00003907 case Instruction::FRem:
3908 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003909 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00003910 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003911 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003912 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003913 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00003914 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00003915 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3916 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3917 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3918 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003919 default:
3920 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00003921 if (Constant *CRHS = dyn_cast<Constant>(RHS))
3922 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00003923
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003924 // If the operation is associative, try some generic simplifications.
3925 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003926 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00003927 return V;
3928
Duncan Sandsb8cee002012-03-13 11:42:19 +00003929 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00003930 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003931 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003932 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003933 return V;
3934
3935 // If the operation is with the result of a phi instruction, check whether
3936 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003937 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003938 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00003939 return V;
3940
Craig Topper9f008862014-04-15 04:59:12 +00003941 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00003942 }
3943}
Chris Lattnerc1f19072009-11-09 23:28:39 +00003944
Sanjay Patel472cc782016-01-11 22:14:42 +00003945/// Given operands for a BinaryOperator, see if we can fold the result.
3946/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003947/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
3948/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
3949static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3950 const FastMathFlags &FMF, const Query &Q,
3951 unsigned MaxRecurse) {
3952 switch (Opcode) {
3953 case Instruction::FAdd:
3954 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
3955 case Instruction::FSub:
3956 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
3957 case Instruction::FMul:
3958 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
3959 default:
3960 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
3961 }
3962}
3963
Duncan Sands7e800d62010-11-14 11:23:23 +00003964Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003965 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003966 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003967 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003968 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00003969 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00003970}
3971
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003972Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003973 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00003974 const TargetLibraryInfo *TLI,
3975 const DominatorTree *DT, AssumptionCache *AC,
3976 const Instruction *CxtI) {
3977 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
3978 RecursionLimit);
3979}
3980
Sanjay Patel472cc782016-01-11 22:14:42 +00003981/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003982static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003983 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003984 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003985 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003986 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003987}
3988
3989Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003990 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00003991 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003992 const Instruction *CxtI) {
Chandler Carruth66b31302015-01-04 12:03:27 +00003993 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003994 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003995}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00003996
Michael Ilseman54857292013-02-07 19:26:05 +00003997static bool IsIdempotent(Intrinsic::ID ID) {
3998 switch (ID) {
3999 default: return false;
4000
4001 // Unary idempotent: f(f(x)) = f(x)
4002 case Intrinsic::fabs:
4003 case Intrinsic::floor:
4004 case Intrinsic::ceil:
4005 case Intrinsic::trunc:
4006 case Intrinsic::rint:
4007 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004008 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004009 return true;
4010 }
4011}
4012
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004013static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4014 const DataLayout &DL) {
4015 GlobalValue *PtrSym;
4016 APInt PtrOffset;
4017 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4018 return nullptr;
4019
4020 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4021 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4022 Type *Int32PtrTy = Int32Ty->getPointerTo();
4023 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4024
4025 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4026 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4027 return nullptr;
4028
4029 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4030 if (OffsetInt % 4 != 0)
4031 return nullptr;
4032
4033 Constant *C = ConstantExpr::getGetElementPtr(
4034 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4035 ConstantInt::get(Int64Ty, OffsetInt / 4));
4036 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4037 if (!Loaded)
4038 return nullptr;
4039
4040 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4041 if (!LoadedCE)
4042 return nullptr;
4043
4044 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4045 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4046 if (!LoadedCE)
4047 return nullptr;
4048 }
4049
4050 if (LoadedCE->getOpcode() != Instruction::Sub)
4051 return nullptr;
4052
4053 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4054 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4055 return nullptr;
4056 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4057
4058 Constant *LoadedRHS = LoadedCE->getOperand(1);
4059 GlobalValue *LoadedRHSSym;
4060 APInt LoadedRHSOffset;
4061 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4062 DL) ||
4063 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4064 return nullptr;
4065
4066 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4067}
4068
David Majnemer17a95aa2016-07-14 06:58:37 +00004069static bool maskIsAllZeroOrUndef(Value *Mask) {
4070 auto *ConstMask = dyn_cast<Constant>(Mask);
4071 if (!ConstMask)
4072 return false;
4073 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4074 return true;
4075 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4076 ++I) {
4077 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4078 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4079 continue;
4080 return false;
4081 }
4082 return true;
4083}
4084
Michael Ilseman54857292013-02-07 19:26:05 +00004085template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004086static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004087 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004088 Intrinsic::ID IID = F->getIntrinsicID();
4089 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4090 Type *ReturnType = F->getReturnType();
4091
4092 // Binary Ops
4093 if (NumOperands == 2) {
4094 Value *LHS = *ArgBegin;
4095 Value *RHS = *(ArgBegin + 1);
4096 if (IID == Intrinsic::usub_with_overflow ||
4097 IID == Intrinsic::ssub_with_overflow) {
4098 // X - X -> { 0, false }
4099 if (LHS == RHS)
4100 return Constant::getNullValue(ReturnType);
4101
4102 // X - undef -> undef
4103 // undef - X -> undef
4104 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4105 return UndefValue::get(ReturnType);
4106 }
4107
4108 if (IID == Intrinsic::uadd_with_overflow ||
4109 IID == Intrinsic::sadd_with_overflow) {
4110 // X + undef -> undef
4111 if (isa<UndefValue>(RHS))
4112 return UndefValue::get(ReturnType);
4113 }
4114
4115 if (IID == Intrinsic::umul_with_overflow ||
4116 IID == Intrinsic::smul_with_overflow) {
4117 // X * 0 -> { 0, false }
4118 if (match(RHS, m_Zero()))
4119 return Constant::getNullValue(ReturnType);
4120
4121 // X * undef -> { 0, false }
4122 if (match(RHS, m_Undef()))
4123 return Constant::getNullValue(ReturnType);
4124 }
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004125
4126 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4127 isa<Constant>(RHS))
4128 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4129 Q.DL);
David Majnemer15032582015-05-22 03:56:46 +00004130 }
4131
David Majnemerd77a3b62016-07-13 23:32:53 +00004132 // Simplify calls to llvm.masked.load.*
4133 if (IID == Intrinsic::masked_load) {
David Majnemer17a95aa2016-07-14 06:58:37 +00004134 Value *MaskArg = ArgBegin[2];
4135 Value *PassthruArg = ArgBegin[3];
4136 // If the mask is all zeros or undef, the "passthru" argument is the result.
4137 if (maskIsAllZeroOrUndef(MaskArg))
4138 return PassthruArg;
David Majnemerd77a3b62016-07-13 23:32:53 +00004139 }
4140
Michael Ilseman54857292013-02-07 19:26:05 +00004141 // Perform idempotent optimizations
4142 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00004143 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004144
4145 // Unary Ops
David Majnemer15032582015-05-22 03:56:46 +00004146 if (NumOperands == 1)
Michael Ilseman54857292013-02-07 19:26:05 +00004147 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4148 if (II->getIntrinsicID() == IID)
4149 return II;
4150
Craig Topper9f008862014-04-15 04:59:12 +00004151 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004152}
4153
Chandler Carruth9dc35582012-12-28 11:30:55 +00004154template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004155static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004156 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004157 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004158 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4159 Ty = PTy->getElementType();
4160 FunctionType *FTy = cast<FunctionType>(Ty);
4161
Dan Gohman85977e62011-11-04 18:32:42 +00004162 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004163 // call null -> undef
4164 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004165 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004166
Chandler Carruthf6182152012-12-28 14:23:29 +00004167 Function *F = dyn_cast<Function>(V);
4168 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004169 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004170
David Majnemer15032582015-05-22 03:56:46 +00004171 if (F->isIntrinsic())
4172 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004173 return Ret;
4174
Chandler Carruthf6182152012-12-28 14:23:29 +00004175 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004176 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004177
4178 SmallVector<Constant *, 4> ConstantArgs;
4179 ConstantArgs.reserve(ArgEnd - ArgBegin);
4180 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4181 Constant *C = dyn_cast<Constant>(*I);
4182 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004183 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004184 ConstantArgs.push_back(C);
4185 }
4186
4187 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004188}
4189
Chandler Carruthf6182152012-12-28 14:23:29 +00004190Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004191 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004192 const TargetLibraryInfo *TLI, const DominatorTree *DT,
4193 AssumptionCache *AC, const Instruction *CxtI) {
4194 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004195 RecursionLimit);
4196}
4197
Chandler Carruthf6182152012-12-28 14:23:29 +00004198Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004199 const DataLayout &DL, const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004200 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004201 const Instruction *CxtI) {
4202 return ::SimplifyCall(V, Args.begin(), Args.end(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004203 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004204}
4205
Sanjay Patel472cc782016-01-11 22:14:42 +00004206/// See if we can compute a simplified version of this instruction.
4207/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004208Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004209 const TargetLibraryInfo *TLI,
Chandler Carruth66b31302015-01-04 12:03:27 +00004210 const DominatorTree *DT, AssumptionCache *AC) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004211 Value *Result;
4212
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004213 switch (I->getOpcode()) {
4214 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004215 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004216 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004217 case Instruction::FAdd:
4218 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004219 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004220 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004221 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004222 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4223 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004224 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4225 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004226 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004227 case Instruction::FSub:
4228 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004229 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004230 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004231 case Instruction::Sub:
4232 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4233 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004234 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4235 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004236 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004237 case Instruction::FMul:
4238 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004239 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004240 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004241 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004242 Result =
4243 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004244 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004245 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004246 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4247 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004248 break;
4249 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004250 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4251 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004252 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004253 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004254 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
4255 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004256 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004257 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004258 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4259 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004260 break;
4261 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004262 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
4263 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004264 break;
4265 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004266 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
4267 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004268 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004269 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004270 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4271 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004272 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
4273 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004274 break;
4275 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004276 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004277 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4278 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004279 break;
4280 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004281 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004282 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
4283 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004284 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004285 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004286 Result =
4287 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004288 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004289 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004290 Result =
4291 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004292 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004293 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004294 Result =
4295 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004296 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004297 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004298 Result =
4299 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
4300 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004301 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004302 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004303 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4304 I->getOperand(0), I->getOperand(1),
4305 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004306 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004307 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004308 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004309 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004310 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004311 case Instruction::GetElementPtr: {
4312 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004313 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
4314 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004315 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004316 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004317 case Instruction::InsertValue: {
4318 InsertValueInst *IV = cast<InsertValueInst>(I);
4319 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4320 IV->getInsertedValueOperand(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004321 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004322 break;
4323 }
David Majnemer25a796e2015-07-13 01:15:46 +00004324 case Instruction::ExtractValue: {
4325 auto *EVI = cast<ExtractValueInst>(I);
4326 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
4327 EVI->getIndices(), DL, TLI, DT, AC, I);
4328 break;
4329 }
David Majnemer599ca442015-07-13 01:15:53 +00004330 case Instruction::ExtractElement: {
4331 auto *EEI = cast<ExtractElementInst>(I);
4332 Result = SimplifyExtractElementInst(
4333 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
4334 break;
4335 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004336 case Instruction::PHI:
Chandler Carruth66b31302015-01-04 12:03:27 +00004337 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004338 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004339 case Instruction::Call: {
4340 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004341 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
4342 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004343 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004344 }
David Majnemer6774d612016-07-26 17:58:05 +00004345#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4346#include "llvm/IR/Instruction.def"
4347#undef HANDLE_CAST_INST
4348 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
4349 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004350 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004351 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004352
Hal Finkelf2199b22015-10-23 20:37:08 +00004353 // In general, it is possible for computeKnownBits to determine all bits in a
4354 // value even when the operands are not all constants.
4355 if (!Result && I->getType()->isIntegerTy()) {
4356 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4357 APInt KnownZero(BitWidth, 0);
4358 APInt KnownOne(BitWidth, 0);
4359 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT);
4360 if ((KnownZero | KnownOne).isAllOnesValue())
4361 Result = ConstantInt::get(I->getContext(), KnownOne);
4362 }
4363
Duncan Sands64e41cf2010-11-17 08:35:29 +00004364 /// If called on unreachable code, the above logic may report that the
4365 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004366 /// detecting that case here, returning a safe value instead.
4367 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004368}
4369
Sanjay Patelf44bd382016-01-20 18:59:48 +00004370/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004371/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004372///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004373/// This is the common implementation of the recursive simplification routines.
4374/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4375/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4376/// instructions to process and attempt to simplify it using
4377/// InstructionSimplify.
4378///
4379/// This routine returns 'true' only when *it* simplifies something. The passed
4380/// in simplified value does not count toward this.
4381static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004382 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004383 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004384 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004385 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004386 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004387 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004388
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004389 // If we have an explicit value to collapse to, do that round of the
4390 // simplification loop by hand initially.
4391 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004392 for (User *U : I->users())
4393 if (U != I)
4394 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004395
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004396 // Replace the instruction with its simplified value.
4397 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004398
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004399 // Gracefully handle edge cases where the instruction is not wired into any
4400 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004401 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4402 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004403 I->eraseFromParent();
4404 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004405 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004406 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004407
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004408 // Note that we must test the size on each iteration, the worklist can grow.
4409 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4410 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004411
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004412 // See if this instruction simplifies.
Chandler Carruth66b31302015-01-04 12:03:27 +00004413 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004414 if (!SimpleV)
4415 continue;
4416
4417 Simplified = true;
4418
4419 // Stash away all the uses of the old instruction so we can check them for
4420 // recursive simplifications after a RAUW. This is cheaper than checking all
4421 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004422 for (User *U : I->users())
4423 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004424
4425 // Replace the instruction with its simplified value.
4426 I->replaceAllUsesWith(SimpleV);
4427
4428 // Gracefully handle edge cases where the instruction is not wired into any
4429 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004430 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4431 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004432 I->eraseFromParent();
4433 }
4434 return Simplified;
4435}
4436
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004437bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004438 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004439 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004440 AssumptionCache *AC) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004441 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004442}
4443
4444bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004445 const TargetLibraryInfo *TLI,
Hal Finkel60db0582014-09-07 18:57:58 +00004446 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00004447 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004448 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4449 assert(SimpleV && "Must provide a simplified value.");
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004450 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004451}