blob: 8fce1630aeec5ec6c0e5be27a451b6a4065676a4 [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"
Sanjay Patel54656ca2017-02-06 18:26:06 +000027#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
Chandler Carruth8a8cd2b2014-01-07 11:48:04 +000028#include "llvm/Analysis/ValueTracking.h"
David Majnemer599ca442015-07-13 01:15:53 +000029#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000030#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/DataLayout.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000032#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000034#include "llvm/IR/GlobalAlias.h"
35#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000036#include "llvm/IR/PatternMatch.h"
Chandler Carruth4220e9c2014-03-04 11:17:44 +000037#include "llvm/IR/ValueHandle.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000038#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000039using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000040using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000041
Chandler Carruthf1221bd2014-04-22 02:48:03 +000042#define DEBUG_TYPE "instsimplify"
43
Chris Lattner9e4aa022011-02-09 17:15:04 +000044enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000045
Duncan Sands3547d2e2010-12-22 09:40:51 +000046STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000047STATISTIC(NumReassoc, "Number of reassociations");
48
Benjamin Kramercfd8d902014-09-12 08:56:53 +000049namespace {
Duncan Sandsb8cee002012-03-13 11:42:19 +000050struct Query {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000051 const DataLayout &DL;
Duncan Sandsb8cee002012-03-13 11:42:19 +000052 const TargetLibraryInfo *TLI;
53 const DominatorTree *DT;
Daniel Jasperaec2fa32016-12-19 08:22:17 +000054 AssumptionCache *AC;
Hal Finkel60db0582014-09-07 18:57:58 +000055 const Instruction *CxtI;
Duncan Sandsb8cee002012-03-13 11:42:19 +000056
Mehdi Aminia28d91d2015-03-10 02:37:25 +000057 Query(const DataLayout &DL, const TargetLibraryInfo *tli,
Daniel Jasperaec2fa32016-12-19 08:22:17 +000058 const DominatorTree *dt, AssumptionCache *ac = nullptr,
59 const Instruction *cxti = nullptr)
60 : DL(DL), TLI(tli), DT(dt), AC(ac), CxtI(cxti) {}
Duncan Sandsb8cee002012-03-13 11:42:19 +000061};
Benjamin Kramercfd8d902014-09-12 08:56:53 +000062} // end anonymous namespace
Duncan Sandsb8cee002012-03-13 11:42:19 +000063
64static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
65static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000066 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000067static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
68 const Query &, unsigned);
Duncan Sandsb8cee002012-03-13 11:42:19 +000069static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000070 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000071static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
72 const Query &Q, unsigned MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +000073static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
74static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000075static Value *SimplifyCastInst(unsigned, Value *, Type *,
76 const Query &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000077
Sanjay Patel472cc782016-01-11 22:14:42 +000078/// For a boolean type, or a vector of boolean type, return false, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000079/// a vector with every element false, as appropriate for the type.
80static Constant *getFalse(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000081 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000082 "Expected i1 type or a vector of i1!");
83 return Constant::getNullValue(Ty);
84}
85
Sanjay Patel472cc782016-01-11 22:14:42 +000086/// For a boolean type, or a vector of boolean type, return true, or
Duncan Sandsc1c92712011-07-26 15:03:53 +000087/// a vector with every element true, as appropriate for the type.
88static Constant *getTrue(Type *Ty) {
Nick Lewyckye659b842011-12-01 02:39:36 +000089 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsc1c92712011-07-26 15:03:53 +000090 "Expected i1 type or a vector of i1!");
91 return Constant::getAllOnesValue(Ty);
92}
93
Duncan Sands3d5692a2011-10-30 19:56:36 +000094/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
95static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
96 Value *RHS) {
97 CmpInst *Cmp = dyn_cast<CmpInst>(V);
98 if (!Cmp)
99 return false;
100 CmpInst::Predicate CPred = Cmp->getPredicate();
101 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
102 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
103 return true;
104 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
105 CRHS == LHS;
106}
107
Sanjay Patel472cc782016-01-11 22:14:42 +0000108/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +0000109static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
110 Instruction *I = dyn_cast<Instruction>(V);
111 if (!I)
112 // Arguments and constants dominate all instructions.
113 return true;
114
Chandler Carruth3ffccb32012-03-21 10:58:47 +0000115 // If we are processing instructions (and/or basic blocks) that have not been
116 // fully added to a function, the parent nodes may still be null. Simply
117 // return the conservative answer in these cases.
118 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
119 return false;
120
Duncan Sands5ffc2982010-11-16 12:16:38 +0000121 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000122 if (DT) {
123 if (!DT->isReachableFromEntry(P->getParent()))
124 return true;
125 if (!DT->isReachableFromEntry(I->getParent()))
126 return false;
127 return DT->dominates(I, P);
128 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000129
David Majnemer8a1c45d2015-12-12 05:38:55 +0000130 // Otherwise, if the instruction is in the entry block and is not an invoke,
131 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000132 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000133 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000134 return true;
135
136 return false;
137}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000138
Sanjay Patel472cc782016-01-11 22:14:42 +0000139/// Simplify "A op (B op' C)" by distributing op over op', turning it into
140/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000141/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
142/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
143/// Returns the simplified value, or null if no simplification was performed.
144static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000145 unsigned OpcToExpand, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000146 unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000147 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000148 // Recursion is always used, so bail out at once if we already hit the limit.
149 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000150 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000151
152 // Check whether the expression has the form "(A op' B) op C".
153 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
154 if (Op0->getOpcode() == OpcodeToExpand) {
155 // It does! Try turning it into "(A op C) op' (B op C)".
156 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
157 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000158 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
159 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000160 // They do! Return "L op' R" if it simplifies or is already available.
161 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000162 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
163 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000164 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000165 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000166 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000167 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000168 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000169 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000170 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000171 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000172 }
173 }
174
175 // Check whether the expression has the form "A op (B op' C)".
176 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
177 if (Op1->getOpcode() == OpcodeToExpand) {
178 // It does! Try turning it into "(A op B) op' (A op C)".
179 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
180 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000181 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
182 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000183 // They do! Return "L op' R" if it simplifies or is already available.
184 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000185 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
186 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000187 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000188 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000189 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000190 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000191 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000192 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000193 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000194 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000195 }
196 }
197
Craig Topper9f008862014-04-15 04:59:12 +0000198 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000199}
200
Sanjay Patel472cc782016-01-11 22:14:42 +0000201/// Generic simplifications for associative binary operations.
202/// Returns the simpler value, or null if none was found.
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000203static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000204 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramerb6d52b82010-12-28 13:52:52 +0000205 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000206 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
207
208 // Recursion is always used, so bail out at once if we already hit the limit.
209 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000210 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000211
212 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
213 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
214
215 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
216 if (Op0 && Op0->getOpcode() == Opcode) {
217 Value *A = Op0->getOperand(0);
218 Value *B = Op0->getOperand(1);
219 Value *C = RHS;
220
221 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000222 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000223 // It does! Return "A op V" if it simplifies or is already available.
224 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000225 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000227 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000228 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000229 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000230 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000231 }
232 }
233
234 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
235 if (Op1 && Op1->getOpcode() == Opcode) {
236 Value *A = LHS;
237 Value *B = Op1->getOperand(0);
238 Value *C = Op1->getOperand(1);
239
240 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000241 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000242 // It does! Return "V op C" if it simplifies or is already available.
243 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000244 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000245 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000246 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000247 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000248 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000249 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000250 }
251 }
252
253 // The remaining transforms require commutativity as well as associativity.
254 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000255 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000256
257 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
258 if (Op0 && Op0->getOpcode() == Opcode) {
259 Value *A = Op0->getOperand(0);
260 Value *B = Op0->getOperand(1);
261 Value *C = RHS;
262
263 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000264 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000265 // It does! Return "V op B" if it simplifies or is already available.
266 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000267 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000269 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000270 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000271 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000272 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000273 }
274 }
275
276 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
277 if (Op1 && Op1->getOpcode() == Opcode) {
278 Value *A = LHS;
279 Value *B = Op1->getOperand(0);
280 Value *C = Op1->getOperand(1);
281
282 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000283 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000284 // It does! Return "B op V" if it simplifies or is already available.
285 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000286 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000287 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000288 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000289 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000290 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000291 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000292 }
293 }
294
Craig Topper9f008862014-04-15 04:59:12 +0000295 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000296}
297
Sanjay Patel472cc782016-01-11 22:14:42 +0000298/// In the case of a binary operation with a select instruction as an operand,
299/// try to simplify the binop by seeing whether evaluating it on both branches
300/// of the select results in the same value. Returns the common value if so,
301/// otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000302static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000303 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000304 // Recursion is always used, so bail out at once if we already hit the limit.
305 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000306 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000307
Duncan Sandsb0579e92010-11-10 13:00:08 +0000308 SelectInst *SI;
309 if (isa<SelectInst>(LHS)) {
310 SI = cast<SelectInst>(LHS);
311 } else {
312 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
313 SI = cast<SelectInst>(RHS);
314 }
315
316 // Evaluate the BinOp on the true and false branches of the select.
317 Value *TV;
318 Value *FV;
319 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000320 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
321 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000322 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000323 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
324 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000325 }
326
Duncan Sandse3c53952011-01-01 16:12:09 +0000327 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000328 // If they both failed to simplify then return null.
329 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000330 return TV;
331
332 // If one branch simplified to undef, return the other one.
333 if (TV && isa<UndefValue>(TV))
334 return FV;
335 if (FV && isa<UndefValue>(FV))
336 return TV;
337
338 // If applying the operation did not change the true and false select values,
339 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000340 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000341 return SI;
342
343 // If one branch simplified and the other did not, and the simplified
344 // value is equal to the unsimplified one, return the simplified value.
345 // For example, select (cond, X, X & Z) & Z -> X & Z.
346 if ((FV && !TV) || (TV && !FV)) {
347 // Check that the simplified value has the form "X op Y" where "op" is the
348 // same as the original operation.
349 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
350 if (Simplified && Simplified->getOpcode() == Opcode) {
351 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
352 // We already know that "op" is the same as for the simplified value. See
353 // if the operands match too. If so, return the simplified value.
354 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
355 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
356 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000357 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
358 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000359 return Simplified;
360 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000361 Simplified->getOperand(1) == UnsimplifiedLHS &&
362 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000363 return Simplified;
364 }
365 }
366
Craig Topper9f008862014-04-15 04:59:12 +0000367 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000368}
369
Sanjay Patel472cc782016-01-11 22:14:42 +0000370/// In the case of a comparison with a select instruction, try to simplify the
371/// comparison by seeing whether both branches of the select result in the same
372/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000373static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000374 Value *RHS, const Query &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000375 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000376 // Recursion is always used, so bail out at once if we already hit the limit.
377 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000378 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000379
Duncan Sandsb0579e92010-11-10 13:00:08 +0000380 // Make sure the select is on the LHS.
381 if (!isa<SelectInst>(LHS)) {
382 std::swap(LHS, RHS);
383 Pred = CmpInst::getSwappedPredicate(Pred);
384 }
385 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
386 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000387 Value *Cond = SI->getCondition();
388 Value *TV = SI->getTrueValue();
389 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000390
Duncan Sands06504022011-02-03 09:37:39 +0000391 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000392 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000393 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000394 if (TCmp == Cond) {
395 // It not only simplified, it simplified to the select condition. Replace
396 // it with 'true'.
397 TCmp = getTrue(Cond->getType());
398 } else if (!TCmp) {
399 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
400 // condition then we can replace it with 'true'. Otherwise give up.
401 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000402 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000403 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000404 }
405
Duncan Sands3d5692a2011-10-30 19:56:36 +0000406 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000407 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000408 if (FCmp == Cond) {
409 // It not only simplified, it simplified to the select condition. Replace
410 // it with 'false'.
411 FCmp = getFalse(Cond->getType());
412 } else if (!FCmp) {
413 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
414 // condition then we can replace it with 'false'. Otherwise give up.
415 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000416 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000417 FCmp = getFalse(Cond->getType());
418 }
419
420 // If both sides simplified to the same value, then use it as the result of
421 // the original comparison.
422 if (TCmp == FCmp)
423 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000424
425 // The remaining cases only make sense if the select condition has the same
426 // type as the result of the comparison, so bail out if this is not so.
427 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000428 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000429 // If the false value simplified to false, then the result of the compare
430 // is equal to "Cond && TCmp". This also catches the case when the false
431 // value simplified to false and the true value to true, returning "Cond".
432 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000433 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000434 return V;
435 // If the true value simplified to true, then the result of the compare
436 // is equal to "Cond || FCmp".
437 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000438 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000439 return V;
440 // Finally, if the false value simplified to true and the true value to
441 // false, then the result of the compare is equal to "!Cond".
442 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
443 if (Value *V =
444 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000445 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000446 return V;
447
Craig Topper9f008862014-04-15 04:59:12 +0000448 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000449}
450
Sanjay Patel472cc782016-01-11 22:14:42 +0000451/// In the case of a binary operation with an operand that is a PHI instruction,
452/// try to simplify the binop by seeing whether evaluating it on the incoming
453/// phi values yields the same result for every value. If so returns the common
454/// value, otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000455static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000456 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000457 // Recursion is always used, so bail out at once if we already hit the limit.
458 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000459 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000460
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000461 PHINode *PI;
462 if (isa<PHINode>(LHS)) {
463 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000464 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000465 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000466 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000467 } else {
468 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
469 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000470 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000471 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000472 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000473 }
474
475 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000476 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000477 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000478 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000479 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000480 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000481 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
482 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000483 // If the operation failed to simplify, or simplified to a different value
484 // to previously, then give up.
485 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000486 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000487 CommonValue = V;
488 }
489
490 return CommonValue;
491}
492
Sanjay Patel472cc782016-01-11 22:14:42 +0000493/// In the case of a comparison with a PHI instruction, try to simplify the
494/// comparison by seeing whether comparing with all of the incoming phi values
495/// yields the same result every time. If so returns the common result,
496/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000497static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000498 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000499 // Recursion is always used, so bail out at once if we already hit the limit.
500 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000501 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000502
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000503 // Make sure the phi is on the LHS.
504 if (!isa<PHINode>(LHS)) {
505 std::swap(LHS, RHS);
506 Pred = CmpInst::getSwappedPredicate(Pred);
507 }
508 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
509 PHINode *PI = cast<PHINode>(LHS);
510
Duncan Sands5ffc2982010-11-16 12:16:38 +0000511 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000512 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000513 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000514
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000515 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000516 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000517 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000518 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000519 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000520 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000521 // If the operation failed to simplify, or simplified to a different value
522 // to previously, then give up.
523 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000524 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000525 CommonValue = V;
526 }
527
528 return CommonValue;
529}
530
Sanjay Patel472cc782016-01-11 22:14:42 +0000531/// Given operands for an Add, see if we can fold the result.
532/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000533static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000534 const Query &Q, unsigned MaxRecurse) {
Chris Lattner3d9823b2009-11-27 17:42:22 +0000535 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000536 if (Constant *CRHS = dyn_cast<Constant>(Op1))
537 return ConstantFoldBinaryOpOperands(Instruction::Add, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +0000538
Chris Lattner3d9823b2009-11-27 17:42:22 +0000539 // Canonicalize the constant to the RHS.
540 std::swap(Op0, Op1);
541 }
Duncan Sands7e800d62010-11-14 11:23:23 +0000542
Duncan Sands0a2c41682010-12-15 14:07:39 +0000543 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000544 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000545 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000546
Duncan Sands0a2c41682010-12-15 14:07:39 +0000547 // X + 0 -> X
548 if (match(Op1, m_Zero()))
549 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000550
Duncan Sands0a2c41682010-12-15 14:07:39 +0000551 // X + (Y - X) -> Y
552 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000553 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000554 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000555 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
556 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000557 return Y;
558
559 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000560 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000561 if (match(Op0, m_Not(m_Specific(Op1))) ||
562 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000563 return Constant::getAllOnesValue(Ty);
564
565 // add nsw/nuw (xor Y, signbit), signbit --> Y
566 // The no-wrapping add guarantees that the top bit will be set by the add.
567 // Therefore, the xor must be clearing the already set sign bit of Y.
568 Constant *SignBit =
569 ConstantInt::get(Ty, APInt::getSignBit(Ty->getScalarSizeInBits()));
570 if ((isNSW || isNUW) && match(Op1, m_Specific(SignBit)) &&
571 match(Op0, m_Xor(m_Value(Y), m_Specific(SignBit))))
572 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000573
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000574 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000575 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000576 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000577 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000578
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000579 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000580 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000581 MaxRecurse))
582 return V;
583
Duncan Sandsb238de02010-11-19 09:20:39 +0000584 // Threading Add over selects and phi nodes is pointless, so don't bother.
585 // Threading over the select in "A + select(cond, B, C)" means evaluating
586 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
587 // only if B and C are equal. If B and C are equal then (since we assume
588 // that operands have already been simplified) "select(cond, B, C)" should
589 // have been simplified to the common value of B and C already. Analysing
590 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
591 // for threading over phi nodes.
592
Craig Topper9f008862014-04-15 04:59:12 +0000593 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000594}
595
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000596Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000597 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000598 const DominatorTree *DT, AssumptionCache *AC,
599 const Instruction *CxtI) {
600 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000601 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000602}
603
Chandler Carrutha0796552012-03-12 11:19:31 +0000604/// \brief Compute the base pointer and cumulative constant offsets for V.
605///
606/// This strips all constant offsets off of V, leaving it the base pointer, and
607/// accumulates the total constant offset applied in the returned constant. It
608/// returns 0 if V is not a pointer, and returns the constant '0' if there are
609/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000610///
611/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
612/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
613/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000614static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000615 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000616 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000617
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000618 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000619 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000620
621 // Even though we don't look through PHI nodes, we could be called on an
622 // instruction in an unreachable block, which may be on a cycle.
623 SmallPtrSet<Value *, 4> Visited;
624 Visited.insert(V);
625 do {
626 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000627 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000628 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000629 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000630 V = GEP->getPointerOperand();
631 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000632 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000633 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000634 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000635 break;
636 V = GA->getAliasee();
637 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000638 if (auto CS = CallSite(V))
639 if (Value *RV = CS.getReturnedArgOperand()) {
640 V = RV;
641 continue;
642 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000643 break;
644 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000645 assert(V->getType()->getScalarType()->isPointerTy() &&
646 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000647 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000648
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000649 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
650 if (V->getType()->isVectorTy())
651 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
652 OffsetIntPtr);
653 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000654}
655
656/// \brief Compute the constant difference between two pointer values.
657/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000658static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
659 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000660 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
661 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000662
663 // If LHS and RHS are not related via constant offsets to the same base
664 // value, there is nothing we can do here.
665 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000666 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000667
668 // Otherwise, the difference of LHS - RHS can be computed as:
669 // LHS - RHS
670 // = (LHSOffset + Base) - (RHSOffset + Base)
671 // = LHSOffset - RHSOffset
672 return ConstantExpr::getSub(LHSOffset, RHSOffset);
673}
674
Sanjay Patel472cc782016-01-11 22:14:42 +0000675/// Given operands for a Sub, see if we can fold the result.
676/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000677static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000678 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000679 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000680 if (Constant *CRHS = dyn_cast<Constant>(Op1))
681 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000682
683 // X - undef -> undef
684 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000685 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000686 return UndefValue::get(Op0->getType());
687
688 // X - 0 -> X
689 if (match(Op1, m_Zero()))
690 return Op0;
691
692 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000693 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000694 return Constant::getNullValue(Op0->getType());
695
Sanjay Patelefd88852016-10-19 21:23:45 +0000696 // Is this a negation?
697 if (match(Op0, m_Zero())) {
698 // 0 - X -> 0 if the sub is NUW.
699 if (isNUW)
700 return Op0;
701
702 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
703 APInt KnownZero(BitWidth, 0);
704 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000705 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patelefd88852016-10-19 21:23:45 +0000706 if (KnownZero == ~APInt::getSignBit(BitWidth)) {
707 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
708 // Op1 must be 0 because negating the minimum signed value is undefined.
709 if (isNSW)
710 return Op0;
711
712 // 0 - X -> X if X is 0 or the minimum signed value.
713 return Op1;
714 }
715 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000716
Duncan Sands99589d02011-01-18 11:50:19 +0000717 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
718 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000719 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000720 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
721 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000722 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000723 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000724 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000725 // It does, we successfully reassociated!
726 ++NumReassoc;
727 return W;
728 }
729 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000730 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000731 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000732 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000733 // It does, we successfully reassociated!
734 ++NumReassoc;
735 return W;
736 }
737 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000738
Duncan Sands99589d02011-01-18 11:50:19 +0000739 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
740 // For example, X - (X + 1) -> -1
741 X = Op0;
742 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
743 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000744 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000745 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000746 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000747 // It does, we successfully reassociated!
748 ++NumReassoc;
749 return W;
750 }
751 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000752 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, 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::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000755 // It does, we successfully reassociated!
756 ++NumReassoc;
757 return W;
758 }
759 }
760
761 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
762 // For example, X - (X - Y) -> Y.
763 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000764 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
765 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000766 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000767 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000768 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000769 // It does, we successfully reassociated!
770 ++NumReassoc;
771 return W;
772 }
773
Duncan Sands395ac42d2012-03-13 14:07:05 +0000774 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
775 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
776 match(Op1, m_Trunc(m_Value(Y))))
777 if (X->getType() == Y->getType())
778 // See if "V === X - Y" simplifies.
779 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
780 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000781 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
782 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000783 // It does, return the simplified "trunc V".
784 return W;
785
786 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000787 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000788 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000789 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000790 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
791
Duncan Sands99589d02011-01-18 11:50:19 +0000792 // i1 sub -> xor.
793 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000794 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000795 return V;
796
Duncan Sands0a2c41682010-12-15 14:07:39 +0000797 // Threading Sub over selects and phi nodes is pointless, so don't bother.
798 // Threading over the select in "A - select(cond, B, C)" means evaluating
799 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
800 // only if B and C are equal. If B and C are equal then (since we assume
801 // that operands have already been simplified) "select(cond, B, C)" should
802 // have been simplified to the common value of B and C already. Analysing
803 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
804 // for threading over phi nodes.
805
Craig Topper9f008862014-04-15 04:59:12 +0000806 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000807}
808
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000809Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000810 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000811 const DominatorTree *DT, AssumptionCache *AC,
812 const Instruction *CxtI) {
813 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000814 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000815}
816
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000817/// Given operands for an FAdd, see if we can fold the result. If not, this
818/// returns null.
819static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
820 const Query &Q, unsigned MaxRecurse) {
821 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000822 if (Constant *CRHS = dyn_cast<Constant>(Op1))
823 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000824
825 // Canonicalize the constant to the RHS.
826 std::swap(Op0, Op1);
827 }
828
829 // fadd X, -0 ==> X
830 if (match(Op1, m_NegZero()))
831 return Op0;
832
833 // fadd X, 0 ==> X, when we know X is not -0
834 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000835 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000836 return Op0;
837
838 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
839 // where nnan and ninf have to occur at least once somewhere in this
840 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000841 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000842 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
843 SubOp = Op1;
844 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
845 SubOp = Op0;
846 if (SubOp) {
847 Instruction *FSub = cast<Instruction>(SubOp);
848 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
849 (FMF.noInfs() || FSub->hasNoInfs()))
850 return Constant::getNullValue(Op0->getType());
851 }
852
Craig Topper9f008862014-04-15 04:59:12 +0000853 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000854}
855
856/// Given operands for an FSub, see if we can fold the result. If not, this
857/// returns null.
858static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
859 const Query &Q, unsigned MaxRecurse) {
860 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000861 if (Constant *CRHS = dyn_cast<Constant>(Op1))
862 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000863 }
864
865 // fsub X, 0 ==> X
866 if (match(Op1, m_Zero()))
867 return Op0;
868
869 // fsub X, -0 ==> X, when we know X is not -0
870 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000871 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000872 return Op0;
873
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000874 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000875 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000876 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
877 return X;
878
879 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000880 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000881 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
882 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000883
Benjamin Kramer228680d2015-06-14 21:01:20 +0000884 // fsub nnan x, x ==> 0.0
885 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000886 return Constant::getNullValue(Op0->getType());
887
Craig Topper9f008862014-04-15 04:59:12 +0000888 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000889}
890
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000891/// Given the operands for an FMul, see if we can fold the result
892static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
893 FastMathFlags FMF,
894 const Query &Q,
895 unsigned MaxRecurse) {
896 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000897 if (Constant *CRHS = dyn_cast<Constant>(Op1))
898 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000899
900 // Canonicalize the constant to the RHS.
901 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000902 }
903
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000904 // fmul X, 1.0 ==> X
905 if (match(Op1, m_FPOne()))
906 return Op0;
907
908 // fmul nnan nsz X, 0 ==> 0
909 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
910 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000911
Craig Topper9f008862014-04-15 04:59:12 +0000912 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000913}
914
Sanjay Patel472cc782016-01-11 22:14:42 +0000915/// Given operands for a Mul, see if we can fold the result.
916/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000917static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
918 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000919 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000920 if (Constant *CRHS = dyn_cast<Constant>(Op1))
921 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000922
923 // Canonicalize the constant to the RHS.
924 std::swap(Op0, Op1);
925 }
926
927 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000928 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000929 return Constant::getNullValue(Op0->getType());
930
931 // X * 0 -> 0
932 if (match(Op1, m_Zero()))
933 return Op1;
934
935 // X * 1 -> X
936 if (match(Op1, m_One()))
937 return Op0;
938
Duncan Sandsb67edc62011-01-30 18:03:50 +0000939 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000940 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000941 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
942 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
943 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000944
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000945 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000946 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000947 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000948 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000949
950 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000951 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000952 MaxRecurse))
953 return V;
954
955 // Mul distributes over Add. Try some generic simplifications based on this.
956 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000957 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000958 return V;
959
960 // If the operation is with the result of a select instruction, check whether
961 // operating on either branch of the select always yields the same value.
962 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000963 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000964 MaxRecurse))
965 return V;
966
967 // If the operation is with the result of a phi instruction, check whether
968 // operating on all incoming values of the phi always yields the same value.
969 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000970 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000971 MaxRecurse))
972 return V;
973
Craig Topper9f008862014-04-15 04:59:12 +0000974 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000975}
976
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000977Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000978 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000979 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000980 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000981 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000982 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000983 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000984}
985
986Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000987 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000988 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000989 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000990 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000991 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000992 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000993}
994
Chandler Carruth66b31302015-01-04 12:03:27 +0000995Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000997 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000998 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000999 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001000 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001001 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00001002}
1003
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001004Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001005 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001006 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001007 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001008 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001009 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001010}
1011
Sanjay Patel472cc782016-01-11 22:14:42 +00001012/// Given operands for an SDiv or UDiv, see if we can fold the result.
1013/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001014static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001015 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001016 if (Constant *C0 = dyn_cast<Constant>(Op0))
1017 if (Constant *C1 = dyn_cast<Constant>(Op1))
1018 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +00001019
Duncan Sands65995fa2011-01-28 18:50:50 +00001020 bool isSigned = Opcode == Instruction::SDiv;
1021
Duncan Sands771e82a2011-01-28 16:51:11 +00001022 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001023 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001024 return Op1;
1025
David Majnemer71dc8fb2014-12-10 07:52:18 +00001026 // X / 0 -> undef, we don't need to preserve faults!
1027 if (match(Op1, m_Zero()))
1028 return UndefValue::get(Op1->getType());
1029
Duncan Sands771e82a2011-01-28 16:51:11 +00001030 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001031 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001032 return Constant::getNullValue(Op0->getType());
1033
1034 // 0 / X -> 0, we don't need to preserve faults!
1035 if (match(Op0, m_Zero()))
1036 return Op0;
1037
1038 // X / 1 -> X
1039 if (match(Op1, m_One()))
1040 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001041
1042 if (Op0->getType()->isIntegerTy(1))
1043 // It can't be division by zero, hence it must be division by one.
1044 return Op0;
1045
1046 // X / X -> 1
1047 if (Op0 == Op1)
1048 return ConstantInt::get(Op0->getType(), 1);
1049
1050 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001051 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001052 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1053 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001054 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001055 // If the Mul knows it does not overflow, then we are good to go.
1056 if ((isSigned && Mul->hasNoSignedWrap()) ||
1057 (!isSigned && Mul->hasNoUnsignedWrap()))
1058 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001059 // If X has the form X = A / Y then X * Y cannot overflow.
1060 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1061 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1062 return X;
1063 }
1064
Duncan Sands65995fa2011-01-28 18:50:50 +00001065 // (X rem Y) / Y -> 0
1066 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1067 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1068 return Constant::getNullValue(Op0->getType());
1069
David Majnemercb9d5962014-10-11 10:20:01 +00001070 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1071 ConstantInt *C1, *C2;
1072 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1073 match(Op1, m_ConstantInt(C2))) {
1074 bool Overflow;
1075 C1->getValue().umul_ov(C2->getValue(), Overflow);
1076 if (Overflow)
1077 return Constant::getNullValue(Op0->getType());
1078 }
1079
Duncan Sands65995fa2011-01-28 18:50:50 +00001080 // If the operation is with the result of a select instruction, check whether
1081 // operating on either branch of the select always yields the same value.
1082 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001083 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001084 return V;
1085
1086 // If the operation is with the result of a phi instruction, check whether
1087 // operating on all incoming values of the phi always yields the same value.
1088 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001089 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001090 return V;
1091
Craig Topper9f008862014-04-15 04:59:12 +00001092 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001093}
1094
Sanjay Patel472cc782016-01-11 22:14:42 +00001095/// Given operands for an SDiv, see if we can fold the result.
1096/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001097static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1098 unsigned MaxRecurse) {
1099 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001100 return V;
1101
Craig Topper9f008862014-04-15 04:59:12 +00001102 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001103}
1104
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001105Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001106 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001107 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001108 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001109 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001110 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001111}
1112
Sanjay Patel472cc782016-01-11 22:14:42 +00001113/// Given operands for a UDiv, see if we can fold the result.
1114/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001115static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1116 unsigned MaxRecurse) {
1117 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001118 return V;
1119
David Majnemer63da0c22017-01-06 22:58:02 +00001120 // udiv %V, C -> 0 if %V < C
1121 if (MaxRecurse) {
1122 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1123 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1124 if (C->isAllOnesValue()) {
1125 return Constant::getNullValue(Op0->getType());
1126 }
1127 }
1128 }
1129
Craig Topper9f008862014-04-15 04:59:12 +00001130 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001131}
1132
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001133Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001134 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001135 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001136 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001137 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001138 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001139}
1140
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001141static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1142 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001143 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001144 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001145 return Op0;
1146
1147 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001148 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001149 return Op1;
1150
Zia Ansari394cef82016-12-08 23:27:40 +00001151 // X / 1.0 -> X
1152 if (match(Op1, m_FPOne()))
1153 return Op0;
1154
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001155 // 0 / X -> 0
1156 // Requires that NaNs are off (X could be zero) and signed zeroes are
1157 // ignored (X could be positive or negative, so the output sign is unknown).
1158 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1159 return Op0;
1160
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001161 if (FMF.noNaNs()) {
1162 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001163 if (Op0 == Op1)
1164 return ConstantFP::get(Op0->getType(), 1.0);
1165
1166 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001167 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001168 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1169 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1170 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1171 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1172 BinaryOperator::getFNegArgument(Op1) == Op0))
1173 return ConstantFP::get(Op0->getType(), -1.0);
1174 }
1175
Craig Topper9f008862014-04-15 04:59:12 +00001176 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001177}
1178
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001179Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001180 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001181 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001182 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001183 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001184 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001185 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001186}
1187
Sanjay Patel472cc782016-01-11 22:14:42 +00001188/// Given operands for an SRem or URem, see if we can fold the result.
1189/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001190static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001191 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001192 if (Constant *C0 = dyn_cast<Constant>(Op0))
1193 if (Constant *C1 = dyn_cast<Constant>(Op1))
1194 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001195
Duncan Sandsa3e36992011-05-02 16:27:02 +00001196 // X % undef -> undef
1197 if (match(Op1, m_Undef()))
1198 return Op1;
1199
1200 // undef % X -> 0
1201 if (match(Op0, m_Undef()))
1202 return Constant::getNullValue(Op0->getType());
1203
1204 // 0 % X -> 0, we don't need to preserve faults!
1205 if (match(Op0, m_Zero()))
1206 return Op0;
1207
1208 // X % 0 -> undef, we don't need to preserve faults!
1209 if (match(Op1, m_Zero()))
1210 return UndefValue::get(Op0->getType());
1211
1212 // X % 1 -> 0
1213 if (match(Op1, m_One()))
1214 return Constant::getNullValue(Op0->getType());
1215
1216 if (Op0->getType()->isIntegerTy(1))
1217 // It can't be remainder by zero, hence it must be remainder by one.
1218 return Constant::getNullValue(Op0->getType());
1219
1220 // X % X -> 0
1221 if (Op0 == Op1)
1222 return Constant::getNullValue(Op0->getType());
1223
David Majnemerb435a422014-09-17 04:16:35 +00001224 // (X % Y) % Y -> X % Y
1225 if ((Opcode == Instruction::SRem &&
1226 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1227 (Opcode == Instruction::URem &&
1228 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001229 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001230
Duncan Sandsa3e36992011-05-02 16:27:02 +00001231 // If the operation is with the result of a select instruction, check whether
1232 // operating on either branch of the select always yields the same value.
1233 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001234 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001235 return V;
1236
1237 // If the operation is with the result of a phi instruction, check whether
1238 // operating on all incoming values of the phi always yields the same value.
1239 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001240 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001241 return V;
1242
Craig Topper9f008862014-04-15 04:59:12 +00001243 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001244}
1245
Sanjay Patel472cc782016-01-11 22:14:42 +00001246/// Given operands for an SRem, see if we can fold the result.
1247/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001248static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1249 unsigned MaxRecurse) {
1250 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001251 return V;
1252
Craig Topper9f008862014-04-15 04:59:12 +00001253 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001254}
1255
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001256Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001257 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001258 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001259 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001260 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001261 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001262}
1263
Sanjay Patel472cc782016-01-11 22:14:42 +00001264/// Given operands for a URem, see if we can fold the result.
1265/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001266static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001267 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001268 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001269 return V;
1270
David Majnemer8c0e62f2017-01-06 21:23:51 +00001271 // urem %V, C -> %V if %V < C
1272 if (MaxRecurse) {
1273 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1274 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1275 if (C->isAllOnesValue()) {
1276 return Op0;
1277 }
1278 }
1279 }
1280
Craig Topper9f008862014-04-15 04:59:12 +00001281 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001282}
1283
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001284Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001285 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001286 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001287 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001288 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001289 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001290}
1291
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001292static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1293 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001294 // undef % X -> undef (the undef could be a snan).
1295 if (match(Op0, m_Undef()))
1296 return Op0;
1297
1298 // X % undef -> undef
1299 if (match(Op1, m_Undef()))
1300 return Op1;
1301
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001302 // 0 % X -> 0
1303 // Requires that NaNs are off (X could be zero) and signed zeroes are
1304 // ignored (X could be positive or negative, so the output sign is unknown).
1305 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1306 return Op0;
1307
Craig Topper9f008862014-04-15 04:59:12 +00001308 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001309}
1310
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001311Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001312 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001313 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001314 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001315 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001316 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001317 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001318}
1319
Sanjay Patel472cc782016-01-11 22:14:42 +00001320/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001321static bool isUndefShift(Value *Amount) {
1322 Constant *C = dyn_cast<Constant>(Amount);
1323 if (!C)
1324 return false;
1325
1326 // X shift by undef -> undef because it may shift by the bitwidth.
1327 if (isa<UndefValue>(C))
1328 return true;
1329
1330 // Shifting by the bitwidth or more is undefined.
1331 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1332 if (CI->getValue().getLimitedValue() >=
1333 CI->getType()->getScalarSizeInBits())
1334 return true;
1335
1336 // If all lanes of a vector shift are undefined the whole shift is.
1337 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1338 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1339 if (!isUndefShift(C->getAggregateElement(I)))
1340 return false;
1341 return true;
1342 }
1343
1344 return false;
1345}
1346
Sanjay Patel472cc782016-01-11 22:14:42 +00001347/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1348/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001349static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001350 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001351 if (Constant *C0 = dyn_cast<Constant>(Op0))
1352 if (Constant *C1 = dyn_cast<Constant>(Op1))
1353 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001354
Duncan Sands571fd9a2011-01-14 14:44:12 +00001355 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001356 if (match(Op0, m_Zero()))
1357 return Op0;
1358
Duncan Sands571fd9a2011-01-14 14:44:12 +00001359 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001360 if (match(Op1, m_Zero()))
1361 return Op0;
1362
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001363 // Fold undefined shifts.
1364 if (isUndefShift(Op1))
1365 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001366
Duncan Sands571fd9a2011-01-14 14:44:12 +00001367 // If the operation is with the result of a select instruction, check whether
1368 // operating on either branch of the select always yields the same value.
1369 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001370 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001371 return V;
1372
1373 // If the operation is with the result of a phi instruction, check whether
1374 // operating on all incoming values of the phi always yields the same value.
1375 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001376 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001377 return V;
1378
Sanjay Patel6786bc52016-05-10 20:46:54 +00001379 // If any bits in the shift amount make that value greater than or equal to
1380 // the number of bits in the type, the shift is undefined.
1381 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1382 APInt KnownZero(BitWidth, 0);
1383 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001384 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001385 if (KnownOne.getLimitedValue() >= BitWidth)
1386 return UndefValue::get(Op0->getType());
1387
1388 // If all valid bits in the shift amount are known zero, the first operand is
1389 // unchanged.
1390 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1391 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1392 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1393 return Op0;
1394
Craig Topper9f008862014-04-15 04:59:12 +00001395 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001396}
1397
David Majnemerbf7550e2014-11-05 00:59:59 +00001398/// \brief Given operands for an Shl, LShr or AShr, see if we can
1399/// fold the result. If not, this returns null.
1400static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1401 bool isExact, const Query &Q,
1402 unsigned MaxRecurse) {
1403 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1404 return V;
1405
1406 // X >> X -> 0
1407 if (Op0 == Op1)
1408 return Constant::getNullValue(Op0->getType());
1409
David Majnemer65c52ae2014-12-17 01:54:33 +00001410 // undef >> X -> 0
1411 // undef >> X -> undef (if it's exact)
1412 if (match(Op0, m_Undef()))
1413 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1414
David Majnemerbf7550e2014-11-05 00:59:59 +00001415 // The low bit cannot be shifted out of an exact shift if it is set.
1416 if (isExact) {
1417 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1418 APInt Op0KnownZero(BitWidth, 0);
1419 APInt Op0KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001420 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1421 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001422 if (Op0KnownOne[0])
1423 return Op0;
1424 }
1425
1426 return nullptr;
1427}
1428
Sanjay Patel472cc782016-01-11 22:14:42 +00001429/// Given operands for an Shl, see if we can fold the result.
1430/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001431static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001432 const Query &Q, unsigned MaxRecurse) {
1433 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001434 return V;
1435
1436 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001437 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001438 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001439 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001440
Chris Lattner9e4aa022011-02-09 17:15:04 +00001441 // (X >> A) << A -> X
1442 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001443 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001444 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001445 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001446}
1447
Chris Lattner9e4aa022011-02-09 17:15:04 +00001448Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001449 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001450 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001451 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001452 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001453 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001454}
1455
Sanjay Patel472cc782016-01-11 22:14:42 +00001456/// Given operands for an LShr, see if we can fold the result.
1457/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001458static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001459 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001460 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1461 MaxRecurse))
1462 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001463
Chris Lattner9e4aa022011-02-09 17:15:04 +00001464 // (X << A) >> A -> X
1465 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001466 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001467 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001468
Craig Topper9f008862014-04-15 04:59:12 +00001469 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001470}
1471
Chris Lattner9e4aa022011-02-09 17:15:04 +00001472Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001473 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001474 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001475 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001476 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001477 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001478 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001479}
1480
Sanjay Patel472cc782016-01-11 22:14:42 +00001481/// Given operands for an AShr, see if we can fold the result.
1482/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001483static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001484 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001485 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1486 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001487 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001488
1489 // all ones >>a X -> all ones
1490 if (match(Op0, m_AllOnes()))
1491 return Op0;
1492
Chris Lattner9e4aa022011-02-09 17:15:04 +00001493 // (X << A) >> A -> X
1494 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001495 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001496 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001497
Suyog Sarda68862412014-07-17 06:28:15 +00001498 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001499 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001500 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1501 return Op0;
1502
Craig Topper9f008862014-04-15 04:59:12 +00001503 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001504}
1505
Chris Lattner9e4aa022011-02-09 17:15:04 +00001506Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001507 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001508 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001509 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001510 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001511 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001512 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001513}
1514
David Majnemer1af36e52014-12-06 10:51:40 +00001515static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1516 ICmpInst *UnsignedICmp, bool IsAnd) {
1517 Value *X, *Y;
1518
1519 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001520 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1521 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001522 return nullptr;
1523
1524 ICmpInst::Predicate UnsignedPred;
1525 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1526 ICmpInst::isUnsigned(UnsignedPred))
1527 ;
1528 else if (match(UnsignedICmp,
1529 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1530 ICmpInst::isUnsigned(UnsignedPred))
1531 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1532 else
1533 return nullptr;
1534
1535 // X < Y && Y != 0 --> X < Y
1536 // X < Y || Y != 0 --> Y != 0
1537 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1538 return IsAnd ? UnsignedICmp : ZeroICmp;
1539
1540 // X >= Y || Y != 0 --> true
1541 // X >= Y || Y == 0 --> X >= Y
1542 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1543 if (EqPred == ICmpInst::ICMP_NE)
1544 return getTrue(UnsignedICmp->getType());
1545 return UnsignedICmp;
1546 }
1547
David Majnemerd5b3aa42014-12-08 18:30:43 +00001548 // X < Y && Y == 0 --> false
1549 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1550 IsAnd)
1551 return getFalse(UnsignedICmp->getType());
1552
David Majnemer1af36e52014-12-06 10:51:40 +00001553 return nullptr;
1554}
1555
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001556/// Commuted variants are assumed to be handled by calling this function again
1557/// with the parameters swapped.
1558static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1559 ICmpInst::Predicate Pred0, Pred1;
1560 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001561 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1562 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001563 return nullptr;
1564
1565 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1566 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1567 // can eliminate Op1 from this 'and'.
1568 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1569 return Op0;
1570
1571 // Check for any combination of predicates that are guaranteed to be disjoint.
1572 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1573 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1574 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1575 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1576 return getFalse(Op0->getType());
1577
1578 return nullptr;
1579}
1580
1581/// Commuted variants are assumed to be handled by calling this function again
1582/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001583static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001584 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1585 return X;
1586
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001587 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1588 return X;
1589
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001590 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001591 Type *ITy = Op0->getType();
1592 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001593 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001594 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001595 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1596 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1597 // Make a constant range that's the intersection of the two icmp ranges.
1598 // If the intersection is empty, we know that the result is false.
1599 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1600 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1601 if (Range0.intersectWith(Range1).isEmptySet())
1602 return getFalse(ITy);
1603 }
1604
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001605 // (icmp (add V, C0), C1) & (icmp V, C0)
1606 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001607 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001608
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001609 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001610 return nullptr;
1611
David Majnemera315bd82014-09-15 08:15:28 +00001612 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001613 if (AddInst->getOperand(1) != Op1->getOperand(1))
1614 return nullptr;
1615
David Majnemera315bd82014-09-15 08:15:28 +00001616 bool isNSW = AddInst->hasNoSignedWrap();
1617 bool isNUW = AddInst->hasNoUnsignedWrap();
1618
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001619 const APInt Delta = *C1 - *C0;
1620 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001621 if (Delta == 2) {
1622 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1623 return getFalse(ITy);
1624 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1625 return getFalse(ITy);
1626 }
1627 if (Delta == 1) {
1628 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1629 return getFalse(ITy);
1630 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1631 return getFalse(ITy);
1632 }
1633 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001634 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001635 if (Delta == 2)
1636 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1637 return getFalse(ITy);
1638 if (Delta == 1)
1639 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1640 return getFalse(ITy);
1641 }
1642
1643 return nullptr;
1644}
1645
Sanjay Patel472cc782016-01-11 22:14:42 +00001646/// Given operands for an And, see if we can fold the result.
1647/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001648static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001649 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001650 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001651 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1652 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001653
Chris Lattnera71e9d62009-11-10 00:55:12 +00001654 // Canonicalize the constant to the RHS.
1655 std::swap(Op0, Op1);
1656 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001657
Chris Lattnera71e9d62009-11-10 00:55:12 +00001658 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001659 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001660 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001661
Chris Lattnera71e9d62009-11-10 00:55:12 +00001662 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001663 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001664 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001665
Duncan Sandsc89ac072010-11-17 18:52:15 +00001666 // X & 0 = 0
1667 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001668 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001669
Duncan Sandsc89ac072010-11-17 18:52:15 +00001670 // X & -1 = X
1671 if (match(Op1, m_AllOnes()))
1672 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001673
Chris Lattnera71e9d62009-11-10 00:55:12 +00001674 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001675 if (match(Op0, m_Not(m_Specific(Op1))) ||
1676 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001677 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001678
Chris Lattnera71e9d62009-11-10 00:55:12 +00001679 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001680 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001681 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001682 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001683 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001684
Chris Lattnera71e9d62009-11-10 00:55:12 +00001685 // A & (A | ?) = A
1686 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001687 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001688 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001689
Duncan Sandsba286d72011-10-26 20:55:21 +00001690 // A & (-A) = A if A is a power of two or zero.
1691 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1692 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001693 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1694 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001695 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001696 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1697 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001698 return Op1;
1699 }
1700
David Majnemera315bd82014-09-15 08:15:28 +00001701 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1702 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1703 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1704 return V;
1705 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1706 return V;
1707 }
1708 }
1709
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001710 // The compares may be hidden behind casts. Look through those and try the
1711 // same folds as above.
1712 auto *Cast0 = dyn_cast<CastInst>(Op0);
1713 auto *Cast1 = dyn_cast<CastInst>(Op1);
1714 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1715 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1716 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1717 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1718 if (Cmp0 && Cmp1) {
1719 Instruction::CastOps CastOpc = Cast0->getOpcode();
1720 Type *ResultType = Cast0->getType();
1721 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1722 return ConstantExpr::getCast(CastOpc, V, ResultType);
1723 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1724 return ConstantExpr::getCast(CastOpc, V, ResultType);
1725 }
1726 }
1727
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001728 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001729 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1730 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001731 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001732
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001733 // And distributes over Or. Try some generic simplifications based on this.
1734 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001735 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001736 return V;
1737
1738 // And distributes over Xor. Try some generic simplifications based on this.
1739 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001740 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001741 return V;
1742
Duncan Sandsb0579e92010-11-10 13:00:08 +00001743 // If the operation is with the result of a select instruction, check whether
1744 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001745 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001746 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1747 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001748 return V;
1749
1750 // If the operation is with the result of a phi instruction, check whether
1751 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001752 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001753 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001754 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001755 return V;
1756
Craig Topper9f008862014-04-15 04:59:12 +00001757 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001758}
1759
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001760Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001761 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001762 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001763 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001764 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001765 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001766}
1767
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001768/// Commuted variants are assumed to be handled by calling this function again
1769/// with the parameters swapped.
1770static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1771 ICmpInst::Predicate Pred0, Pred1;
1772 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001773 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1774 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001775 return nullptr;
1776
1777 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1778 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1779 // can eliminate Op0 from this 'or'.
1780 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1781 return Op1;
1782
1783 // Check for any combination of predicates that cover the entire range of
1784 // possibilities.
1785 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1786 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1787 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1788 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1789 return getTrue(Op0->getType());
1790
1791 return nullptr;
1792}
1793
1794/// Commuted variants are assumed to be handled by calling this function again
1795/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001796static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001797 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1798 return X;
1799
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001800 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1801 return X;
1802
Sanjay Patel220a8732016-09-28 14:27:21 +00001803 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001804 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001805 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001806 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001807 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001808 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001809
Sanjay Patel220a8732016-09-28 14:27:21 +00001810 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1811 return nullptr;
1812
1813 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1814 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001815 return nullptr;
1816
1817 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001818 bool isNSW = AddInst->hasNoSignedWrap();
1819 bool isNUW = AddInst->hasNoUnsignedWrap();
1820
Sanjay Patel220a8732016-09-28 14:27:21 +00001821 const APInt Delta = *C1 - *C0;
1822 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001823 if (Delta == 2) {
1824 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1825 return getTrue(ITy);
1826 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1827 return getTrue(ITy);
1828 }
1829 if (Delta == 1) {
1830 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1831 return getTrue(ITy);
1832 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1833 return getTrue(ITy);
1834 }
1835 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001836 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001837 if (Delta == 2)
1838 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1839 return getTrue(ITy);
1840 if (Delta == 1)
1841 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1842 return getTrue(ITy);
1843 }
1844
1845 return nullptr;
1846}
1847
Sanjay Patel472cc782016-01-11 22:14:42 +00001848/// Given operands for an Or, see if we can fold the result.
1849/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001850static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1851 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001852 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001853 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1854 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001855
Chris Lattnera71e9d62009-11-10 00:55:12 +00001856 // Canonicalize the constant to the RHS.
1857 std::swap(Op0, Op1);
1858 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001859
Chris Lattnera71e9d62009-11-10 00:55:12 +00001860 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001861 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001862 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001863
Chris Lattnera71e9d62009-11-10 00:55:12 +00001864 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001865 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001866 return Op0;
1867
Duncan Sandsc89ac072010-11-17 18:52:15 +00001868 // X | 0 = X
1869 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001870 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001871
Duncan Sandsc89ac072010-11-17 18:52:15 +00001872 // X | -1 = -1
1873 if (match(Op1, m_AllOnes()))
1874 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001875
Chris Lattnera71e9d62009-11-10 00:55:12 +00001876 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001877 if (match(Op0, m_Not(m_Specific(Op1))) ||
1878 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001879 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001880
Chris Lattnera71e9d62009-11-10 00:55:12 +00001881 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001882 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001883 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001884 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001885 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001886
Chris Lattnera71e9d62009-11-10 00:55:12 +00001887 // A | (A & ?) = A
1888 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001889 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001890 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001891
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001892 // ~(A & ?) | A = -1
1893 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1894 (A == Op1 || B == Op1))
1895 return Constant::getAllOnesValue(Op1->getType());
1896
1897 // A | ~(A & ?) = -1
1898 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1899 (A == Op0 || B == Op0))
1900 return Constant::getAllOnesValue(Op0->getType());
1901
David Majnemera315bd82014-09-15 08:15:28 +00001902 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1903 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1904 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1905 return V;
1906 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1907 return V;
1908 }
1909 }
1910
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001911 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001912 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1913 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001914 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001915
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001916 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001917 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1918 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001919 return V;
1920
Duncan Sandsb0579e92010-11-10 13:00:08 +00001921 // If the operation is with the result of a select instruction, check whether
1922 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001923 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001924 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001925 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001926 return V;
1927
Nick Lewycky8561a492014-06-19 03:51:46 +00001928 // (A & C)|(B & D)
1929 Value *C = nullptr, *D = nullptr;
1930 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1931 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1932 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1933 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1934 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1935 // (A & C1)|(B & C2)
1936 // If we have: ((V + N) & C1) | (V & C2)
1937 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1938 // replace with V+N.
1939 Value *V1, *V2;
1940 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1941 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1942 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001943 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001944 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001945 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001946 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001947 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001948 return A;
1949 }
1950 // Or commutes, try both ways.
1951 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1952 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1953 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001954 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001955 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001956 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001957 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001958 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001959 return B;
1960 }
1961 }
1962 }
1963
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001964 // If the operation is with the result of a phi instruction, check whether
1965 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001966 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001967 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001968 return V;
1969
Craig Topper9f008862014-04-15 04:59:12 +00001970 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001971}
1972
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001973Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001974 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001975 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001976 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001977 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001978 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001979}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001980
Sanjay Patel472cc782016-01-11 22:14:42 +00001981/// Given operands for a Xor, see if we can fold the result.
1982/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001983static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1984 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001985 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001986 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1987 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001988
1989 // Canonicalize the constant to the RHS.
1990 std::swap(Op0, Op1);
1991 }
1992
1993 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001994 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001995 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001996
1997 // A ^ 0 = A
1998 if (match(Op1, m_Zero()))
1999 return Op0;
2000
Eli Friedmanad3cfe72011-08-17 19:31:49 +00002001 // A ^ A = 0
2002 if (Op0 == Op1)
2003 return Constant::getNullValue(Op0->getType());
2004
Duncan Sandsc89ac072010-11-17 18:52:15 +00002005 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00002006 if (match(Op0, m_Not(m_Specific(Op1))) ||
2007 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00002008 return Constant::getAllOnesValue(Op0->getType());
2009
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002010 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002011 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2012 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002013 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002014
Duncan Sandsb238de02010-11-19 09:20:39 +00002015 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2016 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2017 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2018 // only if B and C are equal. If B and C are equal then (since we assume
2019 // that operands have already been simplified) "select(cond, B, C)" should
2020 // have been simplified to the common value of B and C already. Analysing
2021 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2022 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002023
Craig Topper9f008862014-04-15 04:59:12 +00002024 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002025}
2026
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002027Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002028 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002029 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00002030 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002031 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00002032 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00002033}
2034
Chris Lattner229907c2011-07-18 04:54:35 +00002035static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002036 return CmpInst::makeCmpResultType(Op->getType());
2037}
2038
Sanjay Patel472cc782016-01-11 22:14:42 +00002039/// Rummage around inside V looking for something equivalent to the comparison
2040/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2041/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002042static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2043 Value *LHS, Value *RHS) {
2044 SelectInst *SI = dyn_cast<SelectInst>(V);
2045 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002046 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002047 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2048 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002049 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002050 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2051 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2052 return Cmp;
2053 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2054 LHS == CmpRHS && RHS == CmpLHS)
2055 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002056 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002057}
2058
Dan Gohman9631d902013-02-01 00:49:06 +00002059// A significant optimization not implemented here is assuming that alloca
2060// addresses are not equal to incoming argument values. They don't *alias*,
2061// as we say, but that doesn't mean they aren't equal, so we take a
2062// conservative approach.
2063//
2064// This is inspired in part by C++11 5.10p1:
2065// "Two pointers of the same type compare equal if and only if they are both
2066// null, both point to the same function, or both represent the same
2067// address."
2068//
2069// This is pretty permissive.
2070//
2071// It's also partly due to C11 6.5.9p6:
2072// "Two pointers compare equal if and only if both are null pointers, both are
2073// pointers to the same object (including a pointer to an object and a
2074// subobject at its beginning) or function, both are pointers to one past the
2075// last element of the same array object, or one is a pointer to one past the
2076// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002077// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002078// object in the address space.)
2079//
2080// C11's version is more restrictive, however there's no reason why an argument
2081// couldn't be a one-past-the-end value for a stack object in the caller and be
2082// equal to the beginning of a stack object in the callee.
2083//
2084// If the C and C++ standards are ever made sufficiently restrictive in this
2085// area, it may be possible to update LLVM's semantics accordingly and reinstate
2086// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002087static Constant *
2088computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2089 const DominatorTree *DT, CmpInst::Predicate Pred,
2090 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002091 // First, skip past any trivial no-ops.
2092 LHS = LHS->stripPointerCasts();
2093 RHS = RHS->stripPointerCasts();
2094
2095 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002096 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002097 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2098 return ConstantInt::get(GetCompareTy(LHS),
2099 !CmpInst::isTrueWhenEqual(Pred));
2100
Chandler Carruth8059c842012-03-25 21:28:14 +00002101 // We can only fold certain predicates on pointer comparisons.
2102 switch (Pred) {
2103 default:
Craig Topper9f008862014-04-15 04:59:12 +00002104 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002105
2106 // Equality comaprisons are easy to fold.
2107 case CmpInst::ICMP_EQ:
2108 case CmpInst::ICMP_NE:
2109 break;
2110
2111 // We can only handle unsigned relational comparisons because 'inbounds' on
2112 // a GEP only protects against unsigned wrapping.
2113 case CmpInst::ICMP_UGT:
2114 case CmpInst::ICMP_UGE:
2115 case CmpInst::ICMP_ULT:
2116 case CmpInst::ICMP_ULE:
2117 // However, we have to switch them to their signed variants to handle
2118 // negative indices from the base pointer.
2119 Pred = ICmpInst::getSignedPredicate(Pred);
2120 break;
2121 }
2122
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002123 // Strip off any constant offsets so that we can reason about them.
2124 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2125 // here and compare base addresses like AliasAnalysis does, however there are
2126 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2127 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2128 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002129 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2130 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002131
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002132 // If LHS and RHS are related via constant offsets to the same base
2133 // value, we can replace it with an icmp which just compares the offsets.
2134 if (LHS == RHS)
2135 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002136
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002137 // Various optimizations for (in)equality comparisons.
2138 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2139 // Different non-empty allocations that exist at the same time have
2140 // different addresses (if the program can tell). Global variables always
2141 // exist, so they always exist during the lifetime of each other and all
2142 // allocas. Two different allocas usually have different addresses...
2143 //
2144 // However, if there's an @llvm.stackrestore dynamically in between two
2145 // allocas, they may have the same address. It's tempting to reduce the
2146 // scope of the problem by only looking at *static* allocas here. That would
2147 // cover the majority of allocas while significantly reducing the likelihood
2148 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2149 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2150 // an entry block. Also, if we have a block that's not attached to a
2151 // function, we can't tell if it's "static" under the current definition.
2152 // Theoretically, this problem could be fixed by creating a new kind of
2153 // instruction kind specifically for static allocas. Such a new instruction
2154 // could be required to be at the top of the entry block, thus preventing it
2155 // from being subject to a @llvm.stackrestore. Instcombine could even
2156 // convert regular allocas into these special allocas. It'd be nifty.
2157 // However, until then, this problem remains open.
2158 //
2159 // So, we'll assume that two non-empty allocas have different addresses
2160 // for now.
2161 //
2162 // With all that, if the offsets are within the bounds of their allocations
2163 // (and not one-past-the-end! so we can't use inbounds!), and their
2164 // allocations aren't the same, the pointers are not equal.
2165 //
2166 // Note that it's not necessary to check for LHS being a global variable
2167 // address, due to canonicalization and constant folding.
2168 if (isa<AllocaInst>(LHS) &&
2169 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002170 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2171 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002172 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002173 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002174 getObjectSize(LHS, LHSSize, DL, TLI) &&
2175 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002176 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2177 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002178 if (!LHSOffsetValue.isNegative() &&
2179 !RHSOffsetValue.isNegative() &&
2180 LHSOffsetValue.ult(LHSSize) &&
2181 RHSOffsetValue.ult(RHSSize)) {
2182 return ConstantInt::get(GetCompareTy(LHS),
2183 !CmpInst::isTrueWhenEqual(Pred));
2184 }
2185 }
2186
2187 // Repeat the above check but this time without depending on DataLayout
2188 // or being able to compute a precise size.
2189 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2190 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2191 LHSOffset->isNullValue() &&
2192 RHSOffset->isNullValue())
2193 return ConstantInt::get(GetCompareTy(LHS),
2194 !CmpInst::isTrueWhenEqual(Pred));
2195 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002196
2197 // Even if an non-inbounds GEP occurs along the path we can still optimize
2198 // equality comparisons concerning the result. We avoid walking the whole
2199 // chain again by starting where the last calls to
2200 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002201 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2202 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002203 if (LHS == RHS)
2204 return ConstantExpr::getICmp(Pred,
2205 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2206 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002207
2208 // If one side of the equality comparison must come from a noalias call
2209 // (meaning a system memory allocation function), and the other side must
2210 // come from a pointer that cannot overlap with dynamically-allocated
2211 // memory within the lifetime of the current function (allocas, byval
2212 // arguments, globals), then determine the comparison result here.
2213 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2214 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2215 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2216
2217 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002218 auto IsNAC = [](ArrayRef<Value *> Objects) {
2219 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002220 };
2221
2222 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002223 // noalias calls. For allocas, we consider only static ones (dynamic
2224 // allocas might be transformed into calls to malloc not simultaneously
2225 // live with the compared-to allocation). For globals, we exclude symbols
2226 // that might be resolve lazily to symbols in another dynamically-loaded
2227 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002228 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2229 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002230 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2231 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2232 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2233 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002234 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002235 !GV->isThreadLocal();
2236 if (const Argument *A = dyn_cast<Argument>(V))
2237 return A->hasByValAttr();
2238 return false;
2239 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002240 };
2241
2242 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2243 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2244 return ConstantInt::get(GetCompareTy(LHS),
2245 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002246
2247 // Fold comparisons for non-escaping pointer even if the allocation call
2248 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2249 // dynamic allocation call could be either of the operands.
2250 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002251 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002252 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002253 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002254 MI = RHS;
2255 // FIXME: We should also fold the compare when the pointer escapes, but the
2256 // compare dominates the pointer escape
2257 if (MI && !PointerMayBeCaptured(MI, true, true))
2258 return ConstantInt::get(GetCompareTy(LHS),
2259 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002260 }
2261
2262 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002263 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002264}
Chris Lattner01990f02012-02-24 19:01:58 +00002265
Sanjay Pateldc65a272016-12-03 17:30:22 +00002266/// Fold an icmp when its operands have i1 scalar type.
2267static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2268 Value *RHS, const Query &Q) {
2269 Type *ITy = GetCompareTy(LHS); // The return type.
2270 Type *OpTy = LHS->getType(); // The operand type.
2271 if (!OpTy->getScalarType()->isIntegerTy(1))
2272 return nullptr;
2273
2274 switch (Pred) {
2275 default:
2276 break;
2277 case ICmpInst::ICMP_EQ:
2278 // X == 1 -> X
2279 if (match(RHS, m_One()))
2280 return LHS;
2281 break;
2282 case ICmpInst::ICMP_NE:
2283 // X != 0 -> X
2284 if (match(RHS, m_Zero()))
2285 return LHS;
2286 break;
2287 case ICmpInst::ICMP_UGT:
2288 // X >u 0 -> X
2289 if (match(RHS, m_Zero()))
2290 return LHS;
2291 break;
2292 case ICmpInst::ICMP_UGE:
2293 // X >=u 1 -> X
2294 if (match(RHS, m_One()))
2295 return LHS;
2296 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2297 return getTrue(ITy);
2298 break;
2299 case ICmpInst::ICMP_SGE:
2300 /// For signed comparison, the values for an i1 are 0 and -1
2301 /// respectively. This maps into a truth table of:
2302 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2303 /// 0 | 0 | 1 (0 >= 0) | 1
2304 /// 0 | 1 | 1 (0 >= -1) | 1
2305 /// 1 | 0 | 0 (-1 >= 0) | 0
2306 /// 1 | 1 | 1 (-1 >= -1) | 1
2307 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2308 return getTrue(ITy);
2309 break;
2310 case ICmpInst::ICMP_SLT:
2311 // X <s 0 -> X
2312 if (match(RHS, m_Zero()))
2313 return LHS;
2314 break;
2315 case ICmpInst::ICMP_SLE:
2316 // X <=s -1 -> X
2317 if (match(RHS, m_One()))
2318 return LHS;
2319 break;
2320 case ICmpInst::ICMP_ULE:
2321 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2322 return getTrue(ITy);
2323 break;
2324 }
2325
2326 return nullptr;
2327}
2328
2329/// Try hard to fold icmp with zero RHS because this is a common case.
2330static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2331 Value *RHS, const Query &Q) {
2332 if (!match(RHS, m_Zero()))
2333 return nullptr;
2334
2335 Type *ITy = GetCompareTy(LHS); // The return type.
2336 bool LHSKnownNonNegative, LHSKnownNegative;
2337 switch (Pred) {
2338 default:
2339 llvm_unreachable("Unknown ICmp predicate!");
2340 case ICmpInst::ICMP_ULT:
2341 return getFalse(ITy);
2342 case ICmpInst::ICMP_UGE:
2343 return getTrue(ITy);
2344 case ICmpInst::ICMP_EQ:
2345 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002346 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002347 return getFalse(ITy);
2348 break;
2349 case ICmpInst::ICMP_NE:
2350 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002351 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002352 return getTrue(ITy);
2353 break;
2354 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002355 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2356 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002357 if (LHSKnownNegative)
2358 return getTrue(ITy);
2359 if (LHSKnownNonNegative)
2360 return getFalse(ITy);
2361 break;
2362 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002363 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2364 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002365 if (LHSKnownNegative)
2366 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002367 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002368 return getFalse(ITy);
2369 break;
2370 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002371 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2372 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002373 if (LHSKnownNegative)
2374 return getFalse(ITy);
2375 if (LHSKnownNonNegative)
2376 return getTrue(ITy);
2377 break;
2378 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002379 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2380 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002381 if (LHSKnownNegative)
2382 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002383 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002384 return getTrue(ITy);
2385 break;
2386 }
2387
2388 return nullptr;
2389}
2390
Sanjay Patelbe332132017-01-23 18:22:26 +00002391/// Many binary operators with a constant operand have an easy-to-compute
2392/// range of outputs. This can be used to fold a comparison to always true or
2393/// always false.
2394static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2395 unsigned Width = Lower.getBitWidth();
2396 const APInt *C;
2397 switch (BO.getOpcode()) {
2398 case Instruction::Add:
Sanjay Patel56227252017-01-24 17:03:24 +00002399 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2400 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2401 if (BO.hasNoUnsignedWrap()) {
2402 // 'add nuw x, C' produces [C, UINT_MAX].
2403 Lower = *C;
2404 } else if (BO.hasNoSignedWrap()) {
2405 if (C->isNegative()) {
2406 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2407 Lower = APInt::getSignedMinValue(Width);
2408 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2409 } else {
2410 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2411 Lower = APInt::getSignedMinValue(Width) + *C;
2412 Upper = APInt::getSignedMaxValue(Width) + 1;
2413 }
2414 }
2415 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002416 break;
2417
2418 case Instruction::And:
2419 if (match(BO.getOperand(1), m_APInt(C)))
2420 // 'and x, C' produces [0, C].
2421 Upper = *C + 1;
2422 break;
2423
2424 case Instruction::Or:
2425 if (match(BO.getOperand(1), m_APInt(C)))
2426 // 'or x, C' produces [C, UINT_MAX].
2427 Lower = *C;
2428 break;
2429
2430 case Instruction::AShr:
2431 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2432 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2433 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2434 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2435 } else if (match(BO.getOperand(0), m_APInt(C))) {
2436 unsigned ShiftAmount = Width - 1;
2437 if (*C != 0 && BO.isExact())
2438 ShiftAmount = C->countTrailingZeros();
2439 if (C->isNegative()) {
2440 // 'ashr C, x' produces [C, C >> (Width-1)]
2441 Lower = *C;
2442 Upper = C->ashr(ShiftAmount) + 1;
2443 } else {
2444 // 'ashr C, x' produces [C >> (Width-1), C]
2445 Lower = C->ashr(ShiftAmount);
2446 Upper = *C + 1;
2447 }
2448 }
2449 break;
2450
2451 case Instruction::LShr:
2452 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2453 // 'lshr x, C' produces [0, UINT_MAX >> C].
2454 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2455 } else if (match(BO.getOperand(0), m_APInt(C))) {
2456 // 'lshr C, x' produces [C >> (Width-1), C].
2457 unsigned ShiftAmount = Width - 1;
2458 if (*C != 0 && BO.isExact())
2459 ShiftAmount = C->countTrailingZeros();
2460 Lower = C->lshr(ShiftAmount);
2461 Upper = *C + 1;
2462 }
2463 break;
2464
2465 case Instruction::Shl:
2466 if (match(BO.getOperand(0), m_APInt(C))) {
2467 if (BO.hasNoUnsignedWrap()) {
2468 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2469 Lower = *C;
2470 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2471 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2472 if (C->isNegative()) {
2473 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2474 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2475 Lower = C->shl(ShiftAmount);
2476 Upper = *C + 1;
2477 } else {
2478 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2479 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2480 Lower = *C;
2481 Upper = C->shl(ShiftAmount) + 1;
2482 }
2483 }
2484 }
2485 break;
2486
2487 case Instruction::SDiv:
2488 if (match(BO.getOperand(1), m_APInt(C))) {
2489 APInt IntMin = APInt::getSignedMinValue(Width);
2490 APInt IntMax = APInt::getSignedMaxValue(Width);
2491 if (C->isAllOnesValue()) {
2492 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2493 // where C != -1 and C != 0 and C != 1
2494 Lower = IntMin + 1;
2495 Upper = IntMax + 1;
2496 } else if (C->countLeadingZeros() < Width - 1) {
2497 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2498 // where C != -1 and C != 0 and C != 1
2499 Lower = IntMin.sdiv(*C);
2500 Upper = IntMax.sdiv(*C);
2501 if (Lower.sgt(Upper))
2502 std::swap(Lower, Upper);
2503 Upper = Upper + 1;
2504 assert(Upper != Lower && "Upper part of range has wrapped!");
2505 }
2506 } else if (match(BO.getOperand(0), m_APInt(C))) {
2507 if (C->isMinSignedValue()) {
2508 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2509 Lower = *C;
2510 Upper = Lower.lshr(1) + 1;
2511 } else {
2512 // 'sdiv C, x' produces [-|C|, |C|].
2513 Upper = C->abs() + 1;
2514 Lower = (-Upper) + 1;
2515 }
2516 }
2517 break;
2518
2519 case Instruction::UDiv:
2520 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2521 // 'udiv x, C' produces [0, UINT_MAX / C].
2522 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2523 } else if (match(BO.getOperand(0), m_APInt(C))) {
2524 // 'udiv C, x' produces [0, C].
2525 Upper = *C + 1;
2526 }
2527 break;
2528
2529 case Instruction::SRem:
2530 if (match(BO.getOperand(1), m_APInt(C))) {
2531 // 'srem x, C' produces (-|C|, |C|).
2532 Upper = C->abs();
2533 Lower = (-Upper) + 1;
2534 }
2535 break;
2536
2537 case Instruction::URem:
2538 if (match(BO.getOperand(1), m_APInt(C)))
2539 // 'urem x, C' produces [0, C).
2540 Upper = *C;
2541 break;
2542
2543 default:
2544 break;
2545 }
2546}
2547
Sanjay Patel67bde282016-08-22 23:12:02 +00002548static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2549 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002550 const APInt *C;
2551 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002552 return nullptr;
2553
2554 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002555 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002556 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002557 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002558 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002559 return ConstantInt::getTrue(GetCompareTy(RHS));
2560
Sanjay Patelbe332132017-01-23 18:22:26 +00002561 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002562 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002563 APInt Lower = APInt(Width, 0);
2564 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002565 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2566 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002567
2568 ConstantRange LHS_CR =
2569 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2570
2571 if (auto *I = dyn_cast<Instruction>(LHS))
2572 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2573 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2574
2575 if (!LHS_CR.isFullSet()) {
2576 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002577 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002578 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002579 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002580 }
2581
2582 return nullptr;
2583}
2584
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002585static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2586 Value *RHS, const Query &Q,
2587 unsigned MaxRecurse) {
2588 Type *ITy = GetCompareTy(LHS); // The return type.
2589
2590 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2591 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2592 if (MaxRecurse && (LBO || RBO)) {
2593 // Analyze the case when either LHS or RHS is an add instruction.
2594 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2595 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2596 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2597 if (LBO && LBO->getOpcode() == Instruction::Add) {
2598 A = LBO->getOperand(0);
2599 B = LBO->getOperand(1);
2600 NoLHSWrapProblem =
2601 ICmpInst::isEquality(Pred) ||
2602 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2603 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2604 }
2605 if (RBO && RBO->getOpcode() == Instruction::Add) {
2606 C = RBO->getOperand(0);
2607 D = RBO->getOperand(1);
2608 NoRHSWrapProblem =
2609 ICmpInst::isEquality(Pred) ||
2610 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2611 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2612 }
2613
2614 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2615 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2616 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2617 Constant::getNullValue(RHS->getType()), Q,
2618 MaxRecurse - 1))
2619 return V;
2620
2621 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2622 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2623 if (Value *V =
2624 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2625 C == LHS ? D : C, Q, MaxRecurse - 1))
2626 return V;
2627
2628 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2629 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2630 NoRHSWrapProblem) {
2631 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2632 Value *Y, *Z;
2633 if (A == C) {
2634 // C + B == C + D -> B == D
2635 Y = B;
2636 Z = D;
2637 } else if (A == D) {
2638 // D + B == C + D -> B == C
2639 Y = B;
2640 Z = C;
2641 } else if (B == C) {
2642 // A + C == C + D -> A == D
2643 Y = A;
2644 Z = D;
2645 } else {
2646 assert(B == D);
2647 // A + D == C + D -> A == C
2648 Y = A;
2649 Z = C;
2650 }
2651 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2652 return V;
2653 }
2654 }
2655
2656 {
2657 Value *Y = nullptr;
2658 // icmp pred (or X, Y), X
2659 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2660 if (Pred == ICmpInst::ICMP_ULT)
2661 return getFalse(ITy);
2662 if (Pred == ICmpInst::ICMP_UGE)
2663 return getTrue(ITy);
2664
2665 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2666 bool RHSKnownNonNegative, RHSKnownNegative;
2667 bool YKnownNonNegative, YKnownNegative;
2668 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002669 Q.AC, Q.CxtI, Q.DT);
2670 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002671 Q.CxtI, Q.DT);
2672 if (RHSKnownNonNegative && YKnownNegative)
2673 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2674 if (RHSKnownNegative || YKnownNonNegative)
2675 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2676 }
2677 }
2678 // icmp pred X, (or X, Y)
2679 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2680 if (Pred == ICmpInst::ICMP_ULE)
2681 return getTrue(ITy);
2682 if (Pred == ICmpInst::ICMP_UGT)
2683 return getFalse(ITy);
2684
2685 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2686 bool LHSKnownNonNegative, LHSKnownNegative;
2687 bool YKnownNonNegative, YKnownNegative;
2688 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002689 Q.AC, Q.CxtI, Q.DT);
2690 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002691 Q.CxtI, Q.DT);
2692 if (LHSKnownNonNegative && YKnownNegative)
2693 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2694 if (LHSKnownNegative || YKnownNonNegative)
2695 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2696 }
2697 }
2698 }
2699
2700 // icmp pred (and X, Y), X
2701 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2702 m_And(m_Specific(RHS), m_Value())))) {
2703 if (Pred == ICmpInst::ICMP_UGT)
2704 return getFalse(ITy);
2705 if (Pred == ICmpInst::ICMP_ULE)
2706 return getTrue(ITy);
2707 }
2708 // icmp pred X, (and X, Y)
2709 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2710 m_And(m_Specific(LHS), m_Value())))) {
2711 if (Pred == ICmpInst::ICMP_UGE)
2712 return getTrue(ITy);
2713 if (Pred == ICmpInst::ICMP_ULT)
2714 return getFalse(ITy);
2715 }
2716
2717 // 0 - (zext X) pred C
2718 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2719 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2720 if (RHSC->getValue().isStrictlyPositive()) {
2721 if (Pred == ICmpInst::ICMP_SLT)
2722 return ConstantInt::getTrue(RHSC->getContext());
2723 if (Pred == ICmpInst::ICMP_SGE)
2724 return ConstantInt::getFalse(RHSC->getContext());
2725 if (Pred == ICmpInst::ICMP_EQ)
2726 return ConstantInt::getFalse(RHSC->getContext());
2727 if (Pred == ICmpInst::ICMP_NE)
2728 return ConstantInt::getTrue(RHSC->getContext());
2729 }
2730 if (RHSC->getValue().isNonNegative()) {
2731 if (Pred == ICmpInst::ICMP_SLE)
2732 return ConstantInt::getTrue(RHSC->getContext());
2733 if (Pred == ICmpInst::ICMP_SGT)
2734 return ConstantInt::getFalse(RHSC->getContext());
2735 }
2736 }
2737 }
2738
2739 // icmp pred (urem X, Y), Y
2740 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2741 bool KnownNonNegative, KnownNegative;
2742 switch (Pred) {
2743 default:
2744 break;
2745 case ICmpInst::ICMP_SGT:
2746 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002747 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2748 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002749 if (!KnownNonNegative)
2750 break;
2751 LLVM_FALLTHROUGH;
2752 case ICmpInst::ICMP_EQ:
2753 case ICmpInst::ICMP_UGT:
2754 case ICmpInst::ICMP_UGE:
2755 return getFalse(ITy);
2756 case ICmpInst::ICMP_SLT:
2757 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002758 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2759 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002760 if (!KnownNonNegative)
2761 break;
2762 LLVM_FALLTHROUGH;
2763 case ICmpInst::ICMP_NE:
2764 case ICmpInst::ICMP_ULT:
2765 case ICmpInst::ICMP_ULE:
2766 return getTrue(ITy);
2767 }
2768 }
2769
2770 // icmp pred X, (urem Y, X)
2771 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2772 bool KnownNonNegative, KnownNegative;
2773 switch (Pred) {
2774 default:
2775 break;
2776 case ICmpInst::ICMP_SGT:
2777 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002778 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2779 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002780 if (!KnownNonNegative)
2781 break;
2782 LLVM_FALLTHROUGH;
2783 case ICmpInst::ICMP_NE:
2784 case ICmpInst::ICMP_UGT:
2785 case ICmpInst::ICMP_UGE:
2786 return getTrue(ITy);
2787 case ICmpInst::ICMP_SLT:
2788 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002789 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2790 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002791 if (!KnownNonNegative)
2792 break;
2793 LLVM_FALLTHROUGH;
2794 case ICmpInst::ICMP_EQ:
2795 case ICmpInst::ICMP_ULT:
2796 case ICmpInst::ICMP_ULE:
2797 return getFalse(ITy);
2798 }
2799 }
2800
2801 // x >> y <=u x
2802 // x udiv y <=u x.
2803 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2804 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2805 // icmp pred (X op Y), X
2806 if (Pred == ICmpInst::ICMP_UGT)
2807 return getFalse(ITy);
2808 if (Pred == ICmpInst::ICMP_ULE)
2809 return getTrue(ITy);
2810 }
2811
2812 // x >=u x >> y
2813 // x >=u x udiv y.
2814 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2815 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2816 // icmp pred X, (X op Y)
2817 if (Pred == ICmpInst::ICMP_ULT)
2818 return getFalse(ITy);
2819 if (Pred == ICmpInst::ICMP_UGE)
2820 return getTrue(ITy);
2821 }
2822
2823 // handle:
2824 // CI2 << X == CI
2825 // CI2 << X != CI
2826 //
2827 // where CI2 is a power of 2 and CI isn't
2828 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2829 const APInt *CI2Val, *CIVal = &CI->getValue();
2830 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2831 CI2Val->isPowerOf2()) {
2832 if (!CIVal->isPowerOf2()) {
2833 // CI2 << X can equal zero in some circumstances,
2834 // this simplification is unsafe if CI is zero.
2835 //
2836 // We know it is safe if:
2837 // - The shift is nsw, we can't shift out the one bit.
2838 // - The shift is nuw, we can't shift out the one bit.
2839 // - CI2 is one
2840 // - CI isn't zero
2841 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2842 *CI2Val == 1 || !CI->isZero()) {
2843 if (Pred == ICmpInst::ICMP_EQ)
2844 return ConstantInt::getFalse(RHS->getContext());
2845 if (Pred == ICmpInst::ICMP_NE)
2846 return ConstantInt::getTrue(RHS->getContext());
2847 }
2848 }
2849 if (CIVal->isSignBit() && *CI2Val == 1) {
2850 if (Pred == ICmpInst::ICMP_UGT)
2851 return ConstantInt::getFalse(RHS->getContext());
2852 if (Pred == ICmpInst::ICMP_ULE)
2853 return ConstantInt::getTrue(RHS->getContext());
2854 }
2855 }
2856 }
2857
2858 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2859 LBO->getOperand(1) == RBO->getOperand(1)) {
2860 switch (LBO->getOpcode()) {
2861 default:
2862 break;
2863 case Instruction::UDiv:
2864 case Instruction::LShr:
2865 if (ICmpInst::isSigned(Pred))
2866 break;
2867 LLVM_FALLTHROUGH;
2868 case Instruction::SDiv:
2869 case Instruction::AShr:
2870 if (!LBO->isExact() || !RBO->isExact())
2871 break;
2872 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2873 RBO->getOperand(0), Q, MaxRecurse - 1))
2874 return V;
2875 break;
2876 case Instruction::Shl: {
2877 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2878 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2879 if (!NUW && !NSW)
2880 break;
2881 if (!NSW && ICmpInst::isSigned(Pred))
2882 break;
2883 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2884 RBO->getOperand(0), Q, MaxRecurse - 1))
2885 return V;
2886 break;
2887 }
2888 }
2889 }
2890 return nullptr;
2891}
2892
Sanjay Patel35289c62016-12-10 17:40:47 +00002893/// Simplify integer comparisons where at least one operand of the compare
2894/// matches an integer min/max idiom.
2895static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2896 Value *RHS, const Query &Q,
2897 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002898 Type *ITy = GetCompareTy(LHS); // The return type.
2899 Value *A, *B;
2900 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2901 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2902
2903 // Signed variants on "max(a,b)>=a -> true".
2904 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2905 if (A != RHS)
2906 std::swap(A, B); // smax(A, B) pred A.
2907 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2908 // We analyze this as smax(A, B) pred A.
2909 P = Pred;
2910 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2911 (A == LHS || B == LHS)) {
2912 if (A != LHS)
2913 std::swap(A, B); // A pred smax(A, B).
2914 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2915 // We analyze this as smax(A, B) swapped-pred A.
2916 P = CmpInst::getSwappedPredicate(Pred);
2917 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2918 (A == RHS || B == RHS)) {
2919 if (A != RHS)
2920 std::swap(A, B); // smin(A, B) pred A.
2921 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2922 // We analyze this as smax(-A, -B) swapped-pred -A.
2923 // Note that we do not need to actually form -A or -B thanks to EqP.
2924 P = CmpInst::getSwappedPredicate(Pred);
2925 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2926 (A == LHS || B == LHS)) {
2927 if (A != LHS)
2928 std::swap(A, B); // A pred smin(A, B).
2929 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2930 // We analyze this as smax(-A, -B) pred -A.
2931 // Note that we do not need to actually form -A or -B thanks to EqP.
2932 P = Pred;
2933 }
2934 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2935 // Cases correspond to "max(A, B) p A".
2936 switch (P) {
2937 default:
2938 break;
2939 case CmpInst::ICMP_EQ:
2940 case CmpInst::ICMP_SLE:
2941 // Equivalent to "A EqP B". This may be the same as the condition tested
2942 // in the max/min; if so, we can just return that.
2943 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2944 return V;
2945 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2946 return V;
2947 // Otherwise, see if "A EqP B" simplifies.
2948 if (MaxRecurse)
2949 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2950 return V;
2951 break;
2952 case CmpInst::ICMP_NE:
2953 case CmpInst::ICMP_SGT: {
2954 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2955 // Equivalent to "A InvEqP B". This may be the same as the condition
2956 // tested in the max/min; if so, we can just return that.
2957 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2958 return V;
2959 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2960 return V;
2961 // Otherwise, see if "A InvEqP B" simplifies.
2962 if (MaxRecurse)
2963 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2964 return V;
2965 break;
2966 }
2967 case CmpInst::ICMP_SGE:
2968 // Always true.
2969 return getTrue(ITy);
2970 case CmpInst::ICMP_SLT:
2971 // Always false.
2972 return getFalse(ITy);
2973 }
2974 }
2975
2976 // Unsigned variants on "max(a,b)>=a -> true".
2977 P = CmpInst::BAD_ICMP_PREDICATE;
2978 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2979 if (A != RHS)
2980 std::swap(A, B); // umax(A, B) pred A.
2981 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2982 // We analyze this as umax(A, B) pred A.
2983 P = Pred;
2984 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2985 (A == LHS || B == LHS)) {
2986 if (A != LHS)
2987 std::swap(A, B); // A pred umax(A, B).
2988 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2989 // We analyze this as umax(A, B) swapped-pred A.
2990 P = CmpInst::getSwappedPredicate(Pred);
2991 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2992 (A == RHS || B == RHS)) {
2993 if (A != RHS)
2994 std::swap(A, B); // umin(A, B) pred A.
2995 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2996 // We analyze this as umax(-A, -B) swapped-pred -A.
2997 // Note that we do not need to actually form -A or -B thanks to EqP.
2998 P = CmpInst::getSwappedPredicate(Pred);
2999 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
3000 (A == LHS || B == LHS)) {
3001 if (A != LHS)
3002 std::swap(A, B); // A pred umin(A, B).
3003 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
3004 // We analyze this as umax(-A, -B) pred -A.
3005 // Note that we do not need to actually form -A or -B thanks to EqP.
3006 P = Pred;
3007 }
3008 if (P != CmpInst::BAD_ICMP_PREDICATE) {
3009 // Cases correspond to "max(A, B) p A".
3010 switch (P) {
3011 default:
3012 break;
3013 case CmpInst::ICMP_EQ:
3014 case CmpInst::ICMP_ULE:
3015 // Equivalent to "A EqP B". This may be the same as the condition tested
3016 // in the max/min; if so, we can just return that.
3017 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3018 return V;
3019 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3020 return V;
3021 // Otherwise, see if "A EqP B" simplifies.
3022 if (MaxRecurse)
3023 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3024 return V;
3025 break;
3026 case CmpInst::ICMP_NE:
3027 case CmpInst::ICMP_UGT: {
3028 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3029 // Equivalent to "A InvEqP B". This may be the same as the condition
3030 // tested in the max/min; if so, we can just return that.
3031 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3032 return V;
3033 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3034 return V;
3035 // Otherwise, see if "A InvEqP B" simplifies.
3036 if (MaxRecurse)
3037 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3038 return V;
3039 break;
3040 }
3041 case CmpInst::ICMP_UGE:
3042 // Always true.
3043 return getTrue(ITy);
3044 case CmpInst::ICMP_ULT:
3045 // Always false.
3046 return getFalse(ITy);
3047 }
3048 }
3049
3050 // Variants on "max(x,y) >= min(x,z)".
3051 Value *C, *D;
3052 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3053 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3054 (A == C || A == D || B == C || B == D)) {
3055 // max(x, ?) pred min(x, ?).
3056 if (Pred == CmpInst::ICMP_SGE)
3057 // Always true.
3058 return getTrue(ITy);
3059 if (Pred == CmpInst::ICMP_SLT)
3060 // Always false.
3061 return getFalse(ITy);
3062 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3063 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3064 (A == C || A == D || B == C || B == D)) {
3065 // min(x, ?) pred max(x, ?).
3066 if (Pred == CmpInst::ICMP_SLE)
3067 // Always true.
3068 return getTrue(ITy);
3069 if (Pred == CmpInst::ICMP_SGT)
3070 // Always false.
3071 return getFalse(ITy);
3072 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3073 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3074 (A == C || A == D || B == C || B == D)) {
3075 // max(x, ?) pred min(x, ?).
3076 if (Pred == CmpInst::ICMP_UGE)
3077 // Always true.
3078 return getTrue(ITy);
3079 if (Pred == CmpInst::ICMP_ULT)
3080 // Always false.
3081 return getFalse(ITy);
3082 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3083 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3084 (A == C || A == D || B == C || B == D)) {
3085 // min(x, ?) pred max(x, ?).
3086 if (Pred == CmpInst::ICMP_ULE)
3087 // Always true.
3088 return getTrue(ITy);
3089 if (Pred == CmpInst::ICMP_UGT)
3090 // Always false.
3091 return getFalse(ITy);
3092 }
3093
3094 return nullptr;
3095}
3096
Sanjay Patel472cc782016-01-11 22:14:42 +00003097/// Given operands for an ICmpInst, see if we can fold the result.
3098/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003099static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003100 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003101 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003102 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003103
Chris Lattnera71e9d62009-11-10 00:55:12 +00003104 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003105 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003106 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003107
3108 // If we have a constant, make sure it is on the RHS.
3109 std::swap(LHS, RHS);
3110 Pred = CmpInst::getSwappedPredicate(Pred);
3111 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003112
Chris Lattner229907c2011-07-18 04:54:35 +00003113 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003114
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003115 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003116 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3117 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003118 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003119 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003120
Sanjay Pateldc65a272016-12-03 17:30:22 +00003121 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3122 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003123
Sanjay Pateldc65a272016-12-03 17:30:22 +00003124 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3125 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003126
Sanjay Patel67bde282016-08-22 23:12:02 +00003127 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3128 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003129
Chen Li7452d952015-09-26 03:26:47 +00003130 // If both operands have range metadata, use the metadata
3131 // to simplify the comparison.
3132 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3133 auto RHS_Instr = dyn_cast<Instruction>(RHS);
3134 auto LHS_Instr = dyn_cast<Instruction>(LHS);
3135
3136 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3137 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003138 auto RHS_CR = getConstantRangeFromMetadata(
3139 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3140 auto LHS_CR = getConstantRangeFromMetadata(
3141 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003142
3143 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3144 if (Satisfied_CR.contains(LHS_CR))
3145 return ConstantInt::getTrue(RHS->getContext());
3146
3147 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3148 CmpInst::getInversePredicate(Pred), RHS_CR);
3149 if (InversedSatisfied_CR.contains(LHS_CR))
3150 return ConstantInt::getFalse(RHS->getContext());
3151 }
3152 }
3153
Duncan Sands8fb2c382011-01-20 13:21:55 +00003154 // Compare of cast, for example (zext X) != 0 -> X != 0
3155 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3156 Instruction *LI = cast<CastInst>(LHS);
3157 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003158 Type *SrcTy = SrcOp->getType();
3159 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003160
3161 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3162 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003163 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3164 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003165 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3166 // Transfer the cast to the constant.
3167 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3168 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003169 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003170 return V;
3171 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3172 if (RI->getOperand(0)->getType() == SrcTy)
3173 // Compare without the cast.
3174 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003175 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003176 return V;
3177 }
3178 }
3179
3180 if (isa<ZExtInst>(LHS)) {
3181 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3182 // same type.
3183 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3184 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3185 // Compare X and Y. Note that signed predicates become unsigned.
3186 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003187 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003188 MaxRecurse-1))
3189 return V;
3190 }
3191 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3192 // too. If not, then try to deduce the result of the comparison.
3193 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3194 // Compute the constant that would happen if we truncated to SrcTy then
3195 // reextended to DstTy.
3196 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3197 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3198
3199 // If the re-extended constant didn't change then this is effectively
3200 // also a case of comparing two zero-extended values.
3201 if (RExt == CI && MaxRecurse)
3202 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003203 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003204 return V;
3205
3206 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3207 // there. Use this to work out the result of the comparison.
3208 if (RExt != CI) {
3209 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003210 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003211 // LHS <u RHS.
3212 case ICmpInst::ICMP_EQ:
3213 case ICmpInst::ICMP_UGT:
3214 case ICmpInst::ICMP_UGE:
3215 return ConstantInt::getFalse(CI->getContext());
3216
3217 case ICmpInst::ICMP_NE:
3218 case ICmpInst::ICMP_ULT:
3219 case ICmpInst::ICMP_ULE:
3220 return ConstantInt::getTrue(CI->getContext());
3221
3222 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3223 // is non-negative then LHS <s RHS.
3224 case ICmpInst::ICMP_SGT:
3225 case ICmpInst::ICMP_SGE:
3226 return CI->getValue().isNegative() ?
3227 ConstantInt::getTrue(CI->getContext()) :
3228 ConstantInt::getFalse(CI->getContext());
3229
3230 case ICmpInst::ICMP_SLT:
3231 case ICmpInst::ICMP_SLE:
3232 return CI->getValue().isNegative() ?
3233 ConstantInt::getFalse(CI->getContext()) :
3234 ConstantInt::getTrue(CI->getContext());
3235 }
3236 }
3237 }
3238 }
3239
3240 if (isa<SExtInst>(LHS)) {
3241 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3242 // same type.
3243 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3244 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3245 // Compare X and Y. Note that the predicate does not change.
3246 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003247 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003248 return V;
3249 }
3250 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3251 // too. If not, then try to deduce the result of the comparison.
3252 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3253 // Compute the constant that would happen if we truncated to SrcTy then
3254 // reextended to DstTy.
3255 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3256 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3257
3258 // If the re-extended constant didn't change then this is effectively
3259 // also a case of comparing two sign-extended values.
3260 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003261 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003262 return V;
3263
3264 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3265 // bits there. Use this to work out the result of the comparison.
3266 if (RExt != CI) {
3267 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003268 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003269 case ICmpInst::ICMP_EQ:
3270 return ConstantInt::getFalse(CI->getContext());
3271 case ICmpInst::ICMP_NE:
3272 return ConstantInt::getTrue(CI->getContext());
3273
3274 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3275 // LHS >s RHS.
3276 case ICmpInst::ICMP_SGT:
3277 case ICmpInst::ICMP_SGE:
3278 return CI->getValue().isNegative() ?
3279 ConstantInt::getTrue(CI->getContext()) :
3280 ConstantInt::getFalse(CI->getContext());
3281 case ICmpInst::ICMP_SLT:
3282 case ICmpInst::ICMP_SLE:
3283 return CI->getValue().isNegative() ?
3284 ConstantInt::getFalse(CI->getContext()) :
3285 ConstantInt::getTrue(CI->getContext());
3286
3287 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3288 // LHS >u RHS.
3289 case ICmpInst::ICMP_UGT:
3290 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003291 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003292 if (MaxRecurse)
3293 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3294 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003295 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003296 return V;
3297 break;
3298 case ICmpInst::ICMP_ULT:
3299 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003300 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003301 if (MaxRecurse)
3302 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3303 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003304 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003305 return V;
3306 break;
3307 }
3308 }
3309 }
3310 }
3311 }
3312
James Molloy1d88d6f2015-10-22 13:18:42 +00003313 // icmp eq|ne X, Y -> false|true if X != Y
3314 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003315 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003316 LLVMContext &Ctx = LHS->getType()->getContext();
3317 return Pred == ICmpInst::ICMP_NE ?
3318 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3319 }
Junmo Park53470fc2016-04-05 21:14:31 +00003320
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003321 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3322 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003323
Sanjay Patel35289c62016-12-10 17:40:47 +00003324 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003325 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003326
Chandler Carruth8059c842012-03-25 21:28:14 +00003327 // Simplify comparisons of related pointers using a powerful, recursive
3328 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003329 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003330 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003331 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003332 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3333 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3334 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3335 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3336 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3337 Q.DL.getTypeSizeInBits(CRHS->getType()))
3338 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3339 CLHS->getPointerOperand(),
3340 CRHS->getPointerOperand()))
3341 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003342
Nick Lewycky3db143e2012-02-26 02:09:49 +00003343 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3344 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3345 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3346 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3347 (ICmpInst::isEquality(Pred) ||
3348 (GLHS->isInBounds() && GRHS->isInBounds() &&
3349 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3350 // The bases are equal and the indices are constant. Build a constant
3351 // expression GEP with the same indices and a null base pointer to see
3352 // what constant folding can make out of it.
3353 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3354 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003355 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3356 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003357
3358 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003359 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3360 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003361 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3362 }
3363 }
3364 }
3365
David Majnemer5854e9f2014-11-16 02:20:08 +00003366 // If a bit is known to be zero for A and known to be one for B,
3367 // then A and B cannot be equal.
3368 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003369 const APInt *RHSVal;
3370 if (match(RHS, m_APInt(RHSVal))) {
3371 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003372 APInt LHSKnownZero(BitWidth, 0);
3373 APInt LHSKnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003374 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003375 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003376 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3377 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3378 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003379 }
3380 }
3381
Duncan Sandsf532d312010-11-07 16:12:23 +00003382 // If the comparison is with the result of a select instruction, check whether
3383 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003384 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003385 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003386 return V;
3387
3388 // If the comparison is with the result of a phi instruction, check whether
3389 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003390 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003391 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003392 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003393
Craig Topper9f008862014-04-15 04:59:12 +00003394 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003395}
3396
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003397Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003398 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003399 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003400 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003401 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003402 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003403 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003404}
3405
Sanjay Patel472cc782016-01-11 22:14:42 +00003406/// Given operands for an FCmpInst, see if we can fold the result.
3407/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003408static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003409 FastMathFlags FMF, const Query &Q,
3410 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003411 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3412 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3413
Chris Lattnera71e9d62009-11-10 00:55:12 +00003414 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003415 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003416 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003417
Chris Lattnera71e9d62009-11-10 00:55:12 +00003418 // If we have a constant, make sure it is on the RHS.
3419 std::swap(LHS, RHS);
3420 Pred = CmpInst::getSwappedPredicate(Pred);
3421 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003422
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003423 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003424 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003425 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003426 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003427 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003428 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003429
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003430 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3431 if (FMF.noNaNs()) {
3432 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003433 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003434 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003435 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003436 }
3437
Mehdi Aminieb242a52015-03-09 03:20:25 +00003438 // fcmp pred x, undef and fcmp pred undef, x
3439 // fold to true if unordered, false if ordered
3440 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3441 // Choosing NaN for the undef will always make unordered comparison succeed
3442 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003443 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003444 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003445
3446 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003447 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003448 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003449 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003450 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003451 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003452 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003453
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003454 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003455 const ConstantFP *CFP = nullptr;
3456 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3457 if (RHS->getType()->isVectorTy())
3458 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3459 else
3460 CFP = dyn_cast<ConstantFP>(RHSC);
3461 }
3462 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003463 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003464 if (CFP->getValueAPF().isNaN()) {
3465 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003466 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003467 assert(FCmpInst::isUnordered(Pred) &&
3468 "Comparison must be either ordered or unordered!");
3469 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003470 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003471 }
3472 // Check whether the constant is an infinity.
3473 if (CFP->getValueAPF().isInfinity()) {
3474 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003475 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003476 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003477 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003478 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003479 case FCmpInst::FCMP_UGE:
3480 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003481 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003482 default:
3483 break;
3484 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003485 } else {
3486 switch (Pred) {
3487 case FCmpInst::FCMP_OGT:
3488 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003489 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003490 case FCmpInst::FCMP_ULE:
3491 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003492 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003493 default:
3494 break;
3495 }
3496 }
3497 }
3498 if (CFP->getValueAPF().isZero()) {
3499 switch (Pred) {
3500 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003501 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003502 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003503 break;
3504 case FCmpInst::FCMP_OLT:
3505 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003506 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003507 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003508 break;
3509 default:
3510 break;
3511 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003512 }
3513 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003514
Duncan Sandsa620bd12010-11-07 16:46:25 +00003515 // If the comparison is with the result of a select instruction, check whether
3516 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003517 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003518 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003519 return V;
3520
3521 // If the comparison is with the result of a phi instruction, check whether
3522 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003523 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003524 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003525 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003526
Craig Topper9f008862014-04-15 04:59:12 +00003527 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003528}
3529
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003530Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003531 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003532 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003533 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003534 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003535 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003536 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003537}
3538
Sanjay Patel472cc782016-01-11 22:14:42 +00003539/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003540static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3541 const Query &Q,
3542 unsigned MaxRecurse) {
3543 // Trivial replacement.
3544 if (V == Op)
3545 return RepOp;
3546
3547 auto *I = dyn_cast<Instruction>(V);
3548 if (!I)
3549 return nullptr;
3550
3551 // If this is a binary operator, try to simplify it with the replaced op.
3552 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3553 // Consider:
3554 // %cmp = icmp eq i32 %x, 2147483647
3555 // %add = add nsw i32 %x, 1
3556 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3557 //
3558 // We can't replace %sel with %add unless we strip away the flags.
3559 if (isa<OverflowingBinaryOperator>(B))
3560 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3561 return nullptr;
3562 if (isa<PossiblyExactOperator>(B))
3563 if (B->isExact())
3564 return nullptr;
3565
3566 if (MaxRecurse) {
3567 if (B->getOperand(0) == Op)
3568 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3569 MaxRecurse - 1);
3570 if (B->getOperand(1) == Op)
3571 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3572 MaxRecurse - 1);
3573 }
3574 }
3575
3576 // Same for CmpInsts.
3577 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3578 if (MaxRecurse) {
3579 if (C->getOperand(0) == Op)
3580 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3581 MaxRecurse - 1);
3582 if (C->getOperand(1) == Op)
3583 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3584 MaxRecurse - 1);
3585 }
3586 }
3587
3588 // TODO: We could hand off more cases to instsimplify here.
3589
3590 // If all operands are constant after substituting Op for RepOp then we can
3591 // constant fold the instruction.
3592 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3593 // Build a list of all constant operands.
3594 SmallVector<Constant *, 8> ConstOps;
3595 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3596 if (I->getOperand(i) == Op)
3597 ConstOps.push_back(CRepOp);
3598 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3599 ConstOps.push_back(COp);
3600 else
3601 break;
3602 }
3603
3604 // All operands were constants, fold it.
3605 if (ConstOps.size() == I->getNumOperands()) {
3606 if (CmpInst *C = dyn_cast<CmpInst>(I))
3607 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3608 ConstOps[1], Q.DL, Q.TLI);
3609
3610 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3611 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003612 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003613
Manuel Jacobe9024592016-01-21 06:33:22 +00003614 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003615 }
3616 }
3617
3618 return nullptr;
3619}
3620
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003621/// Try to simplify a select instruction when its condition operand is an
3622/// integer comparison where one operand of the compare is a constant.
3623static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3624 const APInt *Y, bool TrueWhenUnset) {
3625 const APInt *C;
3626
3627 // (X & Y) == 0 ? X & ~Y : X --> X
3628 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3629 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3630 *Y == ~*C)
3631 return TrueWhenUnset ? FalseVal : TrueVal;
3632
3633 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3634 // (X & Y) != 0 ? X : X & ~Y --> X
3635 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3636 *Y == ~*C)
3637 return TrueWhenUnset ? FalseVal : TrueVal;
3638
3639 if (Y->isPowerOf2()) {
3640 // (X & Y) == 0 ? X | Y : X --> X | Y
3641 // (X & Y) != 0 ? X | Y : X --> X
3642 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3643 *Y == *C)
3644 return TrueWhenUnset ? TrueVal : FalseVal;
3645
3646 // (X & Y) == 0 ? X : X | Y --> X
3647 // (X & Y) != 0 ? X : X | Y --> X | Y
3648 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3649 *Y == *C)
3650 return TrueWhenUnset ? TrueVal : FalseVal;
3651 }
Matt Arsenault82606662017-01-11 00:57:54 +00003652
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003653 return nullptr;
3654}
3655
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003656/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3657/// eq/ne.
3658static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3659 Value *FalseVal,
3660 bool TrueWhenUnset) {
3661 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003662 if (!BitWidth)
3663 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00003664
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003665 APInt MinSignedValue;
3666 Value *X;
3667 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3668 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3669 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3670 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3671 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3672 } else {
3673 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3674 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3675 X = CmpLHS;
3676 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3677 }
3678
3679 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3680 TrueWhenUnset))
3681 return V;
3682
3683 return nullptr;
3684}
3685
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003686/// Try to simplify a select instruction when its condition operand is an
3687/// integer comparison.
3688static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3689 Value *FalseVal, const Query &Q,
3690 unsigned MaxRecurse) {
3691 ICmpInst::Predicate Pred;
3692 Value *CmpLHS, *CmpRHS;
3693 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3694 return nullptr;
3695
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003696 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3697 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003698 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3699 Value *X;
3700 const APInt *Y;
3701 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3702 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3703 Pred == ICmpInst::ICMP_EQ))
3704 return V;
3705 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003706 // Comparing signed-less-than 0 checks if the sign bit is set.
3707 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3708 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003709 return V;
3710 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003711 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3712 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3713 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003714 return V;
3715 }
3716
3717 if (CondVal->hasOneUse()) {
3718 const APInt *C;
3719 if (match(CmpRHS, m_APInt(C))) {
3720 // X < MIN ? T : F --> F
3721 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3722 return FalseVal;
3723 // X < MIN ? T : F --> F
3724 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3725 return FalseVal;
3726 // X > MAX ? T : F --> F
3727 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3728 return FalseVal;
3729 // X > MAX ? T : F --> F
3730 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3731 return FalseVal;
3732 }
3733 }
3734
3735 // If we have an equality comparison, then we know the value in one of the
3736 // arms of the select. See if substituting this value into the arm and
3737 // simplifying the result yields the same value as the other arm.
3738 if (Pred == ICmpInst::ICMP_EQ) {
3739 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3740 TrueVal ||
3741 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3742 TrueVal)
3743 return FalseVal;
3744 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3745 FalseVal ||
3746 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3747 FalseVal)
3748 return FalseVal;
3749 } else if (Pred == ICmpInst::ICMP_NE) {
3750 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3751 FalseVal ||
3752 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3753 FalseVal)
3754 return TrueVal;
3755 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3756 TrueVal ||
3757 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3758 TrueVal)
3759 return TrueVal;
3760 }
3761
3762 return nullptr;
3763}
3764
Sanjay Patel472cc782016-01-11 22:14:42 +00003765/// Given operands for a SelectInst, see if we can fold the result.
3766/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003767static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3768 Value *FalseVal, const Query &Q,
3769 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003770 // select true, X, Y -> X
3771 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003772 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3773 if (CB->isAllOnesValue())
3774 return TrueVal;
3775 if (CB->isNullValue())
3776 return FalseVal;
3777 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003778
Chris Lattnerc707fa92010-04-20 05:32:14 +00003779 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003780 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003781 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003782
Chris Lattnerc707fa92010-04-20 05:32:14 +00003783 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3784 if (isa<Constant>(TrueVal))
3785 return TrueVal;
3786 return FalseVal;
3787 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003788 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3789 return FalseVal;
3790 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3791 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003792
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003793 if (Value *V =
3794 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3795 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003796
Craig Topper9f008862014-04-15 04:59:12 +00003797 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003798}
3799
Duncan Sandsb8cee002012-03-13 11:42:19 +00003800Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003801 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003802 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003803 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003804 const Instruction *CxtI) {
3805 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003806 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003807}
3808
Sanjay Patel472cc782016-01-11 22:14:42 +00003809/// Given operands for an GetElementPtrInst, see if we can fold the result.
3810/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003811static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3812 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003813 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003814 unsigned AS =
3815 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003816
Chris Lattner8574aba2009-11-27 00:29:05 +00003817 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003818 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003819 return Ops[0];
3820
Nico Weber48c82402014-08-27 20:06:19 +00003821 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003822 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003823 Type *GEPTy = PointerType::get(LastType, AS);
3824 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3825 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3826
3827 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003828 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003829
Jay Foadb992a632011-07-19 15:07:52 +00003830 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003831 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003832 if (match(Ops[1], m_Zero()))
3833 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003834
David Blaikie4a2e73b2015-04-02 18:55:32 +00003835 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003836 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003837 Value *P;
3838 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003839 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003840 // getelementptr P, N -> P if P points to a type of zero size.
3841 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003842 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003843
3844 // The following transforms are only safe if the ptrtoint cast
3845 // doesn't truncate the pointers.
3846 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003847 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003848 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3849 if (match(P, m_Zero()))
3850 return Constant::getNullValue(GEPTy);
3851 Value *Temp;
3852 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003853 if (Temp->getType() == GEPTy)
3854 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003855 return nullptr;
3856 };
3857
3858 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3859 if (TyAllocSize == 1 &&
3860 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3861 if (Value *R = PtrToIntOrZero(P))
3862 return R;
3863
3864 // getelementptr V, (ashr (sub P, V), C) -> Q
3865 // if P points to a type of size 1 << C.
3866 if (match(Ops[1],
3867 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3868 m_ConstantInt(C))) &&
3869 TyAllocSize == 1ULL << C)
3870 if (Value *R = PtrToIntOrZero(P))
3871 return R;
3872
3873 // getelementptr V, (sdiv (sub P, V), C) -> Q
3874 // if P points to a type of size C.
3875 if (match(Ops[1],
3876 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3877 m_SpecificInt(TyAllocSize))))
3878 if (Value *R = PtrToIntOrZero(P))
3879 return R;
3880 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003881 }
3882 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003883
David Majnemerd1501372016-08-07 07:58:12 +00003884 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3885 all_of(Ops.slice(1).drop_back(1),
3886 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3887 unsigned PtrWidth =
3888 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3889 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3890 APInt BasePtrOffset(PtrWidth, 0);
3891 Value *StrippedBasePtr =
3892 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3893 BasePtrOffset);
3894
David Majnemer5c5df622016-08-16 06:13:46 +00003895 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003896 if (match(Ops.back(),
3897 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3898 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3899 return ConstantExpr::getIntToPtr(CI, GEPTy);
3900 }
David Majnemer5c5df622016-08-16 06:13:46 +00003901 // gep (gep V, C), (xor V, -1) -> C-1
3902 if (match(Ops.back(),
3903 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3904 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3905 return ConstantExpr::getIntToPtr(CI, GEPTy);
3906 }
David Majnemerd1501372016-08-07 07:58:12 +00003907 }
3908 }
3909
Chris Lattner8574aba2009-11-27 00:29:05 +00003910 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003911 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003912 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003913 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003914
David Blaikie4a2e73b2015-04-02 18:55:32 +00003915 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3916 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003917}
3918
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003919Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3920 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003921 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003922 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003923 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003924 return ::SimplifyGEPInst(SrcTy, Ops,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003925 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003926}
3927
Sanjay Patel472cc782016-01-11 22:14:42 +00003928/// Given operands for an InsertValueInst, see if we can fold the result.
3929/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003930static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3931 ArrayRef<unsigned> Idxs, const Query &Q,
3932 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003933 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3934 if (Constant *CVal = dyn_cast<Constant>(Val))
3935 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3936
3937 // insertvalue x, undef, n -> x
3938 if (match(Val, m_Undef()))
3939 return Agg;
3940
3941 // insertvalue x, (extractvalue y, n), n
3942 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003943 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3944 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003945 // insertvalue undef, (extractvalue y, n), n -> y
3946 if (match(Agg, m_Undef()))
3947 return EV->getAggregateOperand();
3948
3949 // insertvalue y, (extractvalue y, n), n -> y
3950 if (Agg == EV->getAggregateOperand())
3951 return Agg;
3952 }
3953
Craig Topper9f008862014-04-15 04:59:12 +00003954 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003955}
3956
Chandler Carruth66b31302015-01-04 12:03:27 +00003957Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003958 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003959 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +00003960 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003961 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003962 RecursionLimit);
3963}
3964
Sanjay Patel472cc782016-01-11 22:14:42 +00003965/// Given operands for an ExtractValueInst, see if we can fold the result.
3966/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003967static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3968 const Query &, unsigned) {
3969 if (auto *CAgg = dyn_cast<Constant>(Agg))
3970 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3971
3972 // extractvalue x, (insertvalue y, elt, n), n -> elt
3973 unsigned NumIdxs = Idxs.size();
3974 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3975 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3976 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3977 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3978 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3979 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3980 Idxs.slice(0, NumCommonIdxs)) {
3981 if (NumIdxs == NumInsertValueIdxs)
3982 return IVI->getInsertedValueOperand();
3983 break;
3984 }
3985 }
3986
3987 return nullptr;
3988}
3989
3990Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3991 const DataLayout &DL,
3992 const TargetLibraryInfo *TLI,
3993 const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003994 AssumptionCache *AC,
David Majnemer25a796e2015-07-13 01:15:46 +00003995 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003996 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003997 RecursionLimit);
3998}
3999
Sanjay Patel472cc782016-01-11 22:14:42 +00004000/// Given operands for an ExtractElementInst, see if we can fold the result.
4001/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00004002static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
4003 unsigned) {
4004 if (auto *CVec = dyn_cast<Constant>(Vec)) {
4005 if (auto *CIdx = dyn_cast<Constant>(Idx))
4006 return ConstantFoldExtractElementInstruction(CVec, CIdx);
4007
4008 // The index is not relevant if our vector is a splat.
4009 if (auto *Splat = CVec->getSplatValue())
4010 return Splat;
4011
4012 if (isa<UndefValue>(Vec))
4013 return UndefValue::get(Vec->getType()->getVectorElementType());
4014 }
4015
4016 // If extracting a specified index from the vector, see if we can recursively
4017 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00004018 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
4019 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00004020 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00004021
4022 return nullptr;
4023}
4024
4025Value *llvm::SimplifyExtractElementInst(
4026 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004027 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
4028 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00004029 RecursionLimit);
4030}
4031
Sanjay Patel472cc782016-01-11 22:14:42 +00004032/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00004033static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004034 // If all of the PHI's incoming values are the same then replace the PHI node
4035 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004036 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004037 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004038 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004039 // If the incoming value is the phi node itself, it can safely be skipped.
4040 if (Incoming == PN) continue;
4041 if (isa<UndefValue>(Incoming)) {
4042 // Remember that we saw an undef value, but otherwise ignore them.
4043 HasUndefInput = true;
4044 continue;
4045 }
4046 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004047 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004048 CommonValue = Incoming;
4049 }
4050
4051 // If CommonValue is null then all of the incoming values were either undef or
4052 // equal to the phi node itself.
4053 if (!CommonValue)
4054 return UndefValue::get(PN->getType());
4055
4056 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4057 // instruction, we cannot return X as the result of the PHI node unless it
4058 // dominates the PHI block.
4059 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00004060 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004061
4062 return CommonValue;
4063}
4064
David Majnemer6774d612016-07-26 17:58:05 +00004065static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4066 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004067 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004068 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004069
David Majnemer6774d612016-07-26 17:58:05 +00004070 if (auto *CI = dyn_cast<CastInst>(Op)) {
4071 auto *Src = CI->getOperand(0);
4072 Type *SrcTy = Src->getType();
4073 Type *MidTy = CI->getType();
4074 Type *DstTy = Ty;
4075 if (Src->getType() == Ty) {
4076 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4077 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4078 Type *SrcIntPtrTy =
4079 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4080 Type *MidIntPtrTy =
4081 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4082 Type *DstIntPtrTy =
4083 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4084 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4085 SrcIntPtrTy, MidIntPtrTy,
4086 DstIntPtrTy) == Instruction::BitCast)
4087 return Src;
4088 }
4089 }
David Majnemera90a6212016-07-26 05:52:29 +00004090
4091 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004092 if (CastOpc == Instruction::BitCast)
4093 if (Op->getType() == Ty)
4094 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004095
4096 return nullptr;
4097}
4098
David Majnemer6774d612016-07-26 17:58:05 +00004099Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4100 const DataLayout &DL,
4101 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004102 const DominatorTree *DT, AssumptionCache *AC,
David Majnemer6774d612016-07-26 17:58:05 +00004103 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004104 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004105 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004106}
4107
Chris Lattnera71e9d62009-11-10 00:55:12 +00004108//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004109
Sanjay Patel472cc782016-01-11 22:14:42 +00004110/// Given operands for a BinaryOperator, see if we can fold the result.
4111/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004112static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004113 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004114 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004115 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004116 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004117 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004118 case Instruction::FAdd:
4119 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4120
Chris Lattner9e4aa022011-02-09 17:15:04 +00004121 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004122 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004123 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004124 case Instruction::FSub:
4125 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4126
Duncan Sandsb8cee002012-03-13 11:42:19 +00004127 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004128 case Instruction::FMul:
4129 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004130 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4131 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004132 case Instruction::FDiv:
4133 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004134 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4135 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004136 case Instruction::FRem:
4137 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004138 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004139 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004140 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004141 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004142 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004143 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004144 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
4145 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4146 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
4147 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004148 default:
4149 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00004150 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4151 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00004152
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004153 // If the operation is associative, try some generic simplifications.
4154 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004155 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004156 return V;
4157
Duncan Sandsb8cee002012-03-13 11:42:19 +00004158 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00004159 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004160 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004161 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004162 return V;
4163
4164 // If the operation is with the result of a phi instruction, check whether
4165 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004166 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004167 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00004168 return V;
4169
Craig Topper9f008862014-04-15 04:59:12 +00004170 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00004171 }
4172}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004173
Sanjay Patel472cc782016-01-11 22:14:42 +00004174/// Given operands for a BinaryOperator, see if we can fold the result.
4175/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004176/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4177/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4178static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4179 const FastMathFlags &FMF, const Query &Q,
4180 unsigned MaxRecurse) {
4181 switch (Opcode) {
4182 case Instruction::FAdd:
4183 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4184 case Instruction::FSub:
4185 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4186 case Instruction::FMul:
4187 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004188 case Instruction::FDiv:
4189 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004190 default:
4191 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4192 }
4193}
4194
Duncan Sands7e800d62010-11-14 11:23:23 +00004195Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004196 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004197 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004198 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004199 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004200 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004201}
4202
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004203Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004204 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004205 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004206 const DominatorTree *DT, AssumptionCache *AC,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004207 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004208 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004209 RecursionLimit);
4210}
4211
Sanjay Patel472cc782016-01-11 22:14:42 +00004212/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004213static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004214 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004215 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004216 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004217 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004218}
4219
4220Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004221 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004222 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004223 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004224 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004225 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004226}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004227
Michael Ilseman54857292013-02-07 19:26:05 +00004228static bool IsIdempotent(Intrinsic::ID ID) {
4229 switch (ID) {
4230 default: return false;
4231
4232 // Unary idempotent: f(f(x)) = f(x)
4233 case Intrinsic::fabs:
4234 case Intrinsic::floor:
4235 case Intrinsic::ceil:
4236 case Intrinsic::trunc:
4237 case Intrinsic::rint:
4238 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004239 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004240 return true;
4241 }
4242}
4243
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004244static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4245 const DataLayout &DL) {
4246 GlobalValue *PtrSym;
4247 APInt PtrOffset;
4248 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4249 return nullptr;
4250
4251 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4252 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4253 Type *Int32PtrTy = Int32Ty->getPointerTo();
4254 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4255
4256 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4257 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4258 return nullptr;
4259
4260 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4261 if (OffsetInt % 4 != 0)
4262 return nullptr;
4263
4264 Constant *C = ConstantExpr::getGetElementPtr(
4265 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4266 ConstantInt::get(Int64Ty, OffsetInt / 4));
4267 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4268 if (!Loaded)
4269 return nullptr;
4270
4271 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4272 if (!LoadedCE)
4273 return nullptr;
4274
4275 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4276 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4277 if (!LoadedCE)
4278 return nullptr;
4279 }
4280
4281 if (LoadedCE->getOpcode() != Instruction::Sub)
4282 return nullptr;
4283
4284 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4285 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4286 return nullptr;
4287 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4288
4289 Constant *LoadedRHS = LoadedCE->getOperand(1);
4290 GlobalValue *LoadedRHSSym;
4291 APInt LoadedRHSOffset;
4292 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4293 DL) ||
4294 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4295 return nullptr;
4296
4297 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4298}
4299
David Majnemer17a95aa2016-07-14 06:58:37 +00004300static bool maskIsAllZeroOrUndef(Value *Mask) {
4301 auto *ConstMask = dyn_cast<Constant>(Mask);
4302 if (!ConstMask)
4303 return false;
4304 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4305 return true;
4306 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4307 ++I) {
4308 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4309 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4310 continue;
4311 return false;
4312 }
4313 return true;
4314}
4315
Michael Ilseman54857292013-02-07 19:26:05 +00004316template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004317static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004318 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004319 Intrinsic::ID IID = F->getIntrinsicID();
4320 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004321
4322 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004323 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004324 // Perform idempotent optimizations
4325 if (IsIdempotent(IID)) {
4326 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4327 if (II->getIntrinsicID() == IID)
4328 return II;
4329 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004330 }
4331
4332 switch (IID) {
4333 case Intrinsic::fabs: {
4334 if (SignBitMustBeZero(*ArgBegin, Q.TLI))
4335 return *ArgBegin;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004336 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004337 }
4338 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004339 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004340 }
4341 }
Michael Ilseman54857292013-02-07 19:26:05 +00004342
Matt Arsenault82606662017-01-11 00:57:54 +00004343 // Binary Ops
4344 if (NumOperands == 2) {
4345 Value *LHS = *ArgBegin;
4346 Value *RHS = *(ArgBegin + 1);
4347 Type *ReturnType = F->getReturnType();
4348
4349 switch (IID) {
4350 case Intrinsic::usub_with_overflow:
4351 case Intrinsic::ssub_with_overflow: {
4352 // X - X -> { 0, false }
4353 if (LHS == RHS)
4354 return Constant::getNullValue(ReturnType);
4355
4356 // X - undef -> undef
4357 // undef - X -> undef
4358 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4359 return UndefValue::get(ReturnType);
4360
4361 return nullptr;
4362 }
4363 case Intrinsic::uadd_with_overflow:
4364 case Intrinsic::sadd_with_overflow: {
4365 // X + undef -> undef
4366 if (isa<UndefValue>(RHS))
4367 return UndefValue::get(ReturnType);
4368
4369 return nullptr;
4370 }
4371 case Intrinsic::umul_with_overflow:
4372 case Intrinsic::smul_with_overflow: {
4373 // X * 0 -> { 0, false }
4374 if (match(RHS, m_Zero()))
4375 return Constant::getNullValue(ReturnType);
4376
4377 // X * undef -> { 0, false }
4378 if (match(RHS, m_Undef()))
4379 return Constant::getNullValue(ReturnType);
4380
4381 return nullptr;
4382 }
4383 case Intrinsic::load_relative: {
4384 Constant *C0 = dyn_cast<Constant>(LHS);
4385 Constant *C1 = dyn_cast<Constant>(RHS);
4386 if (C0 && C1)
4387 return SimplifyRelativeLoad(C0, C1, Q.DL);
4388 return nullptr;
4389 }
4390 default:
4391 return nullptr;
4392 }
4393 }
4394
4395 // Simplify calls to llvm.masked.load.*
4396 switch (IID) {
4397 case Intrinsic::masked_load: {
4398 Value *MaskArg = ArgBegin[2];
4399 Value *PassthruArg = ArgBegin[3];
4400 // If the mask is all zeros or undef, the "passthru" argument is the result.
4401 if (maskIsAllZeroOrUndef(MaskArg))
4402 return PassthruArg;
4403 return nullptr;
4404 }
4405 default:
4406 return nullptr;
4407 }
Michael Ilseman54857292013-02-07 19:26:05 +00004408}
4409
Chandler Carruth9dc35582012-12-28 11:30:55 +00004410template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004411static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004412 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004413 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004414 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4415 Ty = PTy->getElementType();
4416 FunctionType *FTy = cast<FunctionType>(Ty);
4417
Dan Gohman85977e62011-11-04 18:32:42 +00004418 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004419 // call null -> undef
4420 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004421 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004422
Chandler Carruthf6182152012-12-28 14:23:29 +00004423 Function *F = dyn_cast<Function>(V);
4424 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004425 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004426
David Majnemer15032582015-05-22 03:56:46 +00004427 if (F->isIntrinsic())
4428 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004429 return Ret;
4430
Chandler Carruthf6182152012-12-28 14:23:29 +00004431 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004432 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004433
4434 SmallVector<Constant *, 4> ConstantArgs;
4435 ConstantArgs.reserve(ArgEnd - ArgBegin);
4436 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4437 Constant *C = dyn_cast<Constant>(*I);
4438 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004439 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004440 ConstantArgs.push_back(C);
4441 }
4442
4443 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004444}
4445
Chandler Carruthf6182152012-12-28 14:23:29 +00004446Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004447 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004448 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004449 AssumptionCache *AC, const Instruction *CxtI) {
4450 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004451 RecursionLimit);
4452}
4453
Chandler Carruthf6182152012-12-28 14:23:29 +00004454Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004455 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004456 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004457 const Instruction *CxtI) {
4458 return ::SimplifyCall(V, Args.begin(), Args.end(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004459 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004460}
4461
Sanjay Patel472cc782016-01-11 22:14:42 +00004462/// See if we can compute a simplified version of this instruction.
4463/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004464Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004465 const TargetLibraryInfo *TLI,
Sanjay Patel54656ca2017-02-06 18:26:06 +00004466 const DominatorTree *DT, AssumptionCache *AC,
4467 OptimizationRemarkEmitter *ORE) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004468 Value *Result;
4469
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004470 switch (I->getOpcode()) {
4471 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004472 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004473 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004474 case Instruction::FAdd:
4475 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004476 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004477 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004478 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004479 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4480 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004481 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004482 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004483 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004484 case Instruction::FSub:
4485 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004486 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004487 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004488 case Instruction::Sub:
4489 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4490 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004491 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004492 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004493 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004494 case Instruction::FMul:
4495 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004496 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004497 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004498 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004499 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004500 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004501 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004502 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004503 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004504 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004505 break;
4506 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004507 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004508 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004509 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004510 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004511 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004512 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004513 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004514 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004515 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004516 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004517 break;
4518 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004519 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004520 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004521 break;
4522 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004523 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004524 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004525 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004526 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004527 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4528 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004529 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004530 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004531 break;
4532 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004533 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004534 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004535 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004536 break;
4537 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004538 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004539 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004540 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004541 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004542 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004543 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004544 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004545 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004546 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004547 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004548 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004549 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004550 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004551 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004552 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004553 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004554 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004555 Result =
4556 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004557 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004558 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004559 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004560 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4561 I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004562 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004563 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004564 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004565 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004566 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004567 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004568 case Instruction::GetElementPtr: {
4569 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004570 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004571 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004572 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004573 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004574 case Instruction::InsertValue: {
4575 InsertValueInst *IV = cast<InsertValueInst>(I);
4576 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4577 IV->getInsertedValueOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004578 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004579 break;
4580 }
David Majnemer25a796e2015-07-13 01:15:46 +00004581 case Instruction::ExtractValue: {
4582 auto *EVI = cast<ExtractValueInst>(I);
4583 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004584 EVI->getIndices(), DL, TLI, DT, AC, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004585 break;
4586 }
David Majnemer599ca442015-07-13 01:15:53 +00004587 case Instruction::ExtractElement: {
4588 auto *EEI = cast<ExtractElementInst>(I);
4589 Result = SimplifyExtractElementInst(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004590 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
David Majnemer599ca442015-07-13 01:15:53 +00004591 break;
4592 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004593 case Instruction::PHI:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004594 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004595 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004596 case Instruction::Call: {
4597 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004598 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004599 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004600 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004601 }
David Majnemer6774d612016-07-26 17:58:05 +00004602#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4603#include "llvm/IR/Instruction.def"
4604#undef HANDLE_CAST_INST
4605 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004606 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004607 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004608 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004609
Hal Finkelf2199b22015-10-23 20:37:08 +00004610 // In general, it is possible for computeKnownBits to determine all bits in a
4611 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004612 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004613 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4614 APInt KnownZero(BitWidth, 0);
4615 APInt KnownOne(BitWidth, 0);
Sanjay Patel54656ca2017-02-06 18:26:06 +00004616 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT, ORE);
Hal Finkelf2199b22015-10-23 20:37:08 +00004617 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004618 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004619 }
4620
Duncan Sands64e41cf2010-11-17 08:35:29 +00004621 /// If called on unreachable code, the above logic may report that the
4622 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004623 /// detecting that case here, returning a safe value instead.
4624 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004625}
4626
Sanjay Patelf44bd382016-01-20 18:59:48 +00004627/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004628/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004629///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004630/// This is the common implementation of the recursive simplification routines.
4631/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4632/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4633/// instructions to process and attempt to simplify it using
4634/// InstructionSimplify.
4635///
4636/// This routine returns 'true' only when *it* simplifies something. The passed
4637/// in simplified value does not count toward this.
4638static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004639 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004640 const DominatorTree *DT,
4641 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004642 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004643 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004644 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004645
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004646 // If we have an explicit value to collapse to, do that round of the
4647 // simplification loop by hand initially.
4648 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004649 for (User *U : I->users())
4650 if (U != I)
4651 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004652
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004653 // Replace the instruction with its simplified value.
4654 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004655
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004656 // Gracefully handle edge cases where the instruction is not wired into any
4657 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004658 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4659 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004660 I->eraseFromParent();
4661 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004662 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004663 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004664
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004665 // Note that we must test the size on each iteration, the worklist can grow.
4666 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4667 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004668
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004669 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004670 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004671 if (!SimpleV)
4672 continue;
4673
4674 Simplified = true;
4675
4676 // Stash away all the uses of the old instruction so we can check them for
4677 // recursive simplifications after a RAUW. This is cheaper than checking all
4678 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004679 for (User *U : I->users())
4680 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004681
4682 // Replace the instruction with its simplified value.
4683 I->replaceAllUsesWith(SimpleV);
4684
4685 // Gracefully handle edge cases where the instruction is not wired into any
4686 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004687 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4688 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004689 I->eraseFromParent();
4690 }
4691 return Simplified;
4692}
4693
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004694bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004695 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004696 const DominatorTree *DT,
4697 AssumptionCache *AC) {
4698 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004699}
4700
4701bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004702 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004703 const DominatorTree *DT,
4704 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004705 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4706 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004707 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004708}