blob: 5fd96d117a11ac56a0aaf6af87a6cfd702276211 [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;
Hal Finkel60db0582014-09-07 18:57:58 +000053 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000054
Mehdi Aminia28d91d2015-03-10 02:37:25 +000055 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +000056 const DominatorTree *dt, const Instruction *cxti = nullptr)
57 : DL(DL), TLI(tli), DT(dt), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000058};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000059} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000060
61static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
62static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000063 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000064static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
65 const Query &, unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000066static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000067 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000068static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
69 const Query &Q, unsigned MaxRecurse);
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,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000585 const DominatorTree *DT, const Instruction *CxtI) {
586 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000587 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000588}
589
Chandler Carrutha0796552012-03-12 11:19:31 +0000590/// \brief Compute the base pointer and cumulative constant offsets for V.
591///
592/// This strips all constant offsets off of V, leaving it the base pointer, and
593/// accumulates the total constant offset applied in the returned constant. It
594/// returns 0 if V is not a pointer, and returns the constant '0' if there are
595/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000596///
597/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
598/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
599/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000600static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000601 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000602 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000603
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000605 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000606
607 // Even though we don't look through PHI nodes, we could be called on an
608 // instruction in an unreachable block, which may be on a cycle.
609 SmallPtrSet<Value *, 4> Visited;
610 Visited.insert(V);
611 do {
612 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000613 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000614 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000615 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000616 V = GEP->getPointerOperand();
617 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000618 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000619 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000620 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000621 break;
622 V = GA->getAliasee();
623 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000624 if (auto CS = CallSite(V))
625 if (Value *RV = CS.getReturnedArgOperand()) {
626 V = RV;
627 continue;
628 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000629 break;
630 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000631 assert(V->getType()->getScalarType()->isPointerTy() &&
632 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000633 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000634
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000635 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
636 if (V->getType()->isVectorTy())
637 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
638 OffsetIntPtr);
639 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000640}
641
642/// \brief Compute the constant difference between two pointer values.
643/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000644static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
645 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000646 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
647 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000648
649 // If LHS and RHS are not related via constant offsets to the same base
650 // value, there is nothing we can do here.
651 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000652 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000653
654 // Otherwise, the difference of LHS - RHS can be computed as:
655 // LHS - RHS
656 // = (LHSOffset + Base) - (RHSOffset + Base)
657 // = LHSOffset - RHSOffset
658 return ConstantExpr::getSub(LHSOffset, RHSOffset);
659}
660
Sanjay Patel472cc782016-01-11 22:14:42 +0000661/// Given operands for a Sub, see if we can fold the result.
662/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000663static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000664 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000665 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000666 if (Constant *CRHS = dyn_cast<Constant>(Op1))
667 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000668
669 // X - undef -> undef
670 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000671 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000672 return UndefValue::get(Op0->getType());
673
674 // X - 0 -> X
675 if (match(Op1, m_Zero()))
676 return Op0;
677
678 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000679 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000680 return Constant::getNullValue(Op0->getType());
681
Sanjay Patelefd88852016-10-19 21:23:45 +0000682 // Is this a negation?
683 if (match(Op0, m_Zero())) {
684 // 0 - X -> 0 if the sub is NUW.
685 if (isNUW)
686 return Op0;
687
688 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
689 APInt KnownZero(BitWidth, 0);
690 APInt KnownOne(BitWidth, 0);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000691 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.CxtI, Q.DT);
Sanjay Patelefd88852016-10-19 21:23:45 +0000692 if (KnownZero == ~APInt::getSignBit(BitWidth)) {
693 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
694 // Op1 must be 0 because negating the minimum signed value is undefined.
695 if (isNSW)
696 return Op0;
697
698 // 0 - X -> X if X is 0 or the minimum signed value.
699 return Op1;
700 }
701 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000702
Duncan Sands99589d02011-01-18 11:50:19 +0000703 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
704 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000705 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000706 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
707 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000708 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000709 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000710 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000711 // It does, we successfully reassociated!
712 ++NumReassoc;
713 return W;
714 }
715 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000716 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000717 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000718 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000719 // It does, we successfully reassociated!
720 ++NumReassoc;
721 return W;
722 }
723 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000724
Duncan Sands99589d02011-01-18 11:50:19 +0000725 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
726 // For example, X - (X + 1) -> -1
727 X = Op0;
728 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
729 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000730 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000731 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000732 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000733 // It does, we successfully reassociated!
734 ++NumReassoc;
735 return W;
736 }
737 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000738 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000739 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000740 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000741 // It does, we successfully reassociated!
742 ++NumReassoc;
743 return W;
744 }
745 }
746
747 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
748 // For example, X - (X - Y) -> Y.
749 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000750 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
751 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000752 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000753 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000754 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000755 // It does, we successfully reassociated!
756 ++NumReassoc;
757 return W;
758 }
759
Duncan Sands395ac42d2012-03-13 14:07:05 +0000760 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
761 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
762 match(Op1, m_Trunc(m_Value(Y))))
763 if (X->getType() == Y->getType())
764 // See if "V === X - Y" simplifies.
765 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
766 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000767 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
768 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000769 // It does, return the simplified "trunc V".
770 return W;
771
772 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000773 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000774 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000775 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000776 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
777
Duncan Sands99589d02011-01-18 11:50:19 +0000778 // i1 sub -> xor.
779 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000780 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000781 return V;
782
Duncan Sands0a2c41682010-12-15 14:07:39 +0000783 // Threading Sub over selects and phi nodes is pointless, so don't bother.
784 // Threading over the select in "A - select(cond, B, C)" means evaluating
785 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
786 // only if B and C are equal. If B and C are equal then (since we assume
787 // that operands have already been simplified) "select(cond, B, C)" should
788 // have been simplified to the common value of B and C already. Analysing
789 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
790 // for threading over phi nodes.
791
Craig Topper9f008862014-04-15 04:59:12 +0000792 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000793}
794
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000795Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000796 const DataLayout &DL, const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000797 const DominatorTree *DT, const Instruction *CxtI) {
798 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000799 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000800}
801
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000802/// Given operands for an FAdd, see if we can fold the result. If not, this
803/// returns null.
804static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
805 const Query &Q, unsigned MaxRecurse) {
806 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000807 if (Constant *CRHS = dyn_cast<Constant>(Op1))
808 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000809
810 // Canonicalize the constant to the RHS.
811 std::swap(Op0, Op1);
812 }
813
814 // fadd X, -0 ==> X
815 if (match(Op1, m_NegZero()))
816 return Op0;
817
818 // fadd X, 0 ==> X, when we know X is not -0
819 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000820 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000821 return Op0;
822
823 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
824 // where nnan and ninf have to occur at least once somewhere in this
825 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000826 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000827 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
828 SubOp = Op1;
829 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
830 SubOp = Op0;
831 if (SubOp) {
832 Instruction *FSub = cast<Instruction>(SubOp);
833 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
834 (FMF.noInfs() || FSub->hasNoInfs()))
835 return Constant::getNullValue(Op0->getType());
836 }
837
Craig Topper9f008862014-04-15 04:59:12 +0000838 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000839}
840
841/// Given operands for an FSub, see if we can fold the result. If not, this
842/// returns null.
843static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
844 const Query &Q, unsigned MaxRecurse) {
845 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000846 if (Constant *CRHS = dyn_cast<Constant>(Op1))
847 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000848 }
849
850 // fsub X, 0 ==> X
851 if (match(Op1, m_Zero()))
852 return Op0;
853
854 // fsub X, -0 ==> X, when we know X is not -0
855 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000856 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000857 return Op0;
858
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000859 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000860 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000861 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
862 return X;
863
864 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000865 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000866 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
867 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000868
Benjamin Kramer228680d2015-06-14 21:01:20 +0000869 // fsub nnan x, x ==> 0.0
870 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000871 return Constant::getNullValue(Op0->getType());
872
Craig Topper9f008862014-04-15 04:59:12 +0000873 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000874}
875
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000876/// Given the operands for an FMul, see if we can fold the result
877static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
878 FastMathFlags FMF,
879 const Query &Q,
880 unsigned MaxRecurse) {
881 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000882 if (Constant *CRHS = dyn_cast<Constant>(Op1))
883 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000884
885 // Canonicalize the constant to the RHS.
886 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000887 }
888
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000889 // fmul X, 1.0 ==> X
890 if (match(Op1, m_FPOne()))
891 return Op0;
892
893 // fmul nnan nsz X, 0 ==> 0
894 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
895 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000896
Craig Topper9f008862014-04-15 04:59:12 +0000897 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000898}
899
Sanjay Patel472cc782016-01-11 22:14:42 +0000900/// Given operands for a Mul, see if we can fold the result.
901/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000902static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
903 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000904 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000905 if (Constant *CRHS = dyn_cast<Constant>(Op1))
906 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000907
908 // Canonicalize the constant to the RHS.
909 std::swap(Op0, Op1);
910 }
911
912 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000913 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000914 return Constant::getNullValue(Op0->getType());
915
916 // X * 0 -> 0
917 if (match(Op1, m_Zero()))
918 return Op1;
919
920 // X * 1 -> X
921 if (match(Op1, m_One()))
922 return Op0;
923
Duncan Sandsb67edc62011-01-30 18:03:50 +0000924 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000925 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000926 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
927 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
928 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000929
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000930 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000931 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000932 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000933 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000934
935 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000936 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000937 MaxRecurse))
938 return V;
939
940 // Mul distributes over Add. Try some generic simplifications based on this.
941 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000942 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000943 return V;
944
945 // If the operation is with the result of a select instruction, check whether
946 // operating on either branch of the select always yields the same value.
947 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000948 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000949 MaxRecurse))
950 return V;
951
952 // If the operation is with the result of a phi instruction, check whether
953 // operating on all incoming values of the phi always yields the same value.
954 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000955 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000956 MaxRecurse))
957 return V;
958
Craig Topper9f008862014-04-15 04:59:12 +0000959 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000960}
961
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000962Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000963 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000964 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000965 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +0000966 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000967 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000968 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000969}
970
971Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000972 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000973 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000974 const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +0000975 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000976 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000977 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000978}
979
Chandler Carruth66b31302015-01-04 12:03:27 +0000980Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000981 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000982 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000983 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +0000984 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000985 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000986 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000987}
988
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000989Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000990 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000991 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +0000992 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +0000993 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000994 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000995}
996
Sanjay Patel472cc782016-01-11 22:14:42 +0000997/// Given operands for an SDiv or UDiv, see if we can fold the result.
998/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +0000999static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001000 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001001 if (Constant *C0 = dyn_cast<Constant>(Op0))
1002 if (Constant *C1 = dyn_cast<Constant>(Op1))
1003 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +00001004
Duncan Sands65995fa2011-01-28 18:50:50 +00001005 bool isSigned = Opcode == Instruction::SDiv;
1006
Duncan Sands771e82a2011-01-28 16:51:11 +00001007 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001008 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001009 return Op1;
1010
David Majnemer71dc8fb2014-12-10 07:52:18 +00001011 // X / 0 -> undef, we don't need to preserve faults!
1012 if (match(Op1, m_Zero()))
1013 return UndefValue::get(Op1->getType());
1014
Duncan Sands771e82a2011-01-28 16:51:11 +00001015 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001016 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001017 return Constant::getNullValue(Op0->getType());
1018
1019 // 0 / X -> 0, we don't need to preserve faults!
1020 if (match(Op0, m_Zero()))
1021 return Op0;
1022
1023 // X / 1 -> X
1024 if (match(Op1, m_One()))
1025 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001026
1027 if (Op0->getType()->isIntegerTy(1))
1028 // It can't be division by zero, hence it must be division by one.
1029 return Op0;
1030
1031 // X / X -> 1
1032 if (Op0 == Op1)
1033 return ConstantInt::get(Op0->getType(), 1);
1034
1035 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001036 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001037 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1038 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001039 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001040 // If the Mul knows it does not overflow, then we are good to go.
1041 if ((isSigned && Mul->hasNoSignedWrap()) ||
1042 (!isSigned && Mul->hasNoUnsignedWrap()))
1043 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001044 // If X has the form X = A / Y then X * Y cannot overflow.
1045 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1046 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1047 return X;
1048 }
1049
Duncan Sands65995fa2011-01-28 18:50:50 +00001050 // (X rem Y) / Y -> 0
1051 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1052 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1053 return Constant::getNullValue(Op0->getType());
1054
David Majnemercb9d5962014-10-11 10:20:01 +00001055 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1056 ConstantInt *C1, *C2;
1057 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1058 match(Op1, m_ConstantInt(C2))) {
1059 bool Overflow;
1060 C1->getValue().umul_ov(C2->getValue(), Overflow);
1061 if (Overflow)
1062 return Constant::getNullValue(Op0->getType());
1063 }
1064
Duncan Sands65995fa2011-01-28 18:50:50 +00001065 // If the operation is with the result of a select instruction, check whether
1066 // operating on either branch of the select always yields the same value.
1067 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001068 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001069 return V;
1070
1071 // If the operation is with the result of a phi instruction, check whether
1072 // operating on all incoming values of the phi always yields the same value.
1073 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001074 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001075 return V;
1076
Craig Topper9f008862014-04-15 04:59:12 +00001077 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001078}
1079
Sanjay Patel472cc782016-01-11 22:14:42 +00001080/// Given operands for an SDiv, see if we can fold the result.
1081/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001082static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1083 unsigned MaxRecurse) {
1084 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001085 return V;
1086
Craig Topper9f008862014-04-15 04:59:12 +00001087 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001088}
1089
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001090Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001091 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001092 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001093 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001094 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001095 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001096}
1097
Sanjay Patel472cc782016-01-11 22:14:42 +00001098/// Given operands for a UDiv, see if we can fold the result.
1099/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001100static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1101 unsigned MaxRecurse) {
1102 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001103 return V;
1104
Craig Topper9f008862014-04-15 04:59:12 +00001105 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001106}
1107
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001108Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001109 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001110 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001111 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001112 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001113 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001114}
1115
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001116static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1117 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001118 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001119 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001120 return Op0;
1121
1122 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001123 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001124 return Op1;
1125
Zia Ansari394cef82016-12-08 23:27:40 +00001126 // X / 1.0 -> X
1127 if (match(Op1, m_FPOne()))
1128 return Op0;
1129
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001130 // 0 / X -> 0
1131 // Requires that NaNs are off (X could be zero) and signed zeroes are
1132 // ignored (X could be positive or negative, so the output sign is unknown).
1133 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1134 return Op0;
1135
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001136 if (FMF.noNaNs()) {
1137 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001138 if (Op0 == Op1)
1139 return ConstantFP::get(Op0->getType(), 1.0);
1140
1141 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001142 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001143 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1144 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1145 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1146 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1147 BinaryOperator::getFNegArgument(Op1) == Op0))
1148 return ConstantFP::get(Op0->getType(), -1.0);
1149 }
1150
Craig Topper9f008862014-04-15 04:59:12 +00001151 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001152}
1153
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001154Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001155 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001156 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001157 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001158 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001159 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001160 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001161}
1162
Sanjay Patel472cc782016-01-11 22:14:42 +00001163/// Given operands for an SRem or URem, see if we can fold the result.
1164/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001165static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001166 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001167 if (Constant *C0 = dyn_cast<Constant>(Op0))
1168 if (Constant *C1 = dyn_cast<Constant>(Op1))
1169 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001170
Duncan Sandsa3e36992011-05-02 16:27:02 +00001171 // X % undef -> undef
1172 if (match(Op1, m_Undef()))
1173 return Op1;
1174
1175 // undef % X -> 0
1176 if (match(Op0, m_Undef()))
1177 return Constant::getNullValue(Op0->getType());
1178
1179 // 0 % X -> 0, we don't need to preserve faults!
1180 if (match(Op0, m_Zero()))
1181 return Op0;
1182
1183 // X % 0 -> undef, we don't need to preserve faults!
1184 if (match(Op1, m_Zero()))
1185 return UndefValue::get(Op0->getType());
1186
1187 // X % 1 -> 0
1188 if (match(Op1, m_One()))
1189 return Constant::getNullValue(Op0->getType());
1190
1191 if (Op0->getType()->isIntegerTy(1))
1192 // It can't be remainder by zero, hence it must be remainder by one.
1193 return Constant::getNullValue(Op0->getType());
1194
1195 // X % X -> 0
1196 if (Op0 == Op1)
1197 return Constant::getNullValue(Op0->getType());
1198
David Majnemerb435a422014-09-17 04:16:35 +00001199 // (X % Y) % Y -> X % Y
1200 if ((Opcode == Instruction::SRem &&
1201 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1202 (Opcode == Instruction::URem &&
1203 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001204 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001205
Duncan Sandsa3e36992011-05-02 16:27:02 +00001206 // If the operation is with the result of a select instruction, check whether
1207 // operating on either branch of the select always yields the same value.
1208 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001209 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001210 return V;
1211
1212 // If the operation is with the result of a phi instruction, check whether
1213 // operating on all incoming values of the phi always yields the same value.
1214 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001215 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001216 return V;
1217
Craig Topper9f008862014-04-15 04:59:12 +00001218 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001219}
1220
Sanjay Patel472cc782016-01-11 22:14:42 +00001221/// Given operands for an SRem, see if we can fold the result.
1222/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001223static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1224 unsigned MaxRecurse) {
1225 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001226 return V;
1227
Craig Topper9f008862014-04-15 04:59:12 +00001228 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001229}
1230
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001231Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001232 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001233 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001234 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001235 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001236 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001237}
1238
Sanjay Patel472cc782016-01-11 22:14:42 +00001239/// Given operands for a URem, see if we can fold the result.
1240/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001241static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001242 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001243 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001244 return V;
1245
Craig Topper9f008862014-04-15 04:59:12 +00001246 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001247}
1248
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001249Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001250 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001251 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001252 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001253 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001254 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001255}
1256
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001257static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1258 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001259 // undef % X -> undef (the undef could be a snan).
1260 if (match(Op0, m_Undef()))
1261 return Op0;
1262
1263 // X % undef -> undef
1264 if (match(Op1, m_Undef()))
1265 return Op1;
1266
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001267 // 0 % X -> 0
1268 // Requires that NaNs are off (X could be zero) and signed zeroes are
1269 // ignored (X could be positive or negative, so the output sign is unknown).
1270 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1271 return Op0;
1272
Craig Topper9f008862014-04-15 04:59:12 +00001273 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001274}
1275
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001276Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001277 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001278 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001279 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001280 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001281 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001282 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001283}
1284
Sanjay Patel472cc782016-01-11 22:14:42 +00001285/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001286static bool isUndefShift(Value *Amount) {
1287 Constant *C = dyn_cast<Constant>(Amount);
1288 if (!C)
1289 return false;
1290
1291 // X shift by undef -> undef because it may shift by the bitwidth.
1292 if (isa<UndefValue>(C))
1293 return true;
1294
1295 // Shifting by the bitwidth or more is undefined.
1296 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1297 if (CI->getValue().getLimitedValue() >=
1298 CI->getType()->getScalarSizeInBits())
1299 return true;
1300
1301 // If all lanes of a vector shift are undefined the whole shift is.
1302 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1303 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1304 if (!isUndefShift(C->getAggregateElement(I)))
1305 return false;
1306 return true;
1307 }
1308
1309 return false;
1310}
1311
Sanjay Patel472cc782016-01-11 22:14:42 +00001312/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1313/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001314static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001315 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001316 if (Constant *C0 = dyn_cast<Constant>(Op0))
1317 if (Constant *C1 = dyn_cast<Constant>(Op1))
1318 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001319
Duncan Sands571fd9a2011-01-14 14:44:12 +00001320 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001321 if (match(Op0, m_Zero()))
1322 return Op0;
1323
Duncan Sands571fd9a2011-01-14 14:44:12 +00001324 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001325 if (match(Op1, m_Zero()))
1326 return Op0;
1327
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001328 // Fold undefined shifts.
1329 if (isUndefShift(Op1))
1330 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001331
Duncan Sands571fd9a2011-01-14 14:44:12 +00001332 // If the operation is with the result of a select instruction, check whether
1333 // operating on either branch of the select always yields the same value.
1334 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001335 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001336 return V;
1337
1338 // If the operation is with the result of a phi instruction, check whether
1339 // operating on all incoming values of the phi always yields the same value.
1340 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001341 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001342 return V;
1343
Sanjay Patel6786bc52016-05-10 20:46:54 +00001344 // If any bits in the shift amount make that value greater than or equal to
1345 // the number of bits in the type, the shift is undefined.
1346 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1347 APInt KnownZero(BitWidth, 0);
1348 APInt KnownOne(BitWidth, 0);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001349 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001350 if (KnownOne.getLimitedValue() >= BitWidth)
1351 return UndefValue::get(Op0->getType());
1352
1353 // If all valid bits in the shift amount are known zero, the first operand is
1354 // unchanged.
1355 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1356 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1357 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1358 return Op0;
1359
Craig Topper9f008862014-04-15 04:59:12 +00001360 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001361}
1362
David Majnemerbf7550e2014-11-05 00:59:59 +00001363/// \brief Given operands for an Shl, LShr or AShr, see if we can
1364/// fold the result. If not, this returns null.
1365static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1366 bool isExact, const Query &Q,
1367 unsigned MaxRecurse) {
1368 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1369 return V;
1370
1371 // X >> X -> 0
1372 if (Op0 == Op1)
1373 return Constant::getNullValue(Op0->getType());
1374
David Majnemer65c52ae2014-12-17 01:54:33 +00001375 // undef >> X -> 0
1376 // undef >> X -> undef (if it's exact)
1377 if (match(Op0, m_Undef()))
1378 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1379
David Majnemerbf7550e2014-11-05 00:59:59 +00001380 // The low bit cannot be shifted out of an exact shift if it is set.
1381 if (isExact) {
1382 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1383 APInt Op0KnownZero(BitWidth, 0);
1384 APInt Op0KnownOne(BitWidth, 0);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001385 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.CxtI,
1386 Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001387 if (Op0KnownOne[0])
1388 return Op0;
1389 }
1390
1391 return nullptr;
1392}
1393
Sanjay Patel472cc782016-01-11 22:14:42 +00001394/// Given operands for an Shl, see if we can fold the result.
1395/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001396static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001397 const Query &Q, unsigned MaxRecurse) {
1398 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001399 return V;
1400
1401 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001402 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001403 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001404 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001405
Chris Lattner9e4aa022011-02-09 17:15:04 +00001406 // (X >> A) << A -> X
1407 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001408 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001409 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001410 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001411}
1412
Chris Lattner9e4aa022011-02-09 17:15:04 +00001413Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001414 const DataLayout &DL, const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001415 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001416 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001417 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001418 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001419}
1420
Sanjay Patel472cc782016-01-11 22:14:42 +00001421/// Given operands for an LShr, see if we can fold the result.
1422/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001423static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001424 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001425 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1426 MaxRecurse))
1427 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001428
Chris Lattner9e4aa022011-02-09 17:15:04 +00001429 // (X << A) >> A -> X
1430 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001431 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001432 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001433
Craig Topper9f008862014-04-15 04:59:12 +00001434 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001435}
1436
Chris Lattner9e4aa022011-02-09 17:15:04 +00001437Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001438 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001439 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001440 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001441 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001442 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001443 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001444}
1445
Sanjay Patel472cc782016-01-11 22:14:42 +00001446/// Given operands for an AShr, see if we can fold the result.
1447/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001448static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001449 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001450 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1451 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001452 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001453
1454 // all ones >>a X -> all ones
1455 if (match(Op0, m_AllOnes()))
1456 return Op0;
1457
Chris Lattner9e4aa022011-02-09 17:15:04 +00001458 // (X << A) >> A -> X
1459 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001460 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001461 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001462
Suyog Sarda68862412014-07-17 06:28:15 +00001463 // Arithmetic shifting an all-sign-bit value is a no-op.
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001464 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001465 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1466 return Op0;
1467
Craig Topper9f008862014-04-15 04:59:12 +00001468 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001469}
1470
Chris Lattner9e4aa022011-02-09 17:15:04 +00001471Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001472 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001473 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001474 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001475 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001476 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001477 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001478}
1479
David Majnemer1af36e52014-12-06 10:51:40 +00001480static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1481 ICmpInst *UnsignedICmp, bool IsAnd) {
1482 Value *X, *Y;
1483
1484 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001485 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1486 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001487 return nullptr;
1488
1489 ICmpInst::Predicate UnsignedPred;
1490 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1491 ICmpInst::isUnsigned(UnsignedPred))
1492 ;
1493 else if (match(UnsignedICmp,
1494 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1495 ICmpInst::isUnsigned(UnsignedPred))
1496 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1497 else
1498 return nullptr;
1499
1500 // X < Y && Y != 0 --> X < Y
1501 // X < Y || Y != 0 --> Y != 0
1502 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1503 return IsAnd ? UnsignedICmp : ZeroICmp;
1504
1505 // X >= Y || Y != 0 --> true
1506 // X >= Y || Y == 0 --> X >= Y
1507 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1508 if (EqPred == ICmpInst::ICMP_NE)
1509 return getTrue(UnsignedICmp->getType());
1510 return UnsignedICmp;
1511 }
1512
David Majnemerd5b3aa42014-12-08 18:30:43 +00001513 // X < Y && Y == 0 --> false
1514 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1515 IsAnd)
1516 return getFalse(UnsignedICmp->getType());
1517
David Majnemer1af36e52014-12-06 10:51:40 +00001518 return nullptr;
1519}
1520
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001521/// Commuted variants are assumed to be handled by calling this function again
1522/// with the parameters swapped.
1523static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1524 ICmpInst::Predicate Pred0, Pred1;
1525 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001526 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1527 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001528 return nullptr;
1529
1530 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1531 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1532 // can eliminate Op1 from this 'and'.
1533 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1534 return Op0;
1535
1536 // Check for any combination of predicates that are guaranteed to be disjoint.
1537 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1538 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1539 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1540 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1541 return getFalse(Op0->getType());
1542
1543 return nullptr;
1544}
1545
1546/// Commuted variants are assumed to be handled by calling this function again
1547/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001548static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001549 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1550 return X;
1551
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001552 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1553 return X;
1554
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001555 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001556 Type *ITy = Op0->getType();
1557 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001558 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001559 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001560 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1561 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1562 // Make a constant range that's the intersection of the two icmp ranges.
1563 // If the intersection is empty, we know that the result is false.
1564 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1565 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1566 if (Range0.intersectWith(Range1).isEmptySet())
1567 return getFalse(ITy);
1568 }
1569
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001570 // (icmp (add V, C0), C1) & (icmp V, C0)
1571 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001572 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001573
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001574 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001575 return nullptr;
1576
David Majnemera315bd82014-09-15 08:15:28 +00001577 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001578 if (AddInst->getOperand(1) != Op1->getOperand(1))
1579 return nullptr;
1580
David Majnemera315bd82014-09-15 08:15:28 +00001581 bool isNSW = AddInst->hasNoSignedWrap();
1582 bool isNUW = AddInst->hasNoUnsignedWrap();
1583
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001584 const APInt Delta = *C1 - *C0;
1585 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001586 if (Delta == 2) {
1587 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1588 return getFalse(ITy);
1589 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1590 return getFalse(ITy);
1591 }
1592 if (Delta == 1) {
1593 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1594 return getFalse(ITy);
1595 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1596 return getFalse(ITy);
1597 }
1598 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001599 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001600 if (Delta == 2)
1601 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1602 return getFalse(ITy);
1603 if (Delta == 1)
1604 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1605 return getFalse(ITy);
1606 }
1607
1608 return nullptr;
1609}
1610
Sanjay Patel472cc782016-01-11 22:14:42 +00001611/// Given operands for an And, see if we can fold the result.
1612/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001613static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001614 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001615 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001616 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1617 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001618
Chris Lattnera71e9d62009-11-10 00:55:12 +00001619 // Canonicalize the constant to the RHS.
1620 std::swap(Op0, Op1);
1621 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001622
Chris Lattnera71e9d62009-11-10 00:55:12 +00001623 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001624 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001625 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001626
Chris Lattnera71e9d62009-11-10 00:55:12 +00001627 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001628 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001629 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001630
Duncan Sandsc89ac072010-11-17 18:52:15 +00001631 // X & 0 = 0
1632 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001633 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001634
Duncan Sandsc89ac072010-11-17 18:52:15 +00001635 // X & -1 = X
1636 if (match(Op1, m_AllOnes()))
1637 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001638
Chris Lattnera71e9d62009-11-10 00:55:12 +00001639 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001640 if (match(Op0, m_Not(m_Specific(Op1))) ||
1641 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001642 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001643
Chris Lattnera71e9d62009-11-10 00:55:12 +00001644 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001645 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001646 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001647 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001648 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001649
Chris Lattnera71e9d62009-11-10 00:55:12 +00001650 // A & (A | ?) = A
1651 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001652 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001653 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001654
Duncan Sandsba286d72011-10-26 20:55:21 +00001655 // A & (-A) = A if A is a power of two or zero.
1656 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1657 match(Op1, m_Neg(m_Specific(Op0)))) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001658 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.CxtI, Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001659 return Op0;
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001660 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.CxtI, Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001661 return Op1;
1662 }
1663
David Majnemera315bd82014-09-15 08:15:28 +00001664 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1665 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1666 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1667 return V;
1668 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1669 return V;
1670 }
1671 }
1672
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001673 // The compares may be hidden behind casts. Look through those and try the
1674 // same folds as above.
1675 auto *Cast0 = dyn_cast<CastInst>(Op0);
1676 auto *Cast1 = dyn_cast<CastInst>(Op1);
1677 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1678 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1679 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1680 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1681 if (Cmp0 && Cmp1) {
1682 Instruction::CastOps CastOpc = Cast0->getOpcode();
1683 Type *ResultType = Cast0->getType();
1684 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1685 return ConstantExpr::getCast(CastOpc, V, ResultType);
1686 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1687 return ConstantExpr::getCast(CastOpc, V, ResultType);
1688 }
1689 }
1690
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001691 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001692 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1693 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001694 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001695
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001696 // And distributes over Or. Try some generic simplifications based on this.
1697 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001698 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001699 return V;
1700
1701 // And distributes over Xor. Try some generic simplifications based on this.
1702 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001703 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001704 return V;
1705
Duncan Sandsb0579e92010-11-10 13:00:08 +00001706 // If the operation is with the result of a select instruction, check whether
1707 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001708 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001709 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1710 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001711 return V;
1712
1713 // If the operation is with the result of a phi instruction, check whether
1714 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001715 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001716 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001717 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001718 return V;
1719
Craig Topper9f008862014-04-15 04:59:12 +00001720 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001721}
1722
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001723Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001724 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001725 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001726 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001727 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001728 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001729}
1730
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001731/// Commuted variants are assumed to be handled by calling this function again
1732/// with the parameters swapped.
1733static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1734 ICmpInst::Predicate Pred0, Pred1;
1735 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001736 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1737 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001738 return nullptr;
1739
1740 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1741 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1742 // can eliminate Op0 from this 'or'.
1743 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1744 return Op1;
1745
1746 // Check for any combination of predicates that cover the entire range of
1747 // possibilities.
1748 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1749 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1750 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1751 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1752 return getTrue(Op0->getType());
1753
1754 return nullptr;
1755}
1756
1757/// Commuted variants are assumed to be handled by calling this function again
1758/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001759static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001760 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1761 return X;
1762
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001763 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1764 return X;
1765
Sanjay Patel220a8732016-09-28 14:27:21 +00001766 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001767 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001768 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001769 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001770 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001771 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001772
Sanjay Patel220a8732016-09-28 14:27:21 +00001773 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1774 return nullptr;
1775
1776 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1777 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001778 return nullptr;
1779
1780 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001781 bool isNSW = AddInst->hasNoSignedWrap();
1782 bool isNUW = AddInst->hasNoUnsignedWrap();
1783
Sanjay Patel220a8732016-09-28 14:27:21 +00001784 const APInt Delta = *C1 - *C0;
1785 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001786 if (Delta == 2) {
1787 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1788 return getTrue(ITy);
1789 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1790 return getTrue(ITy);
1791 }
1792 if (Delta == 1) {
1793 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1794 return getTrue(ITy);
1795 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1796 return getTrue(ITy);
1797 }
1798 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001799 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001800 if (Delta == 2)
1801 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1802 return getTrue(ITy);
1803 if (Delta == 1)
1804 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1805 return getTrue(ITy);
1806 }
1807
1808 return nullptr;
1809}
1810
Sanjay Patel472cc782016-01-11 22:14:42 +00001811/// Given operands for an Or, see if we can fold the result.
1812/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001813static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1814 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001815 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001816 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1817 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001818
Chris Lattnera71e9d62009-11-10 00:55:12 +00001819 // Canonicalize the constant to the RHS.
1820 std::swap(Op0, Op1);
1821 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001822
Chris Lattnera71e9d62009-11-10 00:55:12 +00001823 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001824 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001825 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001826
Chris Lattnera71e9d62009-11-10 00:55:12 +00001827 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001828 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001829 return Op0;
1830
Duncan Sandsc89ac072010-11-17 18:52:15 +00001831 // X | 0 = X
1832 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001833 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001834
Duncan Sandsc89ac072010-11-17 18:52:15 +00001835 // X | -1 = -1
1836 if (match(Op1, m_AllOnes()))
1837 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001838
Chris Lattnera71e9d62009-11-10 00:55:12 +00001839 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001840 if (match(Op0, m_Not(m_Specific(Op1))) ||
1841 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001842 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001843
Chris Lattnera71e9d62009-11-10 00:55:12 +00001844 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001845 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001846 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001847 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001848 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001849
Chris Lattnera71e9d62009-11-10 00:55:12 +00001850 // A | (A & ?) = A
1851 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001852 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001853 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001854
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001855 // ~(A & ?) | A = -1
1856 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1857 (A == Op1 || B == Op1))
1858 return Constant::getAllOnesValue(Op1->getType());
1859
1860 // A | ~(A & ?) = -1
1861 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1862 (A == Op0 || B == Op0))
1863 return Constant::getAllOnesValue(Op0->getType());
1864
David Majnemera315bd82014-09-15 08:15:28 +00001865 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1866 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1867 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1868 return V;
1869 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1870 return V;
1871 }
1872 }
1873
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001874 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001875 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1876 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001877 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001878
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001879 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001880 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1881 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001882 return V;
1883
Duncan Sandsb0579e92010-11-10 13:00:08 +00001884 // If the operation is with the result of a select instruction, check whether
1885 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001886 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001887 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001888 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001889 return V;
1890
Nick Lewycky8561a492014-06-19 03:51:46 +00001891 // (A & C)|(B & D)
1892 Value *C = nullptr, *D = nullptr;
1893 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1894 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1895 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1896 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1897 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1898 // (A & C1)|(B & C2)
1899 // If we have: ((V + N) & C1) | (V & C2)
1900 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1901 // replace with V+N.
1902 Value *V1, *V2;
1903 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1904 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1905 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001906 if (V1 == B &&
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001907 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001908 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001909 if (V2 == B &&
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001910 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001911 return A;
1912 }
1913 // Or commutes, try both ways.
1914 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1915 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1916 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001917 if (V1 == A &&
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001918 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001919 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001920 if (V2 == A &&
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001921 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001922 return B;
1923 }
1924 }
1925 }
1926
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001927 // If the operation is with the result of a phi instruction, check whether
1928 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001929 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001930 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001931 return V;
1932
Craig Topper9f008862014-04-15 04:59:12 +00001933 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001934}
1935
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001936Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001937 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001938 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001939 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001940 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001941 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001942}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001943
Sanjay Patel472cc782016-01-11 22:14:42 +00001944/// Given operands for a Xor, see if we can fold the result.
1945/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001946static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1947 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001948 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001949 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1950 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001951
1952 // Canonicalize the constant to the RHS.
1953 std::swap(Op0, Op1);
1954 }
1955
1956 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001957 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001958 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001959
1960 // A ^ 0 = A
1961 if (match(Op1, m_Zero()))
1962 return Op0;
1963
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001964 // A ^ A = 0
1965 if (Op0 == Op1)
1966 return Constant::getNullValue(Op0->getType());
1967
Duncan Sandsc89ac072010-11-17 18:52:15 +00001968 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001969 if (match(Op0, m_Not(m_Specific(Op1))) ||
1970 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001971 return Constant::getAllOnesValue(Op0->getType());
1972
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001973 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001974 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1975 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001976 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001977
Duncan Sandsb238de02010-11-19 09:20:39 +00001978 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1979 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1980 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1981 // only if B and C are equal. If B and C are equal then (since we assume
1982 // that operands have already been simplified) "select(cond, B, C)" should
1983 // have been simplified to the common value of B and C already. Analysing
1984 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1985 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001986
Craig Topper9f008862014-04-15 04:59:12 +00001987 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001988}
1989
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001990Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001991 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001992 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00001993 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00001994 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001995 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001996}
1997
Chris Lattner229907c2011-07-18 04:54:35 +00001998static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001999 return CmpInst::makeCmpResultType(Op->getType());
2000}
2001
Sanjay Patel472cc782016-01-11 22:14:42 +00002002/// Rummage around inside V looking for something equivalent to the comparison
2003/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2004/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002005static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2006 Value *LHS, Value *RHS) {
2007 SelectInst *SI = dyn_cast<SelectInst>(V);
2008 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002009 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002010 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2011 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002012 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002013 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2014 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2015 return Cmp;
2016 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2017 LHS == CmpRHS && RHS == CmpLHS)
2018 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002019 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002020}
2021
Dan Gohman9631d902013-02-01 00:49:06 +00002022// A significant optimization not implemented here is assuming that alloca
2023// addresses are not equal to incoming argument values. They don't *alias*,
2024// as we say, but that doesn't mean they aren't equal, so we take a
2025// conservative approach.
2026//
2027// This is inspired in part by C++11 5.10p1:
2028// "Two pointers of the same type compare equal if and only if they are both
2029// null, both point to the same function, or both represent the same
2030// address."
2031//
2032// This is pretty permissive.
2033//
2034// It's also partly due to C11 6.5.9p6:
2035// "Two pointers compare equal if and only if both are null pointers, both are
2036// pointers to the same object (including a pointer to an object and a
2037// subobject at its beginning) or function, both are pointers to one past the
2038// last element of the same array object, or one is a pointer to one past the
2039// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002040// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002041// object in the address space.)
2042//
2043// C11's version is more restrictive, however there's no reason why an argument
2044// couldn't be a one-past-the-end value for a stack object in the caller and be
2045// equal to the beginning of a stack object in the callee.
2046//
2047// If the C and C++ standards are ever made sufficiently restrictive in this
2048// area, it may be possible to update LLVM's semantics accordingly and reinstate
2049// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002050static Constant *
2051computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2052 const DominatorTree *DT, CmpInst::Predicate Pred,
2053 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002054 // First, skip past any trivial no-ops.
2055 LHS = LHS->stripPointerCasts();
2056 RHS = RHS->stripPointerCasts();
2057
2058 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002059 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002060 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2061 return ConstantInt::get(GetCompareTy(LHS),
2062 !CmpInst::isTrueWhenEqual(Pred));
2063
Chandler Carruth8059c842012-03-25 21:28:14 +00002064 // We can only fold certain predicates on pointer comparisons.
2065 switch (Pred) {
2066 default:
Craig Topper9f008862014-04-15 04:59:12 +00002067 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002068
2069 // Equality comaprisons are easy to fold.
2070 case CmpInst::ICMP_EQ:
2071 case CmpInst::ICMP_NE:
2072 break;
2073
2074 // We can only handle unsigned relational comparisons because 'inbounds' on
2075 // a GEP only protects against unsigned wrapping.
2076 case CmpInst::ICMP_UGT:
2077 case CmpInst::ICMP_UGE:
2078 case CmpInst::ICMP_ULT:
2079 case CmpInst::ICMP_ULE:
2080 // However, we have to switch them to their signed variants to handle
2081 // negative indices from the base pointer.
2082 Pred = ICmpInst::getSignedPredicate(Pred);
2083 break;
2084 }
2085
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002086 // Strip off any constant offsets so that we can reason about them.
2087 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2088 // here and compare base addresses like AliasAnalysis does, however there are
2089 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2090 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2091 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002092 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2093 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002094
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002095 // If LHS and RHS are related via constant offsets to the same base
2096 // value, we can replace it with an icmp which just compares the offsets.
2097 if (LHS == RHS)
2098 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002099
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002100 // Various optimizations for (in)equality comparisons.
2101 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2102 // Different non-empty allocations that exist at the same time have
2103 // different addresses (if the program can tell). Global variables always
2104 // exist, so they always exist during the lifetime of each other and all
2105 // allocas. Two different allocas usually have different addresses...
2106 //
2107 // However, if there's an @llvm.stackrestore dynamically in between two
2108 // allocas, they may have the same address. It's tempting to reduce the
2109 // scope of the problem by only looking at *static* allocas here. That would
2110 // cover the majority of allocas while significantly reducing the likelihood
2111 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2112 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2113 // an entry block. Also, if we have a block that's not attached to a
2114 // function, we can't tell if it's "static" under the current definition.
2115 // Theoretically, this problem could be fixed by creating a new kind of
2116 // instruction kind specifically for static allocas. Such a new instruction
2117 // could be required to be at the top of the entry block, thus preventing it
2118 // from being subject to a @llvm.stackrestore. Instcombine could even
2119 // convert regular allocas into these special allocas. It'd be nifty.
2120 // However, until then, this problem remains open.
2121 //
2122 // So, we'll assume that two non-empty allocas have different addresses
2123 // for now.
2124 //
2125 // With all that, if the offsets are within the bounds of their allocations
2126 // (and not one-past-the-end! so we can't use inbounds!), and their
2127 // allocations aren't the same, the pointers are not equal.
2128 //
2129 // Note that it's not necessary to check for LHS being a global variable
2130 // address, due to canonicalization and constant folding.
2131 if (isa<AllocaInst>(LHS) &&
2132 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002133 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2134 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002135 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002136 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002137 getObjectSize(LHS, LHSSize, DL, TLI) &&
2138 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002139 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2140 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002141 if (!LHSOffsetValue.isNegative() &&
2142 !RHSOffsetValue.isNegative() &&
2143 LHSOffsetValue.ult(LHSSize) &&
2144 RHSOffsetValue.ult(RHSSize)) {
2145 return ConstantInt::get(GetCompareTy(LHS),
2146 !CmpInst::isTrueWhenEqual(Pred));
2147 }
2148 }
2149
2150 // Repeat the above check but this time without depending on DataLayout
2151 // or being able to compute a precise size.
2152 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2153 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2154 LHSOffset->isNullValue() &&
2155 RHSOffset->isNullValue())
2156 return ConstantInt::get(GetCompareTy(LHS),
2157 !CmpInst::isTrueWhenEqual(Pred));
2158 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002159
2160 // Even if an non-inbounds GEP occurs along the path we can still optimize
2161 // equality comparisons concerning the result. We avoid walking the whole
2162 // chain again by starting where the last calls to
2163 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002164 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2165 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002166 if (LHS == RHS)
2167 return ConstantExpr::getICmp(Pred,
2168 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2169 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002170
2171 // If one side of the equality comparison must come from a noalias call
2172 // (meaning a system memory allocation function), and the other side must
2173 // come from a pointer that cannot overlap with dynamically-allocated
2174 // memory within the lifetime of the current function (allocas, byval
2175 // arguments, globals), then determine the comparison result here.
2176 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2177 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2178 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2179
2180 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002181 auto IsNAC = [](ArrayRef<Value *> Objects) {
2182 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002183 };
2184
2185 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002186 // noalias calls. For allocas, we consider only static ones (dynamic
2187 // allocas might be transformed into calls to malloc not simultaneously
2188 // live with the compared-to allocation). For globals, we exclude symbols
2189 // that might be resolve lazily to symbols in another dynamically-loaded
2190 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002191 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2192 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002193 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2194 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2195 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2196 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002197 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002198 !GV->isThreadLocal();
2199 if (const Argument *A = dyn_cast<Argument>(V))
2200 return A->hasByValAttr();
2201 return false;
2202 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002203 };
2204
2205 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2206 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2207 return ConstantInt::get(GetCompareTy(LHS),
2208 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002209
2210 // Fold comparisons for non-escaping pointer even if the allocation call
2211 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2212 // dynamic allocation call could be either of the operands.
2213 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002214 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002215 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002216 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002217 MI = RHS;
2218 // FIXME: We should also fold the compare when the pointer escapes, but the
2219 // compare dominates the pointer escape
2220 if (MI && !PointerMayBeCaptured(MI, true, true))
2221 return ConstantInt::get(GetCompareTy(LHS),
2222 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002223 }
2224
2225 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002226 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002227}
Chris Lattner01990f02012-02-24 19:01:58 +00002228
Sanjay Pateldc65a272016-12-03 17:30:22 +00002229/// Fold an icmp when its operands have i1 scalar type.
2230static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2231 Value *RHS, const Query &Q) {
2232 Type *ITy = GetCompareTy(LHS); // The return type.
2233 Type *OpTy = LHS->getType(); // The operand type.
2234 if (!OpTy->getScalarType()->isIntegerTy(1))
2235 return nullptr;
2236
2237 switch (Pred) {
2238 default:
2239 break;
2240 case ICmpInst::ICMP_EQ:
2241 // X == 1 -> X
2242 if (match(RHS, m_One()))
2243 return LHS;
2244 break;
2245 case ICmpInst::ICMP_NE:
2246 // X != 0 -> X
2247 if (match(RHS, m_Zero()))
2248 return LHS;
2249 break;
2250 case ICmpInst::ICMP_UGT:
2251 // X >u 0 -> X
2252 if (match(RHS, m_Zero()))
2253 return LHS;
2254 break;
2255 case ICmpInst::ICMP_UGE:
2256 // X >=u 1 -> X
2257 if (match(RHS, m_One()))
2258 return LHS;
2259 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2260 return getTrue(ITy);
2261 break;
2262 case ICmpInst::ICMP_SGE:
2263 /// For signed comparison, the values for an i1 are 0 and -1
2264 /// respectively. This maps into a truth table of:
2265 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2266 /// 0 | 0 | 1 (0 >= 0) | 1
2267 /// 0 | 1 | 1 (0 >= -1) | 1
2268 /// 1 | 0 | 0 (-1 >= 0) | 0
2269 /// 1 | 1 | 1 (-1 >= -1) | 1
2270 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2271 return getTrue(ITy);
2272 break;
2273 case ICmpInst::ICMP_SLT:
2274 // X <s 0 -> X
2275 if (match(RHS, m_Zero()))
2276 return LHS;
2277 break;
2278 case ICmpInst::ICMP_SLE:
2279 // X <=s -1 -> X
2280 if (match(RHS, m_One()))
2281 return LHS;
2282 break;
2283 case ICmpInst::ICMP_ULE:
2284 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2285 return getTrue(ITy);
2286 break;
2287 }
2288
2289 return nullptr;
2290}
2291
2292/// Try hard to fold icmp with zero RHS because this is a common case.
2293static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2294 Value *RHS, const Query &Q) {
2295 if (!match(RHS, m_Zero()))
2296 return nullptr;
2297
2298 Type *ITy = GetCompareTy(LHS); // The return type.
2299 bool LHSKnownNonNegative, LHSKnownNegative;
2300 switch (Pred) {
2301 default:
2302 llvm_unreachable("Unknown ICmp predicate!");
2303 case ICmpInst::ICMP_ULT:
2304 return getFalse(ITy);
2305 case ICmpInst::ICMP_UGE:
2306 return getTrue(ITy);
2307 case ICmpInst::ICMP_EQ:
2308 case ICmpInst::ICMP_ULE:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002309 if (isKnownNonZero(LHS, Q.DL, 0, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002310 return getFalse(ITy);
2311 break;
2312 case ICmpInst::ICMP_NE:
2313 case ICmpInst::ICMP_UGT:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002314 if (isKnownNonZero(LHS, Q.DL, 0, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002315 return getTrue(ITy);
2316 break;
2317 case ICmpInst::ICMP_SLT:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002318 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.CxtI,
2319 Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002320 if (LHSKnownNegative)
2321 return getTrue(ITy);
2322 if (LHSKnownNonNegative)
2323 return getFalse(ITy);
2324 break;
2325 case ICmpInst::ICMP_SLE:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002326 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.CxtI,
2327 Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002328 if (LHSKnownNegative)
2329 return getTrue(ITy);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002330 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002331 return getFalse(ITy);
2332 break;
2333 case ICmpInst::ICMP_SGE:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002334 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.CxtI,
2335 Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002336 if (LHSKnownNegative)
2337 return getFalse(ITy);
2338 if (LHSKnownNonNegative)
2339 return getTrue(ITy);
2340 break;
2341 case ICmpInst::ICMP_SGT:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002342 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.CxtI,
2343 Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002344 if (LHSKnownNegative)
2345 return getFalse(ITy);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002346 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002347 return getTrue(ITy);
2348 break;
2349 }
2350
2351 return nullptr;
2352}
2353
Sanjay Patel67bde282016-08-22 23:12:02 +00002354static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2355 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002356 const APInt *C;
2357 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002358 return nullptr;
2359
2360 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002361 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002362 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002363 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002364 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002365 return ConstantInt::getTrue(GetCompareTy(RHS));
2366
Sanjay Patel67bde282016-08-22 23:12:02 +00002367 // Many binary operators with constant RHS have easy to compute constant
2368 // range. Use them to check whether the comparison is a tautology.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002369 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002370 APInt Lower = APInt(Width, 0);
2371 APInt Upper = APInt(Width, 0);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002372 const APInt *C2;
2373 if (match(LHS, m_URem(m_Value(), m_APInt(C2)))) {
2374 // 'urem x, C2' produces [0, C2).
2375 Upper = *C2;
2376 } else if (match(LHS, m_SRem(m_Value(), m_APInt(C2)))) {
2377 // 'srem x, C2' produces (-|C2|, |C2|).
2378 Upper = C2->abs();
Sanjay Patel67bde282016-08-22 23:12:02 +00002379 Lower = (-Upper) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002380 } else if (match(LHS, m_UDiv(m_APInt(C2), m_Value()))) {
2381 // 'udiv C2, x' produces [0, C2].
2382 Upper = *C2 + 1;
2383 } else if (match(LHS, m_UDiv(m_Value(), m_APInt(C2)))) {
2384 // 'udiv x, C2' produces [0, UINT_MAX / C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002385 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002386 if (*C2 != 0)
2387 Upper = NegOne.udiv(*C2) + 1;
2388 } else if (match(LHS, m_SDiv(m_APInt(C2), m_Value()))) {
2389 if (C2->isMinSignedValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002390 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002391 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002392 Upper = Lower.lshr(1) + 1;
2393 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002394 // 'sdiv C2, x' produces [-|C2|, |C2|].
2395 Upper = C2->abs() + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002396 Lower = (-Upper) + 1;
2397 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002398 } else if (match(LHS, m_SDiv(m_Value(), m_APInt(C2)))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002399 APInt IntMin = APInt::getSignedMinValue(Width);
2400 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002401 if (C2->isAllOnesValue()) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002402 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002403 // where C2 != -1 and C2 != 0 and C2 != 1
Sanjay Patel67bde282016-08-22 23:12:02 +00002404 Lower = IntMin + 1;
2405 Upper = IntMax + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002406 } else if (C2->countLeadingZeros() < Width - 1) {
2407 // 'sdiv x, C2' produces [INT_MIN / C2, INT_MAX / C2]
2408 // where C2 != -1 and C2 != 0 and C2 != 1
2409 Lower = IntMin.sdiv(*C2);
2410 Upper = IntMax.sdiv(*C2);
Sanjay Patel67bde282016-08-22 23:12:02 +00002411 if (Lower.sgt(Upper))
2412 std::swap(Lower, Upper);
2413 Upper = Upper + 1;
2414 assert(Upper != Lower && "Upper part of range has wrapped!");
2415 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002416 } else if (match(LHS, m_NUWShl(m_APInt(C2), m_Value()))) {
2417 // 'shl nuw C2, x' produces [C2, C2 << CLZ(C2)]
2418 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002419 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002420 } else if (match(LHS, m_NSWShl(m_APInt(C2), m_Value()))) {
2421 if (C2->isNegative()) {
2422 // 'shl nsw C2, x' produces [C2 << CLO(C2)-1, C2]
2423 unsigned ShiftAmount = C2->countLeadingOnes() - 1;
2424 Lower = C2->shl(ShiftAmount);
2425 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002426 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002427 // 'shl nsw C2, x' produces [C2, C2 << CLZ(C2)-1]
2428 unsigned ShiftAmount = C2->countLeadingZeros() - 1;
2429 Lower = *C2;
2430 Upper = C2->shl(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002431 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002432 } else if (match(LHS, m_LShr(m_Value(), m_APInt(C2)))) {
2433 // 'lshr x, C2' produces [0, UINT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002434 APInt NegOne = APInt::getAllOnesValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002435 if (C2->ult(Width))
2436 Upper = NegOne.lshr(*C2) + 1;
2437 } else if (match(LHS, m_LShr(m_APInt(C2), m_Value()))) {
2438 // 'lshr C2, x' produces [C2 >> (Width-1), C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002439 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002440 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2441 ShiftAmount = C2->countTrailingZeros();
2442 Lower = C2->lshr(ShiftAmount);
2443 Upper = *C2 + 1;
2444 } else if (match(LHS, m_AShr(m_Value(), m_APInt(C2)))) {
2445 // 'ashr x, C2' produces [INT_MIN >> C2, INT_MAX >> C2].
Sanjay Patel67bde282016-08-22 23:12:02 +00002446 APInt IntMin = APInt::getSignedMinValue(Width);
2447 APInt IntMax = APInt::getSignedMaxValue(Width);
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002448 if (C2->ult(Width)) {
2449 Lower = IntMin.ashr(*C2);
2450 Upper = IntMax.ashr(*C2) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002451 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002452 } else if (match(LHS, m_AShr(m_APInt(C2), m_Value()))) {
Sanjay Patel67bde282016-08-22 23:12:02 +00002453 unsigned ShiftAmount = Width - 1;
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002454 if (*C2 != 0 && cast<BinaryOperator>(LHS)->isExact())
2455 ShiftAmount = C2->countTrailingZeros();
2456 if (C2->isNegative()) {
2457 // 'ashr C2, x' produces [C2, C2 >> (Width-1)]
2458 Lower = *C2;
2459 Upper = C2->ashr(ShiftAmount) + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002460 } else {
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002461 // 'ashr C2, x' produces [C2 >> (Width-1), C2]
2462 Lower = C2->ashr(ShiftAmount);
2463 Upper = *C2 + 1;
Sanjay Patel67bde282016-08-22 23:12:02 +00002464 }
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002465 } else if (match(LHS, m_Or(m_Value(), m_APInt(C2)))) {
2466 // 'or x, C2' produces [C2, UINT_MAX].
2467 Lower = *C2;
2468 } else if (match(LHS, m_And(m_Value(), m_APInt(C2)))) {
2469 // 'and x, C2' produces [0, C2].
2470 Upper = *C2 + 1;
2471 } else if (match(LHS, m_NUWAdd(m_Value(), m_APInt(C2)))) {
2472 // 'add nuw x, C2' produces [C2, UINT_MAX].
2473 Lower = *C2;
Sanjay Patel67bde282016-08-22 23:12:02 +00002474 }
2475
2476 ConstantRange LHS_CR =
2477 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2478
2479 if (auto *I = dyn_cast<Instruction>(LHS))
2480 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2481 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2482
2483 if (!LHS_CR.isFullSet()) {
2484 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002485 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002486 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002487 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002488 }
2489
2490 return nullptr;
2491}
2492
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002493static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2494 Value *RHS, const Query &Q,
2495 unsigned MaxRecurse) {
2496 Type *ITy = GetCompareTy(LHS); // The return type.
2497
2498 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2499 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2500 if (MaxRecurse && (LBO || RBO)) {
2501 // Analyze the case when either LHS or RHS is an add instruction.
2502 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2503 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2504 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2505 if (LBO && LBO->getOpcode() == Instruction::Add) {
2506 A = LBO->getOperand(0);
2507 B = LBO->getOperand(1);
2508 NoLHSWrapProblem =
2509 ICmpInst::isEquality(Pred) ||
2510 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2511 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2512 }
2513 if (RBO && RBO->getOpcode() == Instruction::Add) {
2514 C = RBO->getOperand(0);
2515 D = RBO->getOperand(1);
2516 NoRHSWrapProblem =
2517 ICmpInst::isEquality(Pred) ||
2518 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2519 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2520 }
2521
2522 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2523 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2524 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2525 Constant::getNullValue(RHS->getType()), Q,
2526 MaxRecurse - 1))
2527 return V;
2528
2529 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2530 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2531 if (Value *V =
2532 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2533 C == LHS ? D : C, Q, MaxRecurse - 1))
2534 return V;
2535
2536 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2537 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2538 NoRHSWrapProblem) {
2539 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2540 Value *Y, *Z;
2541 if (A == C) {
2542 // C + B == C + D -> B == D
2543 Y = B;
2544 Z = D;
2545 } else if (A == D) {
2546 // D + B == C + D -> B == C
2547 Y = B;
2548 Z = C;
2549 } else if (B == C) {
2550 // A + C == C + D -> A == D
2551 Y = A;
2552 Z = D;
2553 } else {
2554 assert(B == D);
2555 // A + D == C + D -> A == C
2556 Y = A;
2557 Z = C;
2558 }
2559 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2560 return V;
2561 }
2562 }
2563
2564 {
2565 Value *Y = nullptr;
2566 // icmp pred (or X, Y), X
2567 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2568 if (Pred == ICmpInst::ICMP_ULT)
2569 return getFalse(ITy);
2570 if (Pred == ICmpInst::ICMP_UGE)
2571 return getTrue(ITy);
2572
2573 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2574 bool RHSKnownNonNegative, RHSKnownNegative;
2575 bool YKnownNonNegative, YKnownNegative;
2576 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002577 Q.CxtI, Q.DT);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002578 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.CxtI,
2579 Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002580 if (RHSKnownNonNegative && YKnownNegative)
2581 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2582 if (RHSKnownNegative || YKnownNonNegative)
2583 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2584 }
2585 }
2586 // icmp pred X, (or X, Y)
2587 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2588 if (Pred == ICmpInst::ICMP_ULE)
2589 return getTrue(ITy);
2590 if (Pred == ICmpInst::ICMP_UGT)
2591 return getFalse(ITy);
2592
2593 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2594 bool LHSKnownNonNegative, LHSKnownNegative;
2595 bool YKnownNonNegative, YKnownNegative;
2596 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002597 Q.CxtI, Q.DT);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002598 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.CxtI,
2599 Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002600 if (LHSKnownNonNegative && YKnownNegative)
2601 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2602 if (LHSKnownNegative || YKnownNonNegative)
2603 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2604 }
2605 }
2606 }
2607
2608 // icmp pred (and X, Y), X
2609 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2610 m_And(m_Specific(RHS), m_Value())))) {
2611 if (Pred == ICmpInst::ICMP_UGT)
2612 return getFalse(ITy);
2613 if (Pred == ICmpInst::ICMP_ULE)
2614 return getTrue(ITy);
2615 }
2616 // icmp pred X, (and X, Y)
2617 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2618 m_And(m_Specific(LHS), m_Value())))) {
2619 if (Pred == ICmpInst::ICMP_UGE)
2620 return getTrue(ITy);
2621 if (Pred == ICmpInst::ICMP_ULT)
2622 return getFalse(ITy);
2623 }
2624
2625 // 0 - (zext X) pred C
2626 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2627 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2628 if (RHSC->getValue().isStrictlyPositive()) {
2629 if (Pred == ICmpInst::ICMP_SLT)
2630 return ConstantInt::getTrue(RHSC->getContext());
2631 if (Pred == ICmpInst::ICMP_SGE)
2632 return ConstantInt::getFalse(RHSC->getContext());
2633 if (Pred == ICmpInst::ICMP_EQ)
2634 return ConstantInt::getFalse(RHSC->getContext());
2635 if (Pred == ICmpInst::ICMP_NE)
2636 return ConstantInt::getTrue(RHSC->getContext());
2637 }
2638 if (RHSC->getValue().isNonNegative()) {
2639 if (Pred == ICmpInst::ICMP_SLE)
2640 return ConstantInt::getTrue(RHSC->getContext());
2641 if (Pred == ICmpInst::ICMP_SGT)
2642 return ConstantInt::getFalse(RHSC->getContext());
2643 }
2644 }
2645 }
2646
2647 // icmp pred (urem X, Y), Y
2648 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2649 bool KnownNonNegative, KnownNegative;
2650 switch (Pred) {
2651 default:
2652 break;
2653 case ICmpInst::ICMP_SGT:
2654 case ICmpInst::ICMP_SGE:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002655 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.CxtI,
2656 Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002657 if (!KnownNonNegative)
2658 break;
2659 LLVM_FALLTHROUGH;
2660 case ICmpInst::ICMP_EQ:
2661 case ICmpInst::ICMP_UGT:
2662 case ICmpInst::ICMP_UGE:
2663 return getFalse(ITy);
2664 case ICmpInst::ICMP_SLT:
2665 case ICmpInst::ICMP_SLE:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002666 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.CxtI,
2667 Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002668 if (!KnownNonNegative)
2669 break;
2670 LLVM_FALLTHROUGH;
2671 case ICmpInst::ICMP_NE:
2672 case ICmpInst::ICMP_ULT:
2673 case ICmpInst::ICMP_ULE:
2674 return getTrue(ITy);
2675 }
2676 }
2677
2678 // icmp pred X, (urem Y, X)
2679 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2680 bool KnownNonNegative, KnownNegative;
2681 switch (Pred) {
2682 default:
2683 break;
2684 case ICmpInst::ICMP_SGT:
2685 case ICmpInst::ICMP_SGE:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002686 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.CxtI,
2687 Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002688 if (!KnownNonNegative)
2689 break;
2690 LLVM_FALLTHROUGH;
2691 case ICmpInst::ICMP_NE:
2692 case ICmpInst::ICMP_UGT:
2693 case ICmpInst::ICMP_UGE:
2694 return getTrue(ITy);
2695 case ICmpInst::ICMP_SLT:
2696 case ICmpInst::ICMP_SLE:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00002697 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.CxtI,
2698 Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002699 if (!KnownNonNegative)
2700 break;
2701 LLVM_FALLTHROUGH;
2702 case ICmpInst::ICMP_EQ:
2703 case ICmpInst::ICMP_ULT:
2704 case ICmpInst::ICMP_ULE:
2705 return getFalse(ITy);
2706 }
2707 }
2708
2709 // x >> y <=u x
2710 // x udiv y <=u x.
2711 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2712 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2713 // icmp pred (X op Y), X
2714 if (Pred == ICmpInst::ICMP_UGT)
2715 return getFalse(ITy);
2716 if (Pred == ICmpInst::ICMP_ULE)
2717 return getTrue(ITy);
2718 }
2719
2720 // x >=u x >> y
2721 // x >=u x udiv y.
2722 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2723 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2724 // icmp pred X, (X op Y)
2725 if (Pred == ICmpInst::ICMP_ULT)
2726 return getFalse(ITy);
2727 if (Pred == ICmpInst::ICMP_UGE)
2728 return getTrue(ITy);
2729 }
2730
2731 // handle:
2732 // CI2 << X == CI
2733 // CI2 << X != CI
2734 //
2735 // where CI2 is a power of 2 and CI isn't
2736 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2737 const APInt *CI2Val, *CIVal = &CI->getValue();
2738 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2739 CI2Val->isPowerOf2()) {
2740 if (!CIVal->isPowerOf2()) {
2741 // CI2 << X can equal zero in some circumstances,
2742 // this simplification is unsafe if CI is zero.
2743 //
2744 // We know it is safe if:
2745 // - The shift is nsw, we can't shift out the one bit.
2746 // - The shift is nuw, we can't shift out the one bit.
2747 // - CI2 is one
2748 // - CI isn't zero
2749 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2750 *CI2Val == 1 || !CI->isZero()) {
2751 if (Pred == ICmpInst::ICMP_EQ)
2752 return ConstantInt::getFalse(RHS->getContext());
2753 if (Pred == ICmpInst::ICMP_NE)
2754 return ConstantInt::getTrue(RHS->getContext());
2755 }
2756 }
2757 if (CIVal->isSignBit() && *CI2Val == 1) {
2758 if (Pred == ICmpInst::ICMP_UGT)
2759 return ConstantInt::getFalse(RHS->getContext());
2760 if (Pred == ICmpInst::ICMP_ULE)
2761 return ConstantInt::getTrue(RHS->getContext());
2762 }
2763 }
2764 }
2765
2766 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2767 LBO->getOperand(1) == RBO->getOperand(1)) {
2768 switch (LBO->getOpcode()) {
2769 default:
2770 break;
2771 case Instruction::UDiv:
2772 case Instruction::LShr:
2773 if (ICmpInst::isSigned(Pred))
2774 break;
2775 LLVM_FALLTHROUGH;
2776 case Instruction::SDiv:
2777 case Instruction::AShr:
2778 if (!LBO->isExact() || !RBO->isExact())
2779 break;
2780 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2781 RBO->getOperand(0), Q, MaxRecurse - 1))
2782 return V;
2783 break;
2784 case Instruction::Shl: {
2785 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2786 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2787 if (!NUW && !NSW)
2788 break;
2789 if (!NSW && ICmpInst::isSigned(Pred))
2790 break;
2791 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2792 RBO->getOperand(0), Q, MaxRecurse - 1))
2793 return V;
2794 break;
2795 }
2796 }
2797 }
2798 return nullptr;
2799}
2800
Sanjay Patel35289c62016-12-10 17:40:47 +00002801/// Simplify integer comparisons where at least one operand of the compare
2802/// matches an integer min/max idiom.
2803static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2804 Value *RHS, const Query &Q,
2805 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002806 Type *ITy = GetCompareTy(LHS); // The return type.
2807 Value *A, *B;
2808 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2809 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2810
2811 // Signed variants on "max(a,b)>=a -> true".
2812 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2813 if (A != RHS)
2814 std::swap(A, B); // smax(A, B) pred A.
2815 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2816 // We analyze this as smax(A, B) pred A.
2817 P = Pred;
2818 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2819 (A == LHS || B == LHS)) {
2820 if (A != LHS)
2821 std::swap(A, B); // A pred smax(A, B).
2822 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2823 // We analyze this as smax(A, B) swapped-pred A.
2824 P = CmpInst::getSwappedPredicate(Pred);
2825 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2826 (A == RHS || B == RHS)) {
2827 if (A != RHS)
2828 std::swap(A, B); // smin(A, B) pred A.
2829 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2830 // We analyze this as smax(-A, -B) swapped-pred -A.
2831 // Note that we do not need to actually form -A or -B thanks to EqP.
2832 P = CmpInst::getSwappedPredicate(Pred);
2833 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2834 (A == LHS || B == LHS)) {
2835 if (A != LHS)
2836 std::swap(A, B); // A pred smin(A, B).
2837 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2838 // We analyze this as smax(-A, -B) pred -A.
2839 // Note that we do not need to actually form -A or -B thanks to EqP.
2840 P = Pred;
2841 }
2842 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2843 // Cases correspond to "max(A, B) p A".
2844 switch (P) {
2845 default:
2846 break;
2847 case CmpInst::ICMP_EQ:
2848 case CmpInst::ICMP_SLE:
2849 // Equivalent to "A EqP B". This may be the same as the condition tested
2850 // in the max/min; if so, we can just return that.
2851 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2852 return V;
2853 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2854 return V;
2855 // Otherwise, see if "A EqP B" simplifies.
2856 if (MaxRecurse)
2857 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2858 return V;
2859 break;
2860 case CmpInst::ICMP_NE:
2861 case CmpInst::ICMP_SGT: {
2862 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2863 // Equivalent to "A InvEqP B". This may be the same as the condition
2864 // tested in the max/min; if so, we can just return that.
2865 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2866 return V;
2867 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2868 return V;
2869 // Otherwise, see if "A InvEqP B" simplifies.
2870 if (MaxRecurse)
2871 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2872 return V;
2873 break;
2874 }
2875 case CmpInst::ICMP_SGE:
2876 // Always true.
2877 return getTrue(ITy);
2878 case CmpInst::ICMP_SLT:
2879 // Always false.
2880 return getFalse(ITy);
2881 }
2882 }
2883
2884 // Unsigned variants on "max(a,b)>=a -> true".
2885 P = CmpInst::BAD_ICMP_PREDICATE;
2886 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2887 if (A != RHS)
2888 std::swap(A, B); // umax(A, B) pred A.
2889 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2890 // We analyze this as umax(A, B) pred A.
2891 P = Pred;
2892 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2893 (A == LHS || B == LHS)) {
2894 if (A != LHS)
2895 std::swap(A, B); // A pred umax(A, B).
2896 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2897 // We analyze this as umax(A, B) swapped-pred A.
2898 P = CmpInst::getSwappedPredicate(Pred);
2899 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2900 (A == RHS || B == RHS)) {
2901 if (A != RHS)
2902 std::swap(A, B); // umin(A, B) pred A.
2903 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2904 // We analyze this as umax(-A, -B) swapped-pred -A.
2905 // Note that we do not need to actually form -A or -B thanks to EqP.
2906 P = CmpInst::getSwappedPredicate(Pred);
2907 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2908 (A == LHS || B == LHS)) {
2909 if (A != LHS)
2910 std::swap(A, B); // A pred umin(A, B).
2911 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2912 // We analyze this as umax(-A, -B) pred -A.
2913 // Note that we do not need to actually form -A or -B thanks to EqP.
2914 P = Pred;
2915 }
2916 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2917 // Cases correspond to "max(A, B) p A".
2918 switch (P) {
2919 default:
2920 break;
2921 case CmpInst::ICMP_EQ:
2922 case CmpInst::ICMP_ULE:
2923 // Equivalent to "A EqP B". This may be the same as the condition tested
2924 // in the max/min; if so, we can just return that.
2925 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2926 return V;
2927 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2928 return V;
2929 // Otherwise, see if "A EqP B" simplifies.
2930 if (MaxRecurse)
2931 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2932 return V;
2933 break;
2934 case CmpInst::ICMP_NE:
2935 case CmpInst::ICMP_UGT: {
2936 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2937 // Equivalent to "A InvEqP B". This may be the same as the condition
2938 // tested in the max/min; if so, we can just return that.
2939 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2940 return V;
2941 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2942 return V;
2943 // Otherwise, see if "A InvEqP B" simplifies.
2944 if (MaxRecurse)
2945 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2946 return V;
2947 break;
2948 }
2949 case CmpInst::ICMP_UGE:
2950 // Always true.
2951 return getTrue(ITy);
2952 case CmpInst::ICMP_ULT:
2953 // Always false.
2954 return getFalse(ITy);
2955 }
2956 }
2957
2958 // Variants on "max(x,y) >= min(x,z)".
2959 Value *C, *D;
2960 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2961 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2962 (A == C || A == D || B == C || B == D)) {
2963 // max(x, ?) pred min(x, ?).
2964 if (Pred == CmpInst::ICMP_SGE)
2965 // Always true.
2966 return getTrue(ITy);
2967 if (Pred == CmpInst::ICMP_SLT)
2968 // Always false.
2969 return getFalse(ITy);
2970 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2971 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2972 (A == C || A == D || B == C || B == D)) {
2973 // min(x, ?) pred max(x, ?).
2974 if (Pred == CmpInst::ICMP_SLE)
2975 // Always true.
2976 return getTrue(ITy);
2977 if (Pred == CmpInst::ICMP_SGT)
2978 // Always false.
2979 return getFalse(ITy);
2980 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2981 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2982 (A == C || A == D || B == C || B == D)) {
2983 // max(x, ?) pred min(x, ?).
2984 if (Pred == CmpInst::ICMP_UGE)
2985 // Always true.
2986 return getTrue(ITy);
2987 if (Pred == CmpInst::ICMP_ULT)
2988 // Always false.
2989 return getFalse(ITy);
2990 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2991 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2992 (A == C || A == D || B == C || B == D)) {
2993 // min(x, ?) pred max(x, ?).
2994 if (Pred == CmpInst::ICMP_ULE)
2995 // Always true.
2996 return getTrue(ITy);
2997 if (Pred == CmpInst::ICMP_UGT)
2998 // Always false.
2999 return getFalse(ITy);
3000 }
3001
3002 return nullptr;
3003}
3004
Sanjay Patel472cc782016-01-11 22:14:42 +00003005/// Given operands for an ICmpInst, see if we can fold the result.
3006/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003007static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003008 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003009 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003010 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003011
Chris Lattnera71e9d62009-11-10 00:55:12 +00003012 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003013 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003014 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003015
3016 // If we have a constant, make sure it is on the RHS.
3017 std::swap(LHS, RHS);
3018 Pred = CmpInst::getSwappedPredicate(Pred);
3019 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003020
Chris Lattner229907c2011-07-18 04:54:35 +00003021 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003022
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003023 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003024 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3025 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003026 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003027 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003028
Sanjay Pateldc65a272016-12-03 17:30:22 +00003029 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3030 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003031
Sanjay Pateldc65a272016-12-03 17:30:22 +00003032 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3033 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003034
Sanjay Patel67bde282016-08-22 23:12:02 +00003035 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3036 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003037
Chen Li7452d952015-09-26 03:26:47 +00003038 // If both operands have range metadata, use the metadata
3039 // to simplify the comparison.
3040 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3041 auto RHS_Instr = dyn_cast<Instruction>(RHS);
3042 auto LHS_Instr = dyn_cast<Instruction>(LHS);
3043
3044 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3045 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003046 auto RHS_CR = getConstantRangeFromMetadata(
3047 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3048 auto LHS_CR = getConstantRangeFromMetadata(
3049 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003050
3051 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3052 if (Satisfied_CR.contains(LHS_CR))
3053 return ConstantInt::getTrue(RHS->getContext());
3054
3055 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3056 CmpInst::getInversePredicate(Pred), RHS_CR);
3057 if (InversedSatisfied_CR.contains(LHS_CR))
3058 return ConstantInt::getFalse(RHS->getContext());
3059 }
3060 }
3061
Duncan Sands8fb2c382011-01-20 13:21:55 +00003062 // Compare of cast, for example (zext X) != 0 -> X != 0
3063 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3064 Instruction *LI = cast<CastInst>(LHS);
3065 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003066 Type *SrcTy = SrcOp->getType();
3067 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003068
3069 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3070 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003071 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3072 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003073 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3074 // Transfer the cast to the constant.
3075 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3076 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003077 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003078 return V;
3079 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3080 if (RI->getOperand(0)->getType() == SrcTy)
3081 // Compare without the cast.
3082 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003083 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003084 return V;
3085 }
3086 }
3087
3088 if (isa<ZExtInst>(LHS)) {
3089 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3090 // same type.
3091 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3092 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3093 // Compare X and Y. Note that signed predicates become unsigned.
3094 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003095 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003096 MaxRecurse-1))
3097 return V;
3098 }
3099 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3100 // too. If not, then try to deduce the result of the comparison.
3101 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3102 // Compute the constant that would happen if we truncated to SrcTy then
3103 // reextended to DstTy.
3104 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3105 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3106
3107 // If the re-extended constant didn't change then this is effectively
3108 // also a case of comparing two zero-extended values.
3109 if (RExt == CI && MaxRecurse)
3110 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003111 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003112 return V;
3113
3114 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3115 // there. Use this to work out the result of the comparison.
3116 if (RExt != CI) {
3117 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003118 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003119 // LHS <u RHS.
3120 case ICmpInst::ICMP_EQ:
3121 case ICmpInst::ICMP_UGT:
3122 case ICmpInst::ICMP_UGE:
3123 return ConstantInt::getFalse(CI->getContext());
3124
3125 case ICmpInst::ICMP_NE:
3126 case ICmpInst::ICMP_ULT:
3127 case ICmpInst::ICMP_ULE:
3128 return ConstantInt::getTrue(CI->getContext());
3129
3130 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3131 // is non-negative then LHS <s RHS.
3132 case ICmpInst::ICMP_SGT:
3133 case ICmpInst::ICMP_SGE:
3134 return CI->getValue().isNegative() ?
3135 ConstantInt::getTrue(CI->getContext()) :
3136 ConstantInt::getFalse(CI->getContext());
3137
3138 case ICmpInst::ICMP_SLT:
3139 case ICmpInst::ICMP_SLE:
3140 return CI->getValue().isNegative() ?
3141 ConstantInt::getFalse(CI->getContext()) :
3142 ConstantInt::getTrue(CI->getContext());
3143 }
3144 }
3145 }
3146 }
3147
3148 if (isa<SExtInst>(LHS)) {
3149 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3150 // same type.
3151 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3152 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3153 // Compare X and Y. Note that the predicate does not change.
3154 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003155 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003156 return V;
3157 }
3158 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3159 // too. If not, then try to deduce the result of the comparison.
3160 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3161 // Compute the constant that would happen if we truncated to SrcTy then
3162 // reextended to DstTy.
3163 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3164 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3165
3166 // If the re-extended constant didn't change then this is effectively
3167 // also a case of comparing two sign-extended values.
3168 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003169 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003170 return V;
3171
3172 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3173 // bits there. Use this to work out the result of the comparison.
3174 if (RExt != CI) {
3175 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003176 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003177 case ICmpInst::ICMP_EQ:
3178 return ConstantInt::getFalse(CI->getContext());
3179 case ICmpInst::ICMP_NE:
3180 return ConstantInt::getTrue(CI->getContext());
3181
3182 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3183 // LHS >s RHS.
3184 case ICmpInst::ICMP_SGT:
3185 case ICmpInst::ICMP_SGE:
3186 return CI->getValue().isNegative() ?
3187 ConstantInt::getTrue(CI->getContext()) :
3188 ConstantInt::getFalse(CI->getContext());
3189 case ICmpInst::ICMP_SLT:
3190 case ICmpInst::ICMP_SLE:
3191 return CI->getValue().isNegative() ?
3192 ConstantInt::getFalse(CI->getContext()) :
3193 ConstantInt::getTrue(CI->getContext());
3194
3195 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3196 // LHS >u RHS.
3197 case ICmpInst::ICMP_UGT:
3198 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003199 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003200 if (MaxRecurse)
3201 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3202 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003203 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003204 return V;
3205 break;
3206 case ICmpInst::ICMP_ULT:
3207 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003208 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003209 if (MaxRecurse)
3210 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3211 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003212 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003213 return V;
3214 break;
3215 }
3216 }
3217 }
3218 }
3219 }
3220
James Molloy1d88d6f2015-10-22 13:18:42 +00003221 // icmp eq|ne X, Y -> false|true if X != Y
3222 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003223 isKnownNonEqual(LHS, RHS, Q.DL, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003224 LLVMContext &Ctx = LHS->getType()->getContext();
3225 return Pred == ICmpInst::ICMP_NE ?
3226 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3227 }
Junmo Park53470fc2016-04-05 21:14:31 +00003228
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003229 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3230 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003231
Sanjay Patel35289c62016-12-10 17:40:47 +00003232 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003233 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003234
Chandler Carruth8059c842012-03-25 21:28:14 +00003235 // Simplify comparisons of related pointers using a powerful, recursive
3236 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003237 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003238 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003239 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003240 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3241 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3242 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3243 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3244 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3245 Q.DL.getTypeSizeInBits(CRHS->getType()))
3246 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3247 CLHS->getPointerOperand(),
3248 CRHS->getPointerOperand()))
3249 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003250
Nick Lewycky3db143e2012-02-26 02:09:49 +00003251 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3252 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3253 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3254 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3255 (ICmpInst::isEquality(Pred) ||
3256 (GLHS->isInBounds() && GRHS->isInBounds() &&
3257 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3258 // The bases are equal and the indices are constant. Build a constant
3259 // expression GEP with the same indices and a null base pointer to see
3260 // what constant folding can make out of it.
3261 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3262 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003263 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3264 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003265
3266 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003267 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3268 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003269 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3270 }
3271 }
3272 }
3273
David Majnemer5854e9f2014-11-16 02:20:08 +00003274 // If a bit is known to be zero for A and known to be one for B,
3275 // then A and B cannot be equal.
3276 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003277 const APInt *RHSVal;
3278 if (match(RHS, m_APInt(RHSVal))) {
3279 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003280 APInt LHSKnownZero(BitWidth, 0);
3281 APInt LHSKnownOne(BitWidth, 0);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003282 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0,
David Majnemer5854e9f2014-11-16 02:20:08 +00003283 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003284 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3285 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3286 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003287 }
3288 }
3289
Duncan Sandsf532d312010-11-07 16:12:23 +00003290 // If the comparison is with the result of a select instruction, check whether
3291 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003292 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003293 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003294 return V;
3295
3296 // If the comparison is with the result of a phi instruction, check whether
3297 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003298 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003299 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003300 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003301
Craig Topper9f008862014-04-15 04:59:12 +00003302 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003303}
3304
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003305Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003306 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003307 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003308 const DominatorTree *DT,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003309 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003310 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003311 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003312}
3313
Sanjay Patel472cc782016-01-11 22:14:42 +00003314/// Given operands for an FCmpInst, see if we can fold the result.
3315/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003316static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003317 FastMathFlags FMF, const Query &Q,
3318 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003319 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3320 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3321
Chris Lattnera71e9d62009-11-10 00:55:12 +00003322 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003323 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003324 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003325
Chris Lattnera71e9d62009-11-10 00:55:12 +00003326 // If we have a constant, make sure it is on the RHS.
3327 std::swap(LHS, RHS);
3328 Pred = CmpInst::getSwappedPredicate(Pred);
3329 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003330
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003331 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003332 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003333 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003334 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003335 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003336 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003337
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003338 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3339 if (FMF.noNaNs()) {
3340 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003341 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003342 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003343 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003344 }
3345
Mehdi Aminieb242a52015-03-09 03:20:25 +00003346 // fcmp pred x, undef and fcmp pred undef, x
3347 // fold to true if unordered, false if ordered
3348 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3349 // Choosing NaN for the undef will always make unordered comparison succeed
3350 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003351 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003352 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003353
3354 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003355 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003356 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003357 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003358 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003359 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003360 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003361
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003362 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003363 const ConstantFP *CFP = nullptr;
3364 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3365 if (RHS->getType()->isVectorTy())
3366 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3367 else
3368 CFP = dyn_cast<ConstantFP>(RHSC);
3369 }
3370 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003371 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003372 if (CFP->getValueAPF().isNaN()) {
3373 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003374 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003375 assert(FCmpInst::isUnordered(Pred) &&
3376 "Comparison must be either ordered or unordered!");
3377 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003378 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003379 }
3380 // Check whether the constant is an infinity.
3381 if (CFP->getValueAPF().isInfinity()) {
3382 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003383 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003384 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003385 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003386 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003387 case FCmpInst::FCMP_UGE:
3388 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003389 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003390 default:
3391 break;
3392 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003393 } else {
3394 switch (Pred) {
3395 case FCmpInst::FCMP_OGT:
3396 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003397 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003398 case FCmpInst::FCMP_ULE:
3399 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003400 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003401 default:
3402 break;
3403 }
3404 }
3405 }
3406 if (CFP->getValueAPF().isZero()) {
3407 switch (Pred) {
3408 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003409 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003410 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003411 break;
3412 case FCmpInst::FCMP_OLT:
3413 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003414 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003415 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003416 break;
3417 default:
3418 break;
3419 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003420 }
3421 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003422
Duncan Sandsa620bd12010-11-07 16:46:25 +00003423 // If the comparison is with the result of a select instruction, check whether
3424 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003425 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003426 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003427 return V;
3428
3429 // If the comparison is with the result of a phi instruction, check whether
3430 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003431 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003432 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003433 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003434
Craig Topper9f008862014-04-15 04:59:12 +00003435 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003436}
3437
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003438Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003439 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003440 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003441 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00003442 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003443 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003444 Query(DL, TLI, DT, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003445}
3446
Sanjay Patel472cc782016-01-11 22:14:42 +00003447/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003448static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3449 const Query &Q,
3450 unsigned MaxRecurse) {
3451 // Trivial replacement.
3452 if (V == Op)
3453 return RepOp;
3454
3455 auto *I = dyn_cast<Instruction>(V);
3456 if (!I)
3457 return nullptr;
3458
3459 // If this is a binary operator, try to simplify it with the replaced op.
3460 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3461 // Consider:
3462 // %cmp = icmp eq i32 %x, 2147483647
3463 // %add = add nsw i32 %x, 1
3464 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3465 //
3466 // We can't replace %sel with %add unless we strip away the flags.
3467 if (isa<OverflowingBinaryOperator>(B))
3468 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3469 return nullptr;
3470 if (isa<PossiblyExactOperator>(B))
3471 if (B->isExact())
3472 return nullptr;
3473
3474 if (MaxRecurse) {
3475 if (B->getOperand(0) == Op)
3476 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3477 MaxRecurse - 1);
3478 if (B->getOperand(1) == Op)
3479 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3480 MaxRecurse - 1);
3481 }
3482 }
3483
3484 // Same for CmpInsts.
3485 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3486 if (MaxRecurse) {
3487 if (C->getOperand(0) == Op)
3488 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3489 MaxRecurse - 1);
3490 if (C->getOperand(1) == Op)
3491 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3492 MaxRecurse - 1);
3493 }
3494 }
3495
3496 // TODO: We could hand off more cases to instsimplify here.
3497
3498 // If all operands are constant after substituting Op for RepOp then we can
3499 // constant fold the instruction.
3500 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3501 // Build a list of all constant operands.
3502 SmallVector<Constant *, 8> ConstOps;
3503 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3504 if (I->getOperand(i) == Op)
3505 ConstOps.push_back(CRepOp);
3506 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3507 ConstOps.push_back(COp);
3508 else
3509 break;
3510 }
3511
3512 // All operands were constants, fold it.
3513 if (ConstOps.size() == I->getNumOperands()) {
3514 if (CmpInst *C = dyn_cast<CmpInst>(I))
3515 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3516 ConstOps[1], Q.DL, Q.TLI);
3517
3518 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3519 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003520 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003521
Manuel Jacobe9024592016-01-21 06:33:22 +00003522 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003523 }
3524 }
3525
3526 return nullptr;
3527}
3528
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003529/// Try to simplify a select instruction when its condition operand is an
3530/// integer comparison where one operand of the compare is a constant.
3531static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3532 const APInt *Y, bool TrueWhenUnset) {
3533 const APInt *C;
3534
3535 // (X & Y) == 0 ? X & ~Y : X --> X
3536 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3537 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3538 *Y == ~*C)
3539 return TrueWhenUnset ? FalseVal : TrueVal;
3540
3541 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3542 // (X & Y) != 0 ? X : X & ~Y --> X
3543 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3544 *Y == ~*C)
3545 return TrueWhenUnset ? FalseVal : TrueVal;
3546
3547 if (Y->isPowerOf2()) {
3548 // (X & Y) == 0 ? X | Y : X --> X | Y
3549 // (X & Y) != 0 ? X | Y : X --> X
3550 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3551 *Y == *C)
3552 return TrueWhenUnset ? TrueVal : FalseVal;
3553
3554 // (X & Y) == 0 ? X : X | Y --> X
3555 // (X & Y) != 0 ? X : X | Y --> X | Y
3556 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3557 *Y == *C)
3558 return TrueWhenUnset ? TrueVal : FalseVal;
3559 }
3560
3561 return nullptr;
3562}
3563
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003564/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3565/// eq/ne.
3566static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3567 Value *FalseVal,
3568 bool TrueWhenUnset) {
3569 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003570 if (!BitWidth)
3571 return nullptr;
3572
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003573 APInt MinSignedValue;
3574 Value *X;
3575 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3576 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3577 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3578 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3579 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3580 } else {
3581 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3582 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3583 X = CmpLHS;
3584 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3585 }
3586
3587 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3588 TrueWhenUnset))
3589 return V;
3590
3591 return nullptr;
3592}
3593
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003594/// Try to simplify a select instruction when its condition operand is an
3595/// integer comparison.
3596static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3597 Value *FalseVal, const Query &Q,
3598 unsigned MaxRecurse) {
3599 ICmpInst::Predicate Pred;
3600 Value *CmpLHS, *CmpRHS;
3601 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3602 return nullptr;
3603
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003604 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3605 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003606 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3607 Value *X;
3608 const APInt *Y;
3609 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3610 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3611 Pred == ICmpInst::ICMP_EQ))
3612 return V;
3613 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003614 // Comparing signed-less-than 0 checks if the sign bit is set.
3615 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3616 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003617 return V;
3618 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003619 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3620 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3621 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003622 return V;
3623 }
3624
3625 if (CondVal->hasOneUse()) {
3626 const APInt *C;
3627 if (match(CmpRHS, m_APInt(C))) {
3628 // X < MIN ? T : F --> F
3629 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3630 return FalseVal;
3631 // X < MIN ? T : F --> F
3632 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3633 return FalseVal;
3634 // X > MAX ? T : F --> F
3635 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3636 return FalseVal;
3637 // X > MAX ? T : F --> F
3638 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3639 return FalseVal;
3640 }
3641 }
3642
3643 // If we have an equality comparison, then we know the value in one of the
3644 // arms of the select. See if substituting this value into the arm and
3645 // simplifying the result yields the same value as the other arm.
3646 if (Pred == ICmpInst::ICMP_EQ) {
3647 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3648 TrueVal ||
3649 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3650 TrueVal)
3651 return FalseVal;
3652 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3653 FalseVal ||
3654 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3655 FalseVal)
3656 return FalseVal;
3657 } else if (Pred == ICmpInst::ICMP_NE) {
3658 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3659 FalseVal ||
3660 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3661 FalseVal)
3662 return TrueVal;
3663 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3664 TrueVal ||
3665 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3666 TrueVal)
3667 return TrueVal;
3668 }
3669
3670 return nullptr;
3671}
3672
Sanjay Patel472cc782016-01-11 22:14:42 +00003673/// Given operands for a SelectInst, see if we can fold the result.
3674/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003675static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3676 Value *FalseVal, const Query &Q,
3677 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003678 // select true, X, Y -> X
3679 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003680 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3681 if (CB->isAllOnesValue())
3682 return TrueVal;
3683 if (CB->isNullValue())
3684 return FalseVal;
3685 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003686
Chris Lattnerc707fa92010-04-20 05:32:14 +00003687 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003688 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003689 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003690
Chris Lattnerc707fa92010-04-20 05:32:14 +00003691 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3692 if (isa<Constant>(TrueVal))
3693 return TrueVal;
3694 return FalseVal;
3695 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003696 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3697 return FalseVal;
3698 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3699 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003700
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003701 if (Value *V =
3702 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3703 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003704
Craig Topper9f008862014-04-15 04:59:12 +00003705 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003706}
3707
Duncan Sandsb8cee002012-03-13 11:42:19 +00003708Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003709 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003710 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003711 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00003712 const Instruction *CxtI) {
3713 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003714 Query(DL, TLI, DT, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003715}
3716
Sanjay Patel472cc782016-01-11 22:14:42 +00003717/// Given operands for an GetElementPtrInst, see if we can fold the result.
3718/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003719static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3720 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003721 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003722 unsigned AS =
3723 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003724
Chris Lattner8574aba2009-11-27 00:29:05 +00003725 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003726 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003727 return Ops[0];
3728
Nico Weber48c82402014-08-27 20:06:19 +00003729 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003730 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003731 Type *GEPTy = PointerType::get(LastType, AS);
3732 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3733 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3734
3735 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003736 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003737
Jay Foadb992a632011-07-19 15:07:52 +00003738 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003739 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003740 if (match(Ops[1], m_Zero()))
3741 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003742
David Blaikie4a2e73b2015-04-02 18:55:32 +00003743 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003744 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003745 Value *P;
3746 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003747 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003748 // getelementptr P, N -> P if P points to a type of zero size.
3749 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003750 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003751
3752 // The following transforms are only safe if the ptrtoint cast
3753 // doesn't truncate the pointers.
3754 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003755 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003756 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3757 if (match(P, m_Zero()))
3758 return Constant::getNullValue(GEPTy);
3759 Value *Temp;
3760 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003761 if (Temp->getType() == GEPTy)
3762 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003763 return nullptr;
3764 };
3765
3766 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3767 if (TyAllocSize == 1 &&
3768 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3769 if (Value *R = PtrToIntOrZero(P))
3770 return R;
3771
3772 // getelementptr V, (ashr (sub P, V), C) -> Q
3773 // if P points to a type of size 1 << C.
3774 if (match(Ops[1],
3775 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3776 m_ConstantInt(C))) &&
3777 TyAllocSize == 1ULL << C)
3778 if (Value *R = PtrToIntOrZero(P))
3779 return R;
3780
3781 // getelementptr V, (sdiv (sub P, V), C) -> Q
3782 // if P points to a type of size C.
3783 if (match(Ops[1],
3784 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3785 m_SpecificInt(TyAllocSize))))
3786 if (Value *R = PtrToIntOrZero(P))
3787 return R;
3788 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003789 }
3790 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003791
David Majnemerd1501372016-08-07 07:58:12 +00003792 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3793 all_of(Ops.slice(1).drop_back(1),
3794 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3795 unsigned PtrWidth =
3796 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3797 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3798 APInt BasePtrOffset(PtrWidth, 0);
3799 Value *StrippedBasePtr =
3800 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3801 BasePtrOffset);
3802
David Majnemer5c5df622016-08-16 06:13:46 +00003803 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003804 if (match(Ops.back(),
3805 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3806 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3807 return ConstantExpr::getIntToPtr(CI, GEPTy);
3808 }
David Majnemer5c5df622016-08-16 06:13:46 +00003809 // gep (gep V, C), (xor V, -1) -> C-1
3810 if (match(Ops.back(),
3811 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3812 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3813 return ConstantExpr::getIntToPtr(CI, GEPTy);
3814 }
David Majnemerd1501372016-08-07 07:58:12 +00003815 }
3816 }
3817
Chris Lattner8574aba2009-11-27 00:29:05 +00003818 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003819 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003820 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003821 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003822
David Blaikie4a2e73b2015-04-02 18:55:32 +00003823 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3824 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003825}
3826
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003827Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3828 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003829 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003830 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00003831 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003832 return ::SimplifyGEPInst(SrcTy, Ops,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003833 Query(DL, TLI, DT, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003834}
3835
Sanjay Patel472cc782016-01-11 22:14:42 +00003836/// Given operands for an InsertValueInst, see if we can fold the result.
3837/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003838static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3839 ArrayRef<unsigned> Idxs, const Query &Q,
3840 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003841 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3842 if (Constant *CVal = dyn_cast<Constant>(Val))
3843 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3844
3845 // insertvalue x, undef, n -> x
3846 if (match(Val, m_Undef()))
3847 return Agg;
3848
3849 // insertvalue x, (extractvalue y, n), n
3850 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003851 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3852 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003853 // insertvalue undef, (extractvalue y, n), n -> y
3854 if (match(Agg, m_Undef()))
3855 return EV->getAggregateOperand();
3856
3857 // insertvalue y, (extractvalue y, n), n -> y
3858 if (Agg == EV->getAggregateOperand())
3859 return Agg;
3860 }
3861
Craig Topper9f008862014-04-15 04:59:12 +00003862 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003863}
3864
Chandler Carruth66b31302015-01-04 12:03:27 +00003865Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003866 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003867 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Chandler Carruth66b31302015-01-04 12:03:27 +00003868 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003869 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003870 RecursionLimit);
3871}
3872
Sanjay Patel472cc782016-01-11 22:14:42 +00003873/// Given operands for an ExtractValueInst, see if we can fold the result.
3874/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003875static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3876 const Query &, unsigned) {
3877 if (auto *CAgg = dyn_cast<Constant>(Agg))
3878 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3879
3880 // extractvalue x, (insertvalue y, elt, n), n -> elt
3881 unsigned NumIdxs = Idxs.size();
3882 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3883 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3884 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3885 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3886 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3887 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3888 Idxs.slice(0, NumCommonIdxs)) {
3889 if (NumIdxs == NumInsertValueIdxs)
3890 return IVI->getInsertedValueOperand();
3891 break;
3892 }
3893 }
3894
3895 return nullptr;
3896}
3897
3898Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3899 const DataLayout &DL,
3900 const TargetLibraryInfo *TLI,
3901 const DominatorTree *DT,
David Majnemer25a796e2015-07-13 01:15:46 +00003902 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003903 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003904 RecursionLimit);
3905}
3906
Sanjay Patel472cc782016-01-11 22:14:42 +00003907/// Given operands for an ExtractElementInst, see if we can fold the result.
3908/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003909static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3910 unsigned) {
3911 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3912 if (auto *CIdx = dyn_cast<Constant>(Idx))
3913 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3914
3915 // The index is not relevant if our vector is a splat.
3916 if (auto *Splat = CVec->getSplatValue())
3917 return Splat;
3918
3919 if (isa<UndefValue>(Vec))
3920 return UndefValue::get(Vec->getType()->getVectorElementType());
3921 }
3922
3923 // If extracting a specified index from the vector, see if we can recursively
3924 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003925 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3926 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003927 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003928
3929 return nullptr;
3930}
3931
3932Value *llvm::SimplifyExtractElementInst(
3933 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00003934 const DominatorTree *DT, const Instruction *CxtI) {
3935 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00003936 RecursionLimit);
3937}
3938
Sanjay Patel472cc782016-01-11 22:14:42 +00003939/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003940static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003941 // If all of the PHI's incoming values are the same then replace the PHI node
3942 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003943 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003944 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003945 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003946 // If the incoming value is the phi node itself, it can safely be skipped.
3947 if (Incoming == PN) continue;
3948 if (isa<UndefValue>(Incoming)) {
3949 // Remember that we saw an undef value, but otherwise ignore them.
3950 HasUndefInput = true;
3951 continue;
3952 }
3953 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003954 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003955 CommonValue = Incoming;
3956 }
3957
3958 // If CommonValue is null then all of the incoming values were either undef or
3959 // equal to the phi node itself.
3960 if (!CommonValue)
3961 return UndefValue::get(PN->getType());
3962
3963 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3964 // instruction, we cannot return X as the result of the PHI node unless it
3965 // dominates the PHI block.
3966 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003967 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003968
3969 return CommonValue;
3970}
3971
David Majnemer6774d612016-07-26 17:58:05 +00003972static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
3973 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00003974 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00003975 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003976
David Majnemer6774d612016-07-26 17:58:05 +00003977 if (auto *CI = dyn_cast<CastInst>(Op)) {
3978 auto *Src = CI->getOperand(0);
3979 Type *SrcTy = Src->getType();
3980 Type *MidTy = CI->getType();
3981 Type *DstTy = Ty;
3982 if (Src->getType() == Ty) {
3983 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
3984 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
3985 Type *SrcIntPtrTy =
3986 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
3987 Type *MidIntPtrTy =
3988 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
3989 Type *DstIntPtrTy =
3990 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
3991 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
3992 SrcIntPtrTy, MidIntPtrTy,
3993 DstIntPtrTy) == Instruction::BitCast)
3994 return Src;
3995 }
3996 }
David Majnemera90a6212016-07-26 05:52:29 +00003997
3998 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00003999 if (CastOpc == Instruction::BitCast)
4000 if (Op->getType() == Ty)
4001 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004002
4003 return nullptr;
4004}
4005
David Majnemer6774d612016-07-26 17:58:05 +00004006Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4007 const DataLayout &DL,
4008 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004009 const DominatorTree *DT,
David Majnemer6774d612016-07-26 17:58:05 +00004010 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004011 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004012 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004013}
4014
Chris Lattnera71e9d62009-11-10 00:55:12 +00004015//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004016
Sanjay Patel472cc782016-01-11 22:14:42 +00004017/// Given operands for a BinaryOperator, see if we can fold the result.
4018/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004019static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004020 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004021 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004022 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004023 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004024 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004025 case Instruction::FAdd:
4026 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4027
Chris Lattner9e4aa022011-02-09 17:15:04 +00004028 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004029 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004030 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004031 case Instruction::FSub:
4032 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4033
Duncan Sandsb8cee002012-03-13 11:42:19 +00004034 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004035 case Instruction::FMul:
4036 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004037 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4038 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004039 case Instruction::FDiv:
4040 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004041 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4042 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004043 case Instruction::FRem:
4044 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004045 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004046 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004047 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004048 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004049 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004050 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004051 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
4052 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4053 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
4054 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004055 default:
4056 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00004057 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4058 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00004059
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004060 // If the operation is associative, try some generic simplifications.
4061 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004062 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004063 return V;
4064
Duncan Sandsb8cee002012-03-13 11:42:19 +00004065 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00004066 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004067 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004068 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004069 return V;
4070
4071 // If the operation is with the result of a phi instruction, check whether
4072 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004073 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004074 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00004075 return V;
4076
Craig Topper9f008862014-04-15 04:59:12 +00004077 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00004078 }
4079}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004080
Sanjay Patel472cc782016-01-11 22:14:42 +00004081/// Given operands for a BinaryOperator, see if we can fold the result.
4082/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004083/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4084/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4085static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4086 const FastMathFlags &FMF, const Query &Q,
4087 unsigned MaxRecurse) {
4088 switch (Opcode) {
4089 case Instruction::FAdd:
4090 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4091 case Instruction::FSub:
4092 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4093 case Instruction::FMul:
4094 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004095 case Instruction::FDiv:
4096 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004097 default:
4098 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4099 }
4100}
4101
Duncan Sands7e800d62010-11-14 11:23:23 +00004102Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004103 const DataLayout &DL, const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004104 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00004105 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004106 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004107 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004108}
4109
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004110Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004111 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004112 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004113 const DominatorTree *DT,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004114 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004115 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004116 RecursionLimit);
4117}
4118
Sanjay Patel472cc782016-01-11 22:14:42 +00004119/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004120static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004121 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004122 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004123 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004124 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004125}
4126
4127Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004128 const DataLayout &DL, const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004129 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00004130 const Instruction *CxtI) {
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004131 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004132 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004133}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004134
Michael Ilseman54857292013-02-07 19:26:05 +00004135static bool IsIdempotent(Intrinsic::ID ID) {
4136 switch (ID) {
4137 default: return false;
4138
4139 // Unary idempotent: f(f(x)) = f(x)
4140 case Intrinsic::fabs:
4141 case Intrinsic::floor:
4142 case Intrinsic::ceil:
4143 case Intrinsic::trunc:
4144 case Intrinsic::rint:
4145 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004146 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004147 return true;
4148 }
4149}
4150
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004151static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4152 const DataLayout &DL) {
4153 GlobalValue *PtrSym;
4154 APInt PtrOffset;
4155 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4156 return nullptr;
4157
4158 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4159 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4160 Type *Int32PtrTy = Int32Ty->getPointerTo();
4161 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4162
4163 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4164 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4165 return nullptr;
4166
4167 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4168 if (OffsetInt % 4 != 0)
4169 return nullptr;
4170
4171 Constant *C = ConstantExpr::getGetElementPtr(
4172 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4173 ConstantInt::get(Int64Ty, OffsetInt / 4));
4174 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4175 if (!Loaded)
4176 return nullptr;
4177
4178 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4179 if (!LoadedCE)
4180 return nullptr;
4181
4182 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4183 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4184 if (!LoadedCE)
4185 return nullptr;
4186 }
4187
4188 if (LoadedCE->getOpcode() != Instruction::Sub)
4189 return nullptr;
4190
4191 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4192 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4193 return nullptr;
4194 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4195
4196 Constant *LoadedRHS = LoadedCE->getOperand(1);
4197 GlobalValue *LoadedRHSSym;
4198 APInt LoadedRHSOffset;
4199 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4200 DL) ||
4201 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4202 return nullptr;
4203
4204 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4205}
4206
David Majnemer17a95aa2016-07-14 06:58:37 +00004207static bool maskIsAllZeroOrUndef(Value *Mask) {
4208 auto *ConstMask = dyn_cast<Constant>(Mask);
4209 if (!ConstMask)
4210 return false;
4211 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4212 return true;
4213 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4214 ++I) {
4215 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4216 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4217 continue;
4218 return false;
4219 }
4220 return true;
4221}
4222
Michael Ilseman54857292013-02-07 19:26:05 +00004223template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004224static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004225 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004226 Intrinsic::ID IID = F->getIntrinsicID();
4227 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
4228 Type *ReturnType = F->getReturnType();
4229
4230 // Binary Ops
4231 if (NumOperands == 2) {
4232 Value *LHS = *ArgBegin;
4233 Value *RHS = *(ArgBegin + 1);
4234 if (IID == Intrinsic::usub_with_overflow ||
4235 IID == Intrinsic::ssub_with_overflow) {
4236 // X - X -> { 0, false }
4237 if (LHS == RHS)
4238 return Constant::getNullValue(ReturnType);
4239
4240 // X - undef -> undef
4241 // undef - X -> undef
4242 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4243 return UndefValue::get(ReturnType);
4244 }
4245
4246 if (IID == Intrinsic::uadd_with_overflow ||
4247 IID == Intrinsic::sadd_with_overflow) {
4248 // X + undef -> undef
4249 if (isa<UndefValue>(RHS))
4250 return UndefValue::get(ReturnType);
4251 }
4252
4253 if (IID == Intrinsic::umul_with_overflow ||
4254 IID == Intrinsic::smul_with_overflow) {
4255 // X * 0 -> { 0, false }
4256 if (match(RHS, m_Zero()))
4257 return Constant::getNullValue(ReturnType);
4258
4259 // X * undef -> { 0, false }
4260 if (match(RHS, m_Undef()))
4261 return Constant::getNullValue(ReturnType);
4262 }
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004263
4264 if (IID == Intrinsic::load_relative && isa<Constant>(LHS) &&
4265 isa<Constant>(RHS))
4266 return SimplifyRelativeLoad(cast<Constant>(LHS), cast<Constant>(RHS),
4267 Q.DL);
David Majnemer15032582015-05-22 03:56:46 +00004268 }
4269
David Majnemerd77a3b62016-07-13 23:32:53 +00004270 // Simplify calls to llvm.masked.load.*
4271 if (IID == Intrinsic::masked_load) {
David Majnemer17a95aa2016-07-14 06:58:37 +00004272 Value *MaskArg = ArgBegin[2];
4273 Value *PassthruArg = ArgBegin[3];
4274 // If the mask is all zeros or undef, the "passthru" argument is the result.
4275 if (maskIsAllZeroOrUndef(MaskArg))
4276 return PassthruArg;
David Majnemerd77a3b62016-07-13 23:32:53 +00004277 }
4278
Michael Ilseman54857292013-02-07 19:26:05 +00004279 // Perform idempotent optimizations
4280 if (!IsIdempotent(IID))
Craig Topper9f008862014-04-15 04:59:12 +00004281 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004282
4283 // Unary Ops
David Majnemer15032582015-05-22 03:56:46 +00004284 if (NumOperands == 1)
Michael Ilseman54857292013-02-07 19:26:05 +00004285 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
4286 if (II->getIntrinsicID() == IID)
4287 return II;
4288
Craig Topper9f008862014-04-15 04:59:12 +00004289 return nullptr;
Michael Ilseman54857292013-02-07 19:26:05 +00004290}
4291
Chandler Carruth9dc35582012-12-28 11:30:55 +00004292template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004293static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004294 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004295 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004296 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4297 Ty = PTy->getElementType();
4298 FunctionType *FTy = cast<FunctionType>(Ty);
4299
Dan Gohman85977e62011-11-04 18:32:42 +00004300 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004301 // call null -> undef
4302 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004303 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004304
Chandler Carruthf6182152012-12-28 14:23:29 +00004305 Function *F = dyn_cast<Function>(V);
4306 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004307 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004308
David Majnemer15032582015-05-22 03:56:46 +00004309 if (F->isIntrinsic())
4310 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004311 return Ret;
4312
Chandler Carruthf6182152012-12-28 14:23:29 +00004313 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004314 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004315
4316 SmallVector<Constant *, 4> ConstantArgs;
4317 ConstantArgs.reserve(ArgEnd - ArgBegin);
4318 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4319 Constant *C = dyn_cast<Constant>(*I);
4320 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004321 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004322 ConstantArgs.push_back(C);
4323 }
4324
4325 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004326}
4327
Chandler Carruthf6182152012-12-28 14:23:29 +00004328Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004329 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004330 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004331 const Instruction *CxtI) {
4332 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004333 RecursionLimit);
4334}
4335
Chandler Carruthf6182152012-12-28 14:23:29 +00004336Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004337 const DataLayout &DL, const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004338 const DominatorTree *DT,
Hal Finkel60db0582014-09-07 18:57:58 +00004339 const Instruction *CxtI) {
4340 return ::SimplifyCall(V, Args.begin(), Args.end(),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004341 Query(DL, TLI, DT, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004342}
4343
Sanjay Patel472cc782016-01-11 22:14:42 +00004344/// See if we can compute a simplified version of this instruction.
4345/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004346Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004347 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004348 const DominatorTree *DT) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004349 Value *Result;
4350
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004351 switch (I->getOpcode()) {
4352 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004353 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004354 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004355 case Instruction::FAdd:
4356 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004357 I->getFastMathFlags(), DL, TLI, DT, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004358 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004359 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004360 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4361 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004362 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004363 TLI, DT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004364 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004365 case Instruction::FSub:
4366 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004367 I->getFastMathFlags(), DL, TLI, DT, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004368 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004369 case Instruction::Sub:
4370 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4371 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004372 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004373 TLI, DT, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004374 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004375 case Instruction::FMul:
4376 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004377 I->getFastMathFlags(), DL, TLI, DT, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004378 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004379 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004380 Result =
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004381 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004382 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004383 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004384 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004385 I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004386 break;
4387 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004388 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004389 I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004390 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004391 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004392 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004393 I->getFastMathFlags(), DL, TLI, DT, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004394 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004395 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004396 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004397 I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004398 break;
4399 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004400 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004401 I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004402 break;
4403 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004404 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004405 I->getFastMathFlags(), DL, TLI, DT, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004406 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004407 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004408 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4409 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004410 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004411 TLI, DT, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004412 break;
4413 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004414 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004415 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004416 I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004417 break;
4418 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004419 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004420 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004421 I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004422 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004423 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004424 Result =
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004425 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004426 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004427 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004428 Result =
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004429 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004430 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004431 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004432 Result =
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004433 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004434 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004435 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004436 Result =
4437 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004438 I->getOperand(1), DL, TLI, DT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004439 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004440 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004441 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4442 I->getOperand(0), I->getOperand(1),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004443 I->getFastMathFlags(), DL, TLI, DT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004444 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004445 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004446 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004447 I->getOperand(2), DL, TLI, DT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004448 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004449 case Instruction::GetElementPtr: {
4450 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004451 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004452 Ops, DL, TLI, DT, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004453 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004454 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004455 case Instruction::InsertValue: {
4456 InsertValueInst *IV = cast<InsertValueInst>(I);
4457 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4458 IV->getInsertedValueOperand(),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004459 IV->getIndices(), DL, TLI, DT, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004460 break;
4461 }
David Majnemer25a796e2015-07-13 01:15:46 +00004462 case Instruction::ExtractValue: {
4463 auto *EVI = cast<ExtractValueInst>(I);
4464 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004465 EVI->getIndices(), DL, TLI, DT, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004466 break;
4467 }
David Majnemer599ca442015-07-13 01:15:53 +00004468 case Instruction::ExtractElement: {
4469 auto *EEI = cast<ExtractElementInst>(I);
4470 Result = SimplifyExtractElementInst(
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004471 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, I);
David Majnemer599ca442015-07-13 01:15:53 +00004472 break;
4473 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004474 case Instruction::PHI:
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004475 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004476 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004477 case Instruction::Call: {
4478 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004479 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004480 TLI, DT, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004481 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004482 }
David Majnemer6774d612016-07-26 17:58:05 +00004483#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4484#include "llvm/IR/Instruction.def"
4485#undef HANDLE_CAST_INST
4486 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004487 DL, TLI, DT, I);
David Majnemera90a6212016-07-26 05:52:29 +00004488 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004489 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004490
Hal Finkelf2199b22015-10-23 20:37:08 +00004491 // In general, it is possible for computeKnownBits to determine all bits in a
4492 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004493 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004494 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4495 APInt KnownZero(BitWidth, 0);
4496 APInt KnownOne(BitWidth, 0);
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004497 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, I, DT);
Hal Finkelf2199b22015-10-23 20:37:08 +00004498 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004499 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004500 }
4501
Duncan Sands64e41cf2010-11-17 08:35:29 +00004502 /// If called on unreachable code, the above logic may report that the
4503 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004504 /// detecting that case here, returning a safe value instead.
4505 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004506}
4507
Sanjay Patelf44bd382016-01-20 18:59:48 +00004508/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004509/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004510///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004511/// This is the common implementation of the recursive simplification routines.
4512/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4513/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4514/// instructions to process and attempt to simplify it using
4515/// InstructionSimplify.
4516///
4517/// This routine returns 'true' only when *it* simplifies something. The passed
4518/// in simplified value does not count toward this.
4519static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004520 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004521 const DominatorTree *DT) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004522 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004523 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004524 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004525
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004526 // If we have an explicit value to collapse to, do that round of the
4527 // simplification loop by hand initially.
4528 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004529 for (User *U : I->users())
4530 if (U != I)
4531 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004532
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004533 // Replace the instruction with its simplified value.
4534 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004535
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004536 // Gracefully handle edge cases where the instruction is not wired into any
4537 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004538 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4539 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004540 I->eraseFromParent();
4541 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004542 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004543 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004544
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004545 // Note that we must test the size on each iteration, the worklist can grow.
4546 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4547 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004548
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004549 // See if this instruction simplifies.
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004550 SimpleV = SimplifyInstruction(I, DL, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004551 if (!SimpleV)
4552 continue;
4553
4554 Simplified = true;
4555
4556 // Stash away all the uses of the old instruction so we can check them for
4557 // recursive simplifications after a RAUW. This is cheaper than checking all
4558 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004559 for (User *U : I->users())
4560 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004561
4562 // Replace the instruction with its simplified value.
4563 I->replaceAllUsesWith(SimpleV);
4564
4565 // Gracefully handle edge cases where the instruction is not wired into any
4566 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004567 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4568 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004569 I->eraseFromParent();
4570 }
4571 return Simplified;
4572}
4573
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004574bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004575 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004576 const DominatorTree *DT) {
4577 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004578}
4579
4580bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004581 const TargetLibraryInfo *TLI,
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004582 const DominatorTree *DT) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004583 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4584 assert(SimpleV && "Must provide a simplified value.");
Hal Finkel3ca4a6b2016-12-15 03:02:15 +00004585 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT);
Chris Lattner852d6d62009-11-10 22:26:15 +00004586}