blob: 2c7ca6210ada7c4c0af7f2804709c51b0d38ce84 [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
Duncan Sands772749a2011-01-01 20:08:02 +0000560 if (match(Op0, m_Not(m_Specific(Op1))) ||
561 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000562 return Constant::getAllOnesValue(Op0->getType());
Duncan Sandsb238de02010-11-19 09:20:39 +0000563
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000564 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000565 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000566 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000567 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000568
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000569 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000570 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000571 MaxRecurse))
572 return V;
573
Duncan Sandsb238de02010-11-19 09:20:39 +0000574 // Threading Add over selects and phi nodes is pointless, so don't bother.
575 // Threading over the select in "A + select(cond, B, C)" means evaluating
576 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
577 // only if B and C are equal. If B and C are equal then (since we assume
578 // that operands have already been simplified) "select(cond, B, C)" should
579 // have been simplified to the common value of B and C already. Analysing
580 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
581 // for threading over phi nodes.
582
Craig Topper9f008862014-04-15 04:59:12 +0000583 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000584}
585
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000586Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000587 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000588 const DominatorTree *DT, AssumptionCache *AC,
589 const Instruction *CxtI) {
590 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000591 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000592}
593
Chandler Carrutha0796552012-03-12 11:19:31 +0000594/// \brief Compute the base pointer and cumulative constant offsets for V.
595///
596/// This strips all constant offsets off of V, leaving it the base pointer, and
597/// accumulates the total constant offset applied in the returned constant. It
598/// returns 0 if V is not a pointer, and returns the constant '0' if there are
599/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000600///
601/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
602/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
603/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000605 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000606 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000607
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000608 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000609 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000610
611 // Even though we don't look through PHI nodes, we could be called on an
612 // instruction in an unreachable block, which may be on a cycle.
613 SmallPtrSet<Value *, 4> Visited;
614 Visited.insert(V);
615 do {
616 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000617 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000618 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000619 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000620 V = GEP->getPointerOperand();
621 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000622 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000623 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000624 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000625 break;
626 V = GA->getAliasee();
627 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000628 if (auto CS = CallSite(V))
629 if (Value *RV = CS.getReturnedArgOperand()) {
630 V = RV;
631 continue;
632 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000633 break;
634 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000635 assert(V->getType()->getScalarType()->isPointerTy() &&
636 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000637 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000638
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000639 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
640 if (V->getType()->isVectorTy())
641 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
642 OffsetIntPtr);
643 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000644}
645
646/// \brief Compute the constant difference between two pointer values.
647/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000648static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
649 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000650 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
651 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000652
653 // If LHS and RHS are not related via constant offsets to the same base
654 // value, there is nothing we can do here.
655 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000656 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000657
658 // Otherwise, the difference of LHS - RHS can be computed as:
659 // LHS - RHS
660 // = (LHSOffset + Base) - (RHSOffset + Base)
661 // = LHSOffset - RHSOffset
662 return ConstantExpr::getSub(LHSOffset, RHSOffset);
663}
664
Sanjay Patel472cc782016-01-11 22:14:42 +0000665/// Given operands for a Sub, see if we can fold the result.
666/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000667static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000668 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0a2c41682010-12-15 14:07:39 +0000669 if (Constant *CLHS = dyn_cast<Constant>(Op0))
Manuel Jacoba61ca372016-01-21 06:26:35 +0000670 if (Constant *CRHS = dyn_cast<Constant>(Op1))
671 return ConstantFoldBinaryOpOperands(Instruction::Sub, CLHS, CRHS, Q.DL);
Duncan Sands0a2c41682010-12-15 14:07:39 +0000672
673 // X - undef -> undef
674 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000675 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000676 return UndefValue::get(Op0->getType());
677
678 // X - 0 -> X
679 if (match(Op1, m_Zero()))
680 return Op0;
681
682 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000683 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000684 return Constant::getNullValue(Op0->getType());
685
Sanjay Patelefd88852016-10-19 21:23:45 +0000686 // Is this a negation?
687 if (match(Op0, m_Zero())) {
688 // 0 - X -> 0 if the sub is NUW.
689 if (isNUW)
690 return Op0;
691
692 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
693 APInt KnownZero(BitWidth, 0);
694 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000695 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patelefd88852016-10-19 21:23:45 +0000696 if (KnownZero == ~APInt::getSignBit(BitWidth)) {
697 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
698 // Op1 must be 0 because negating the minimum signed value is undefined.
699 if (isNSW)
700 return Op0;
701
702 // 0 - X -> X if X is 0 or the minimum signed value.
703 return Op1;
704 }
705 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000706
Duncan Sands99589d02011-01-18 11:50:19 +0000707 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
708 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000709 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000710 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
711 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000712 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000713 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000714 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000715 // It does, we successfully reassociated!
716 ++NumReassoc;
717 return W;
718 }
719 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000720 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000721 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000722 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000723 // It does, we successfully reassociated!
724 ++NumReassoc;
725 return W;
726 }
727 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000728
Duncan Sands99589d02011-01-18 11:50:19 +0000729 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
730 // For example, X - (X + 1) -> -1
731 X = Op0;
732 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
733 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000734 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000735 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000736 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000737 // It does, we successfully reassociated!
738 ++NumReassoc;
739 return W;
740 }
741 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000742 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000743 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000744 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000745 // It does, we successfully reassociated!
746 ++NumReassoc;
747 return W;
748 }
749 }
750
751 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
752 // For example, X - (X - Y) -> Y.
753 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000754 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
755 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000756 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000757 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000758 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000759 // It does, we successfully reassociated!
760 ++NumReassoc;
761 return W;
762 }
763
Duncan Sands395ac42d2012-03-13 14:07:05 +0000764 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
765 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
766 match(Op1, m_Trunc(m_Value(Y))))
767 if (X->getType() == Y->getType())
768 // See if "V === X - Y" simplifies.
769 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
770 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000771 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
772 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000773 // It does, return the simplified "trunc V".
774 return W;
775
776 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000777 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000778 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000779 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000780 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
781
Duncan Sands99589d02011-01-18 11:50:19 +0000782 // i1 sub -> xor.
783 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000784 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000785 return V;
786
Duncan Sands0a2c41682010-12-15 14:07:39 +0000787 // Threading Sub over selects and phi nodes is pointless, so don't bother.
788 // Threading over the select in "A - select(cond, B, C)" means evaluating
789 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
790 // only if B and C are equal. If B and C are equal then (since we assume
791 // that operands have already been simplified) "select(cond, B, C)" should
792 // have been simplified to the common value of B and C already. Analysing
793 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
794 // for threading over phi nodes.
795
Craig Topper9f008862014-04-15 04:59:12 +0000796 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000797}
798
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000799Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000800 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000801 const DominatorTree *DT, AssumptionCache *AC,
802 const Instruction *CxtI) {
803 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000804 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000805}
806
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000807/// Given operands for an FAdd, see if we can fold the result. If not, this
808/// returns null.
809static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
810 const Query &Q, unsigned MaxRecurse) {
811 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000812 if (Constant *CRHS = dyn_cast<Constant>(Op1))
813 return ConstantFoldBinaryOpOperands(Instruction::FAdd, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000814
815 // Canonicalize the constant to the RHS.
816 std::swap(Op0, Op1);
817 }
818
819 // fadd X, -0 ==> X
820 if (match(Op1, m_NegZero()))
821 return Op0;
822
823 // fadd X, 0 ==> X, when we know X is not -0
824 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000825 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000826 return Op0;
827
828 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
829 // where nnan and ninf have to occur at least once somewhere in this
830 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000831 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000832 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
833 SubOp = Op1;
834 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
835 SubOp = Op0;
836 if (SubOp) {
837 Instruction *FSub = cast<Instruction>(SubOp);
838 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
839 (FMF.noInfs() || FSub->hasNoInfs()))
840 return Constant::getNullValue(Op0->getType());
841 }
842
Craig Topper9f008862014-04-15 04:59:12 +0000843 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000844}
845
846/// Given operands for an FSub, see if we can fold the result. If not, this
847/// returns null.
848static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
849 const Query &Q, unsigned MaxRecurse) {
850 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000851 if (Constant *CRHS = dyn_cast<Constant>(Op1))
852 return ConstantFoldBinaryOpOperands(Instruction::FSub, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000853 }
854
855 // fsub X, 0 ==> X
856 if (match(Op1, m_Zero()))
857 return Op0;
858
859 // fsub X, -0 ==> X, when we know X is not -0
860 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000861 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000862 return Op0;
863
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000864 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000865 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000866 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
867 return X;
868
869 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000870 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000871 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
872 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000873
Benjamin Kramer228680d2015-06-14 21:01:20 +0000874 // fsub nnan x, x ==> 0.0
875 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000876 return Constant::getNullValue(Op0->getType());
877
Craig Topper9f008862014-04-15 04:59:12 +0000878 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000879}
880
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000881/// Given the operands for an FMul, see if we can fold the result
882static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
883 FastMathFlags FMF,
884 const Query &Q,
885 unsigned MaxRecurse) {
886 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000887 if (Constant *CRHS = dyn_cast<Constant>(Op1))
888 return ConstantFoldBinaryOpOperands(Instruction::FMul, CLHS, CRHS, Q.DL);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000889
890 // Canonicalize the constant to the RHS.
891 std::swap(Op0, Op1);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000892 }
893
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000894 // fmul X, 1.0 ==> X
895 if (match(Op1, m_FPOne()))
896 return Op0;
897
898 // fmul nnan nsz X, 0 ==> 0
899 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
900 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000901
Craig Topper9f008862014-04-15 04:59:12 +0000902 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000903}
904
Sanjay Patel472cc782016-01-11 22:14:42 +0000905/// Given operands for a Mul, see if we can fold the result.
906/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000907static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
908 unsigned MaxRecurse) {
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000909 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +0000910 if (Constant *CRHS = dyn_cast<Constant>(Op1))
911 return ConstantFoldBinaryOpOperands(Instruction::Mul, CLHS, CRHS, Q.DL);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000912
913 // Canonicalize the constant to the RHS.
914 std::swap(Op0, Op1);
915 }
916
917 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000918 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000919 return Constant::getNullValue(Op0->getType());
920
921 // X * 0 -> 0
922 if (match(Op1, m_Zero()))
923 return Op1;
924
925 // X * 1 -> X
926 if (match(Op1, m_One()))
927 return Op0;
928
Duncan Sandsb67edc62011-01-30 18:03:50 +0000929 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000930 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000931 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
932 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
933 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000934
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000935 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000936 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000937 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000938 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000939
940 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000941 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000942 MaxRecurse))
943 return V;
944
945 // Mul distributes over Add. Try some generic simplifications based on this.
946 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000947 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000948 return V;
949
950 // If the operation is with the result of a select instruction, check whether
951 // operating on either branch of the select always yields the same value.
952 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000953 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000954 MaxRecurse))
955 return V;
956
957 // If the operation is with the result of a phi instruction, check whether
958 // operating on all incoming values of the phi always yields the same value.
959 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000960 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000961 MaxRecurse))
962 return V;
963
Craig Topper9f008862014-04-15 04:59:12 +0000964 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000965}
966
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000967Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000968 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000969 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000970 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000971 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000972 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000973 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000974}
975
976Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000977 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000978 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000979 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000980 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000981 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000982 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000983}
984
Chandler Carruth66b31302015-01-04 12:03:27 +0000985Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000986 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000987 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000988 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000989 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000990 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000991 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000992}
993
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000994Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000995 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000996 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000997 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000998 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000999 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00001000}
1001
Sanjay Patel472cc782016-01-11 22:14:42 +00001002/// Given operands for an SDiv or UDiv, see if we can fold the result.
1003/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001004static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001005 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001006 if (Constant *C0 = dyn_cast<Constant>(Op0))
1007 if (Constant *C1 = dyn_cast<Constant>(Op1))
1008 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands771e82a2011-01-28 16:51:11 +00001009
Duncan Sands65995fa2011-01-28 18:50:50 +00001010 bool isSigned = Opcode == Instruction::SDiv;
1011
Duncan Sands771e82a2011-01-28 16:51:11 +00001012 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001013 if (match(Op1, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001014 return Op1;
1015
David Majnemer71dc8fb2014-12-10 07:52:18 +00001016 // X / 0 -> undef, we don't need to preserve faults!
1017 if (match(Op1, m_Zero()))
1018 return UndefValue::get(Op1->getType());
1019
Duncan Sands771e82a2011-01-28 16:51:11 +00001020 // undef / X -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001021 if (match(Op0, m_Undef()))
Duncan Sands771e82a2011-01-28 16:51:11 +00001022 return Constant::getNullValue(Op0->getType());
1023
1024 // 0 / X -> 0, we don't need to preserve faults!
1025 if (match(Op0, m_Zero()))
1026 return Op0;
1027
1028 // X / 1 -> X
1029 if (match(Op1, m_One()))
1030 return Op0;
Duncan Sands771e82a2011-01-28 16:51:11 +00001031
1032 if (Op0->getType()->isIntegerTy(1))
1033 // It can't be division by zero, hence it must be division by one.
1034 return Op0;
1035
1036 // X / X -> 1
1037 if (Op0 == Op1)
1038 return ConstantInt::get(Op0->getType(), 1);
1039
1040 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001041 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001042 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1043 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001044 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001045 // If the Mul knows it does not overflow, then we are good to go.
1046 if ((isSigned && Mul->hasNoSignedWrap()) ||
1047 (!isSigned && Mul->hasNoUnsignedWrap()))
1048 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001049 // If X has the form X = A / Y then X * Y cannot overflow.
1050 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1051 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1052 return X;
1053 }
1054
Duncan Sands65995fa2011-01-28 18:50:50 +00001055 // (X rem Y) / Y -> 0
1056 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1057 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1058 return Constant::getNullValue(Op0->getType());
1059
David Majnemercb9d5962014-10-11 10:20:01 +00001060 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1061 ConstantInt *C1, *C2;
1062 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1063 match(Op1, m_ConstantInt(C2))) {
1064 bool Overflow;
1065 C1->getValue().umul_ov(C2->getValue(), Overflow);
1066 if (Overflow)
1067 return Constant::getNullValue(Op0->getType());
1068 }
1069
Duncan Sands65995fa2011-01-28 18:50:50 +00001070 // If the operation is with the result of a select instruction, check whether
1071 // operating on either branch of the select always yields the same value.
1072 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001073 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001074 return V;
1075
1076 // If the operation is with the result of a phi instruction, check whether
1077 // operating on all incoming values of the phi always yields the same value.
1078 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001079 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001080 return V;
1081
Craig Topper9f008862014-04-15 04:59:12 +00001082 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001083}
1084
Sanjay Patel472cc782016-01-11 22:14:42 +00001085/// Given operands for an SDiv, see if we can fold the result.
1086/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001087static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1088 unsigned MaxRecurse) {
1089 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001090 return V;
1091
Craig Topper9f008862014-04-15 04:59:12 +00001092 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001093}
1094
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001095Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001096 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001097 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001098 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001099 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001100 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001101}
1102
Sanjay Patel472cc782016-01-11 22:14:42 +00001103/// Given operands for a UDiv, see if we can fold the result.
1104/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001105static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1106 unsigned MaxRecurse) {
1107 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001108 return V;
1109
David Majnemer63da0c22017-01-06 22:58:02 +00001110 // udiv %V, C -> 0 if %V < C
1111 if (MaxRecurse) {
1112 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1113 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1114 if (C->isAllOnesValue()) {
1115 return Constant::getNullValue(Op0->getType());
1116 }
1117 }
1118 }
1119
Craig Topper9f008862014-04-15 04:59:12 +00001120 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001121}
1122
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001123Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001124 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001125 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001126 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001127 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001128 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001129}
1130
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001131static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1132 const Query &Q, unsigned) {
Frits van Bommelc2549662011-01-29 15:26:31 +00001133 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001134 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001135 return Op0;
1136
1137 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001138 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001139 return Op1;
1140
Zia Ansari394cef82016-12-08 23:27:40 +00001141 // X / 1.0 -> X
1142 if (match(Op1, m_FPOne()))
1143 return Op0;
1144
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001145 // 0 / X -> 0
1146 // Requires that NaNs are off (X could be zero) and signed zeroes are
1147 // ignored (X could be positive or negative, so the output sign is unknown).
1148 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1149 return Op0;
1150
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001151 if (FMF.noNaNs()) {
1152 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001153 if (Op0 == Op1)
1154 return ConstantFP::get(Op0->getType(), 1.0);
1155
1156 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001157 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001158 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1159 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1160 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1161 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1162 BinaryOperator::getFNegArgument(Op1) == Op0))
1163 return ConstantFP::get(Op0->getType(), -1.0);
1164 }
1165
Craig Topper9f008862014-04-15 04:59:12 +00001166 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001167}
1168
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001169Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001170 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001171 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001172 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001173 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001174 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001175 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001176}
1177
Sanjay Patel472cc782016-01-11 22:14:42 +00001178/// Given operands for an SRem or URem, see if we can fold the result.
1179/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001180static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001181 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001182 if (Constant *C0 = dyn_cast<Constant>(Op0))
1183 if (Constant *C1 = dyn_cast<Constant>(Op1))
1184 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001185
Duncan Sandsa3e36992011-05-02 16:27:02 +00001186 // X % undef -> undef
1187 if (match(Op1, m_Undef()))
1188 return Op1;
1189
1190 // undef % X -> 0
1191 if (match(Op0, m_Undef()))
1192 return Constant::getNullValue(Op0->getType());
1193
1194 // 0 % X -> 0, we don't need to preserve faults!
1195 if (match(Op0, m_Zero()))
1196 return Op0;
1197
1198 // X % 0 -> undef, we don't need to preserve faults!
1199 if (match(Op1, m_Zero()))
1200 return UndefValue::get(Op0->getType());
1201
1202 // X % 1 -> 0
1203 if (match(Op1, m_One()))
1204 return Constant::getNullValue(Op0->getType());
1205
1206 if (Op0->getType()->isIntegerTy(1))
1207 // It can't be remainder by zero, hence it must be remainder by one.
1208 return Constant::getNullValue(Op0->getType());
1209
1210 // X % X -> 0
1211 if (Op0 == Op1)
1212 return Constant::getNullValue(Op0->getType());
1213
David Majnemerb435a422014-09-17 04:16:35 +00001214 // (X % Y) % Y -> X % Y
1215 if ((Opcode == Instruction::SRem &&
1216 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1217 (Opcode == Instruction::URem &&
1218 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001219 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001220
Duncan Sandsa3e36992011-05-02 16:27:02 +00001221 // If the operation is with the result of a select instruction, check whether
1222 // operating on either branch of the select always yields the same value.
1223 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001224 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001225 return V;
1226
1227 // If the operation is with the result of a phi instruction, check whether
1228 // operating on all incoming values of the phi always yields the same value.
1229 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001230 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001231 return V;
1232
Craig Topper9f008862014-04-15 04:59:12 +00001233 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001234}
1235
Sanjay Patel472cc782016-01-11 22:14:42 +00001236/// Given operands for an SRem, see if we can fold the result.
1237/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001238static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1239 unsigned MaxRecurse) {
1240 if (Value *V = SimplifyRem(Instruction::SRem, 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
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001246Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001247 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001248 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001249 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001250 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001251 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001252}
1253
Sanjay Patel472cc782016-01-11 22:14:42 +00001254/// Given operands for a URem, see if we can fold the result.
1255/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001256static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001257 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001258 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001259 return V;
1260
David Majnemer8c0e62f2017-01-06 21:23:51 +00001261 // urem %V, C -> %V if %V < C
1262 if (MaxRecurse) {
1263 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1264 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1265 if (C->isAllOnesValue()) {
1266 return Op0;
1267 }
1268 }
1269 }
1270
Craig Topper9f008862014-04-15 04:59:12 +00001271 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001272}
1273
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001274Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001275 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001276 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001277 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001278 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001279 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001280}
1281
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001282static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1283 const Query &, unsigned) {
Duncan Sandsa3e36992011-05-02 16:27:02 +00001284 // undef % X -> undef (the undef could be a snan).
1285 if (match(Op0, m_Undef()))
1286 return Op0;
1287
1288 // X % undef -> undef
1289 if (match(Op1, m_Undef()))
1290 return Op1;
1291
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001292 // 0 % X -> 0
1293 // Requires that NaNs are off (X could be zero) and signed zeroes are
1294 // ignored (X could be positive or negative, so the output sign is unknown).
1295 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1296 return Op0;
1297
Craig Topper9f008862014-04-15 04:59:12 +00001298 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001299}
1300
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001301Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001302 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001303 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001304 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001305 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001306 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001307 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001308}
1309
Sanjay Patel472cc782016-01-11 22:14:42 +00001310/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001311static bool isUndefShift(Value *Amount) {
1312 Constant *C = dyn_cast<Constant>(Amount);
1313 if (!C)
1314 return false;
1315
1316 // X shift by undef -> undef because it may shift by the bitwidth.
1317 if (isa<UndefValue>(C))
1318 return true;
1319
1320 // Shifting by the bitwidth or more is undefined.
1321 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1322 if (CI->getValue().getLimitedValue() >=
1323 CI->getType()->getScalarSizeInBits())
1324 return true;
1325
1326 // If all lanes of a vector shift are undefined the whole shift is.
1327 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1328 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1329 if (!isUndefShift(C->getAggregateElement(I)))
1330 return false;
1331 return true;
1332 }
1333
1334 return false;
1335}
1336
Sanjay Patel472cc782016-01-11 22:14:42 +00001337/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1338/// If not, this returns null.
Duncan Sands571fd9a2011-01-14 14:44:12 +00001339static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001340 const Query &Q, unsigned MaxRecurse) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001341 if (Constant *C0 = dyn_cast<Constant>(Op0))
1342 if (Constant *C1 = dyn_cast<Constant>(Op1))
1343 return ConstantFoldBinaryOpOperands(Opcode, C0, C1, Q.DL);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001344
Duncan Sands571fd9a2011-01-14 14:44:12 +00001345 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001346 if (match(Op0, m_Zero()))
1347 return Op0;
1348
Duncan Sands571fd9a2011-01-14 14:44:12 +00001349 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001350 if (match(Op1, m_Zero()))
1351 return Op0;
1352
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001353 // Fold undefined shifts.
1354 if (isUndefShift(Op1))
1355 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001356
Duncan Sands571fd9a2011-01-14 14:44:12 +00001357 // If the operation is with the result of a select instruction, check whether
1358 // operating on either branch of the select always yields the same value.
1359 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001360 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001361 return V;
1362
1363 // If the operation is with the result of a phi instruction, check whether
1364 // operating on all incoming values of the phi always yields the same value.
1365 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001366 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001367 return V;
1368
Sanjay Patel6786bc52016-05-10 20:46:54 +00001369 // If any bits in the shift amount make that value greater than or equal to
1370 // the number of bits in the type, the shift is undefined.
1371 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1372 APInt KnownZero(BitWidth, 0);
1373 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001374 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001375 if (KnownOne.getLimitedValue() >= BitWidth)
1376 return UndefValue::get(Op0->getType());
1377
1378 // If all valid bits in the shift amount are known zero, the first operand is
1379 // unchanged.
1380 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1381 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1382 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1383 return Op0;
1384
Craig Topper9f008862014-04-15 04:59:12 +00001385 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001386}
1387
David Majnemerbf7550e2014-11-05 00:59:59 +00001388/// \brief Given operands for an Shl, LShr or AShr, see if we can
1389/// fold the result. If not, this returns null.
1390static Value *SimplifyRightShift(unsigned Opcode, Value *Op0, Value *Op1,
1391 bool isExact, const Query &Q,
1392 unsigned MaxRecurse) {
1393 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1394 return V;
1395
1396 // X >> X -> 0
1397 if (Op0 == Op1)
1398 return Constant::getNullValue(Op0->getType());
1399
David Majnemer65c52ae2014-12-17 01:54:33 +00001400 // undef >> X -> 0
1401 // undef >> X -> undef (if it's exact)
1402 if (match(Op0, m_Undef()))
1403 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1404
David Majnemerbf7550e2014-11-05 00:59:59 +00001405 // The low bit cannot be shifted out of an exact shift if it is set.
1406 if (isExact) {
1407 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1408 APInt Op0KnownZero(BitWidth, 0);
1409 APInt Op0KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001410 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1411 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001412 if (Op0KnownOne[0])
1413 return Op0;
1414 }
1415
1416 return nullptr;
1417}
1418
Sanjay Patel472cc782016-01-11 22:14:42 +00001419/// Given operands for an Shl, see if we can fold the result.
1420/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001421static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001422 const Query &Q, unsigned MaxRecurse) {
1423 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001424 return V;
1425
1426 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001427 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001428 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001429 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001430
Chris Lattner9e4aa022011-02-09 17:15:04 +00001431 // (X >> A) << A -> X
1432 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001433 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001434 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001435 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001436}
1437
Chris Lattner9e4aa022011-02-09 17:15:04 +00001438Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001439 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001440 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001441 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001442 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001443 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001444}
1445
Sanjay Patel472cc782016-01-11 22:14:42 +00001446/// Given operands for an LShr, see if we can fold the result.
1447/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001448static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001449 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001450 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1451 MaxRecurse))
1452 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001453
Chris Lattner9e4aa022011-02-09 17:15:04 +00001454 // (X << A) >> A -> X
1455 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001456 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001457 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001458
Craig Topper9f008862014-04-15 04:59:12 +00001459 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001460}
1461
Chris Lattner9e4aa022011-02-09 17:15:04 +00001462Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001463 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001464 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001465 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001466 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001467 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001468 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001469}
1470
Sanjay Patel472cc782016-01-11 22:14:42 +00001471/// Given operands for an AShr, see if we can fold the result.
1472/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001473static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001474 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001475 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1476 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001477 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001478
1479 // all ones >>a X -> all ones
1480 if (match(Op0, m_AllOnes()))
1481 return Op0;
1482
Chris Lattner9e4aa022011-02-09 17:15:04 +00001483 // (X << A) >> A -> X
1484 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001485 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001486 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001487
Suyog Sarda68862412014-07-17 06:28:15 +00001488 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001489 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001490 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1491 return Op0;
1492
Craig Topper9f008862014-04-15 04:59:12 +00001493 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001494}
1495
Chris Lattner9e4aa022011-02-09 17:15:04 +00001496Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001497 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001498 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001499 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001500 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001501 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001502 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001503}
1504
David Majnemer1af36e52014-12-06 10:51:40 +00001505static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1506 ICmpInst *UnsignedICmp, bool IsAnd) {
1507 Value *X, *Y;
1508
1509 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001510 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1511 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001512 return nullptr;
1513
1514 ICmpInst::Predicate UnsignedPred;
1515 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1516 ICmpInst::isUnsigned(UnsignedPred))
1517 ;
1518 else if (match(UnsignedICmp,
1519 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1520 ICmpInst::isUnsigned(UnsignedPred))
1521 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1522 else
1523 return nullptr;
1524
1525 // X < Y && Y != 0 --> X < Y
1526 // X < Y || Y != 0 --> Y != 0
1527 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1528 return IsAnd ? UnsignedICmp : ZeroICmp;
1529
1530 // X >= Y || Y != 0 --> true
1531 // X >= Y || Y == 0 --> X >= Y
1532 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1533 if (EqPred == ICmpInst::ICMP_NE)
1534 return getTrue(UnsignedICmp->getType());
1535 return UnsignedICmp;
1536 }
1537
David Majnemerd5b3aa42014-12-08 18:30:43 +00001538 // X < Y && Y == 0 --> false
1539 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1540 IsAnd)
1541 return getFalse(UnsignedICmp->getType());
1542
David Majnemer1af36e52014-12-06 10:51:40 +00001543 return nullptr;
1544}
1545
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001546/// Commuted variants are assumed to be handled by calling this function again
1547/// with the parameters swapped.
1548static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1549 ICmpInst::Predicate Pred0, Pred1;
1550 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001551 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1552 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001553 return nullptr;
1554
1555 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1556 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1557 // can eliminate Op1 from this 'and'.
1558 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1559 return Op0;
1560
1561 // Check for any combination of predicates that are guaranteed to be disjoint.
1562 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1563 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1564 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1565 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1566 return getFalse(Op0->getType());
1567
1568 return nullptr;
1569}
1570
1571/// Commuted variants are assumed to be handled by calling this function again
1572/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001573static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001574 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1575 return X;
1576
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001577 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1578 return X;
1579
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001580 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001581 Type *ITy = Op0->getType();
1582 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001583 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001584 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001585 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1586 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1587 // Make a constant range that's the intersection of the two icmp ranges.
1588 // If the intersection is empty, we know that the result is false.
1589 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1590 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1591 if (Range0.intersectWith(Range1).isEmptySet())
1592 return getFalse(ITy);
1593 }
1594
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001595 // (icmp (add V, C0), C1) & (icmp V, C0)
1596 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001597 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001598
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001599 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001600 return nullptr;
1601
David Majnemera315bd82014-09-15 08:15:28 +00001602 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001603 if (AddInst->getOperand(1) != Op1->getOperand(1))
1604 return nullptr;
1605
David Majnemera315bd82014-09-15 08:15:28 +00001606 bool isNSW = AddInst->hasNoSignedWrap();
1607 bool isNUW = AddInst->hasNoUnsignedWrap();
1608
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001609 const APInt Delta = *C1 - *C0;
1610 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001611 if (Delta == 2) {
1612 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1613 return getFalse(ITy);
1614 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1615 return getFalse(ITy);
1616 }
1617 if (Delta == 1) {
1618 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1619 return getFalse(ITy);
1620 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1621 return getFalse(ITy);
1622 }
1623 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001624 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001625 if (Delta == 2)
1626 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1627 return getFalse(ITy);
1628 if (Delta == 1)
1629 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1630 return getFalse(ITy);
1631 }
1632
1633 return nullptr;
1634}
1635
Sanjay Patel472cc782016-01-11 22:14:42 +00001636/// Given operands for an And, see if we can fold the result.
1637/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001638static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001639 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001640 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001641 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1642 return ConstantFoldBinaryOpOperands(Instruction::And, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001643
Chris Lattnera71e9d62009-11-10 00:55:12 +00001644 // Canonicalize the constant to the RHS.
1645 std::swap(Op0, Op1);
1646 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001647
Chris Lattnera71e9d62009-11-10 00:55:12 +00001648 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001649 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001650 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001651
Chris Lattnera71e9d62009-11-10 00:55:12 +00001652 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001653 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001654 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001655
Duncan Sandsc89ac072010-11-17 18:52:15 +00001656 // X & 0 = 0
1657 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001658 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001659
Duncan Sandsc89ac072010-11-17 18:52:15 +00001660 // X & -1 = X
1661 if (match(Op1, m_AllOnes()))
1662 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001663
Chris Lattnera71e9d62009-11-10 00:55:12 +00001664 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001665 if (match(Op0, m_Not(m_Specific(Op1))) ||
1666 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001667 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001668
Chris Lattnera71e9d62009-11-10 00:55:12 +00001669 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001670 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001671 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001672 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001673 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001674
Chris Lattnera71e9d62009-11-10 00:55:12 +00001675 // A & (A | ?) = A
1676 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001677 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001678 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001679
Duncan Sandsba286d72011-10-26 20:55:21 +00001680 // A & (-A) = A if A is a power of two or zero.
1681 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1682 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001683 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1684 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001685 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001686 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1687 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001688 return Op1;
1689 }
1690
David Majnemera315bd82014-09-15 08:15:28 +00001691 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1692 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1693 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1694 return V;
1695 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1696 return V;
1697 }
1698 }
1699
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001700 // The compares may be hidden behind casts. Look through those and try the
1701 // same folds as above.
1702 auto *Cast0 = dyn_cast<CastInst>(Op0);
1703 auto *Cast1 = dyn_cast<CastInst>(Op1);
1704 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1705 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1706 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1707 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1708 if (Cmp0 && Cmp1) {
1709 Instruction::CastOps CastOpc = Cast0->getOpcode();
1710 Type *ResultType = Cast0->getType();
1711 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1712 return ConstantExpr::getCast(CastOpc, V, ResultType);
1713 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1714 return ConstantExpr::getCast(CastOpc, V, ResultType);
1715 }
1716 }
1717
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001718 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001719 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1720 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001721 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001722
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001723 // And distributes over Or. Try some generic simplifications based on this.
1724 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001725 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001726 return V;
1727
1728 // And distributes over Xor. Try some generic simplifications based on this.
1729 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001730 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001731 return V;
1732
Duncan Sandsb0579e92010-11-10 13:00:08 +00001733 // If the operation is with the result of a select instruction, check whether
1734 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001735 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001736 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1737 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001738 return V;
1739
1740 // If the operation is with the result of a phi instruction, check whether
1741 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001742 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001743 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001744 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001745 return V;
1746
Craig Topper9f008862014-04-15 04:59:12 +00001747 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001748}
1749
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001750Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001751 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001752 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001753 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001754 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001755 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001756}
1757
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001758/// Commuted variants are assumed to be handled by calling this function again
1759/// with the parameters swapped.
1760static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1761 ICmpInst::Predicate Pred0, Pred1;
1762 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001763 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1764 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001765 return nullptr;
1766
1767 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1768 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1769 // can eliminate Op0 from this 'or'.
1770 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1771 return Op1;
1772
1773 // Check for any combination of predicates that cover the entire range of
1774 // possibilities.
1775 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1776 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1777 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1778 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1779 return getTrue(Op0->getType());
1780
1781 return nullptr;
1782}
1783
1784/// Commuted variants are assumed to be handled by calling this function again
1785/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001786static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001787 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1788 return X;
1789
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001790 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1791 return X;
1792
Sanjay Patel220a8732016-09-28 14:27:21 +00001793 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001794 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001795 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001796 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001797 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001798 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001799
Sanjay Patel220a8732016-09-28 14:27:21 +00001800 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1801 return nullptr;
1802
1803 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1804 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001805 return nullptr;
1806
1807 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001808 bool isNSW = AddInst->hasNoSignedWrap();
1809 bool isNUW = AddInst->hasNoUnsignedWrap();
1810
Sanjay Patel220a8732016-09-28 14:27:21 +00001811 const APInt Delta = *C1 - *C0;
1812 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001813 if (Delta == 2) {
1814 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1815 return getTrue(ITy);
1816 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1817 return getTrue(ITy);
1818 }
1819 if (Delta == 1) {
1820 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1821 return getTrue(ITy);
1822 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1823 return getTrue(ITy);
1824 }
1825 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001826 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001827 if (Delta == 2)
1828 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1829 return getTrue(ITy);
1830 if (Delta == 1)
1831 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1832 return getTrue(ITy);
1833 }
1834
1835 return nullptr;
1836}
1837
Sanjay Patel472cc782016-01-11 22:14:42 +00001838/// Given operands for an Or, see if we can fold the result.
1839/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001840static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1841 unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00001842 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001843 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1844 return ConstantFoldBinaryOpOperands(Instruction::Or, CLHS, CRHS, Q.DL);
Duncan Sands7e800d62010-11-14 11:23:23 +00001845
Chris Lattnera71e9d62009-11-10 00:55:12 +00001846 // Canonicalize the constant to the RHS.
1847 std::swap(Op0, Op1);
1848 }
Duncan Sands7e800d62010-11-14 11:23:23 +00001849
Chris Lattnera71e9d62009-11-10 00:55:12 +00001850 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001851 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001852 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001853
Chris Lattnera71e9d62009-11-10 00:55:12 +00001854 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001855 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001856 return Op0;
1857
Duncan Sandsc89ac072010-11-17 18:52:15 +00001858 // X | 0 = X
1859 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001860 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001861
Duncan Sandsc89ac072010-11-17 18:52:15 +00001862 // X | -1 = -1
1863 if (match(Op1, m_AllOnes()))
1864 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001865
Chris Lattnera71e9d62009-11-10 00:55:12 +00001866 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001867 if (match(Op0, m_Not(m_Specific(Op1))) ||
1868 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001869 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001870
Chris Lattnera71e9d62009-11-10 00:55:12 +00001871 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001872 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001873 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001874 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001875 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001876
Chris Lattnera71e9d62009-11-10 00:55:12 +00001877 // A | (A & ?) = A
1878 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001879 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001880 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001881
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001882 // ~(A & ?) | A = -1
1883 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1884 (A == Op1 || B == Op1))
1885 return Constant::getAllOnesValue(Op1->getType());
1886
1887 // A | ~(A & ?) = -1
1888 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1889 (A == Op0 || B == Op0))
1890 return Constant::getAllOnesValue(Op0->getType());
1891
David Majnemera315bd82014-09-15 08:15:28 +00001892 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1893 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1894 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1895 return V;
1896 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1897 return V;
1898 }
1899 }
1900
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001901 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001902 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1903 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001904 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001905
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001906 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001907 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1908 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001909 return V;
1910
Duncan Sandsb0579e92010-11-10 13:00:08 +00001911 // If the operation is with the result of a select instruction, check whether
1912 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001913 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001914 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001915 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001916 return V;
1917
Nick Lewycky8561a492014-06-19 03:51:46 +00001918 // (A & C)|(B & D)
1919 Value *C = nullptr, *D = nullptr;
1920 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1921 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1922 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1923 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1924 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1925 // (A & C1)|(B & C2)
1926 // If we have: ((V + N) & C1) | (V & C2)
1927 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1928 // replace with V+N.
1929 Value *V1, *V2;
1930 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1931 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1932 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001933 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001934 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001935 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001936 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001937 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001938 return A;
1939 }
1940 // Or commutes, try both ways.
1941 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1942 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1943 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001944 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001945 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001946 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001947 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001948 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001949 return B;
1950 }
1951 }
1952 }
1953
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001954 // If the operation is with the result of a phi instruction, check whether
1955 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001956 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001957 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001958 return V;
1959
Craig Topper9f008862014-04-15 04:59:12 +00001960 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001961}
1962
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001963Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001964 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001965 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001966 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001967 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001968 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001969}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001970
Sanjay Patel472cc782016-01-11 22:14:42 +00001971/// Given operands for a Xor, see if we can fold the result.
1972/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001973static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1974 unsigned MaxRecurse) {
Duncan Sandsc89ac072010-11-17 18:52:15 +00001975 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
Manuel Jacoba61ca372016-01-21 06:26:35 +00001976 if (Constant *CRHS = dyn_cast<Constant>(Op1))
1977 return ConstantFoldBinaryOpOperands(Instruction::Xor, CLHS, CRHS, Q.DL);
Duncan Sandsc89ac072010-11-17 18:52:15 +00001978
1979 // Canonicalize the constant to the RHS.
1980 std::swap(Op0, Op1);
1981 }
1982
1983 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001984 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001985 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001986
1987 // A ^ 0 = A
1988 if (match(Op1, m_Zero()))
1989 return Op0;
1990
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001991 // A ^ A = 0
1992 if (Op0 == Op1)
1993 return Constant::getNullValue(Op0->getType());
1994
Duncan Sandsc89ac072010-11-17 18:52:15 +00001995 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001996 if (match(Op0, m_Not(m_Specific(Op1))) ||
1997 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001998 return Constant::getAllOnesValue(Op0->getType());
1999
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002000 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00002001 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
2002 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00002003 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002004
Duncan Sandsb238de02010-11-19 09:20:39 +00002005 // Threading Xor over selects and phi nodes is pointless, so don't bother.
2006 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
2007 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
2008 // only if B and C are equal. If B and C are equal then (since we assume
2009 // that operands have already been simplified) "select(cond, B, C)" should
2010 // have been simplified to the common value of B and C already. Analysing
2011 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
2012 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00002013
Craig Topper9f008862014-04-15 04:59:12 +00002014 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002015}
2016
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002017Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002018 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002019 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00002020 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002021 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00002022 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00002023}
2024
Chris Lattner229907c2011-07-18 04:54:35 +00002025static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002026 return CmpInst::makeCmpResultType(Op->getType());
2027}
2028
Sanjay Patel472cc782016-01-11 22:14:42 +00002029/// Rummage around inside V looking for something equivalent to the comparison
2030/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2031/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002032static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2033 Value *LHS, Value *RHS) {
2034 SelectInst *SI = dyn_cast<SelectInst>(V);
2035 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002036 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002037 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2038 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002039 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002040 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2041 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2042 return Cmp;
2043 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2044 LHS == CmpRHS && RHS == CmpLHS)
2045 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002046 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002047}
2048
Dan Gohman9631d902013-02-01 00:49:06 +00002049// A significant optimization not implemented here is assuming that alloca
2050// addresses are not equal to incoming argument values. They don't *alias*,
2051// as we say, but that doesn't mean they aren't equal, so we take a
2052// conservative approach.
2053//
2054// This is inspired in part by C++11 5.10p1:
2055// "Two pointers of the same type compare equal if and only if they are both
2056// null, both point to the same function, or both represent the same
2057// address."
2058//
2059// This is pretty permissive.
2060//
2061// It's also partly due to C11 6.5.9p6:
2062// "Two pointers compare equal if and only if both are null pointers, both are
2063// pointers to the same object (including a pointer to an object and a
2064// subobject at its beginning) or function, both are pointers to one past the
2065// last element of the same array object, or one is a pointer to one past the
2066// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002067// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002068// object in the address space.)
2069//
2070// C11's version is more restrictive, however there's no reason why an argument
2071// couldn't be a one-past-the-end value for a stack object in the caller and be
2072// equal to the beginning of a stack object in the callee.
2073//
2074// If the C and C++ standards are ever made sufficiently restrictive in this
2075// area, it may be possible to update LLVM's semantics accordingly and reinstate
2076// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002077static Constant *
2078computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2079 const DominatorTree *DT, CmpInst::Predicate Pred,
2080 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002081 // First, skip past any trivial no-ops.
2082 LHS = LHS->stripPointerCasts();
2083 RHS = RHS->stripPointerCasts();
2084
2085 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002086 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002087 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2088 return ConstantInt::get(GetCompareTy(LHS),
2089 !CmpInst::isTrueWhenEqual(Pred));
2090
Chandler Carruth8059c842012-03-25 21:28:14 +00002091 // We can only fold certain predicates on pointer comparisons.
2092 switch (Pred) {
2093 default:
Craig Topper9f008862014-04-15 04:59:12 +00002094 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002095
2096 // Equality comaprisons are easy to fold.
2097 case CmpInst::ICMP_EQ:
2098 case CmpInst::ICMP_NE:
2099 break;
2100
2101 // We can only handle unsigned relational comparisons because 'inbounds' on
2102 // a GEP only protects against unsigned wrapping.
2103 case CmpInst::ICMP_UGT:
2104 case CmpInst::ICMP_UGE:
2105 case CmpInst::ICMP_ULT:
2106 case CmpInst::ICMP_ULE:
2107 // However, we have to switch them to their signed variants to handle
2108 // negative indices from the base pointer.
2109 Pred = ICmpInst::getSignedPredicate(Pred);
2110 break;
2111 }
2112
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002113 // Strip off any constant offsets so that we can reason about them.
2114 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2115 // here and compare base addresses like AliasAnalysis does, however there are
2116 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2117 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2118 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002119 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2120 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002121
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002122 // If LHS and RHS are related via constant offsets to the same base
2123 // value, we can replace it with an icmp which just compares the offsets.
2124 if (LHS == RHS)
2125 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002126
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002127 // Various optimizations for (in)equality comparisons.
2128 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2129 // Different non-empty allocations that exist at the same time have
2130 // different addresses (if the program can tell). Global variables always
2131 // exist, so they always exist during the lifetime of each other and all
2132 // allocas. Two different allocas usually have different addresses...
2133 //
2134 // However, if there's an @llvm.stackrestore dynamically in between two
2135 // allocas, they may have the same address. It's tempting to reduce the
2136 // scope of the problem by only looking at *static* allocas here. That would
2137 // cover the majority of allocas while significantly reducing the likelihood
2138 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2139 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2140 // an entry block. Also, if we have a block that's not attached to a
2141 // function, we can't tell if it's "static" under the current definition.
2142 // Theoretically, this problem could be fixed by creating a new kind of
2143 // instruction kind specifically for static allocas. Such a new instruction
2144 // could be required to be at the top of the entry block, thus preventing it
2145 // from being subject to a @llvm.stackrestore. Instcombine could even
2146 // convert regular allocas into these special allocas. It'd be nifty.
2147 // However, until then, this problem remains open.
2148 //
2149 // So, we'll assume that two non-empty allocas have different addresses
2150 // for now.
2151 //
2152 // With all that, if the offsets are within the bounds of their allocations
2153 // (and not one-past-the-end! so we can't use inbounds!), and their
2154 // allocations aren't the same, the pointers are not equal.
2155 //
2156 // Note that it's not necessary to check for LHS being a global variable
2157 // address, due to canonicalization and constant folding.
2158 if (isa<AllocaInst>(LHS) &&
2159 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002160 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2161 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002162 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002163 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002164 getObjectSize(LHS, LHSSize, DL, TLI) &&
2165 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002166 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2167 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002168 if (!LHSOffsetValue.isNegative() &&
2169 !RHSOffsetValue.isNegative() &&
2170 LHSOffsetValue.ult(LHSSize) &&
2171 RHSOffsetValue.ult(RHSSize)) {
2172 return ConstantInt::get(GetCompareTy(LHS),
2173 !CmpInst::isTrueWhenEqual(Pred));
2174 }
2175 }
2176
2177 // Repeat the above check but this time without depending on DataLayout
2178 // or being able to compute a precise size.
2179 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2180 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2181 LHSOffset->isNullValue() &&
2182 RHSOffset->isNullValue())
2183 return ConstantInt::get(GetCompareTy(LHS),
2184 !CmpInst::isTrueWhenEqual(Pred));
2185 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002186
2187 // Even if an non-inbounds GEP occurs along the path we can still optimize
2188 // equality comparisons concerning the result. We avoid walking the whole
2189 // chain again by starting where the last calls to
2190 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002191 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2192 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002193 if (LHS == RHS)
2194 return ConstantExpr::getICmp(Pred,
2195 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2196 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002197
2198 // If one side of the equality comparison must come from a noalias call
2199 // (meaning a system memory allocation function), and the other side must
2200 // come from a pointer that cannot overlap with dynamically-allocated
2201 // memory within the lifetime of the current function (allocas, byval
2202 // arguments, globals), then determine the comparison result here.
2203 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2204 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2205 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2206
2207 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002208 auto IsNAC = [](ArrayRef<Value *> Objects) {
2209 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002210 };
2211
2212 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002213 // noalias calls. For allocas, we consider only static ones (dynamic
2214 // allocas might be transformed into calls to malloc not simultaneously
2215 // live with the compared-to allocation). For globals, we exclude symbols
2216 // that might be resolve lazily to symbols in another dynamically-loaded
2217 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002218 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2219 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002220 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2221 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2222 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2223 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002224 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002225 !GV->isThreadLocal();
2226 if (const Argument *A = dyn_cast<Argument>(V))
2227 return A->hasByValAttr();
2228 return false;
2229 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002230 };
2231
2232 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2233 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2234 return ConstantInt::get(GetCompareTy(LHS),
2235 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002236
2237 // Fold comparisons for non-escaping pointer even if the allocation call
2238 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2239 // dynamic allocation call could be either of the operands.
2240 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002241 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002242 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002243 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002244 MI = RHS;
2245 // FIXME: We should also fold the compare when the pointer escapes, but the
2246 // compare dominates the pointer escape
2247 if (MI && !PointerMayBeCaptured(MI, true, true))
2248 return ConstantInt::get(GetCompareTy(LHS),
2249 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002250 }
2251
2252 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002253 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002254}
Chris Lattner01990f02012-02-24 19:01:58 +00002255
Sanjay Pateldc65a272016-12-03 17:30:22 +00002256/// Fold an icmp when its operands have i1 scalar type.
2257static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2258 Value *RHS, const Query &Q) {
2259 Type *ITy = GetCompareTy(LHS); // The return type.
2260 Type *OpTy = LHS->getType(); // The operand type.
2261 if (!OpTy->getScalarType()->isIntegerTy(1))
2262 return nullptr;
2263
2264 switch (Pred) {
2265 default:
2266 break;
2267 case ICmpInst::ICMP_EQ:
2268 // X == 1 -> X
2269 if (match(RHS, m_One()))
2270 return LHS;
2271 break;
2272 case ICmpInst::ICMP_NE:
2273 // X != 0 -> X
2274 if (match(RHS, m_Zero()))
2275 return LHS;
2276 break;
2277 case ICmpInst::ICMP_UGT:
2278 // X >u 0 -> X
2279 if (match(RHS, m_Zero()))
2280 return LHS;
2281 break;
2282 case ICmpInst::ICMP_UGE:
2283 // X >=u 1 -> X
2284 if (match(RHS, m_One()))
2285 return LHS;
2286 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2287 return getTrue(ITy);
2288 break;
2289 case ICmpInst::ICMP_SGE:
2290 /// For signed comparison, the values for an i1 are 0 and -1
2291 /// respectively. This maps into a truth table of:
2292 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2293 /// 0 | 0 | 1 (0 >= 0) | 1
2294 /// 0 | 1 | 1 (0 >= -1) | 1
2295 /// 1 | 0 | 0 (-1 >= 0) | 0
2296 /// 1 | 1 | 1 (-1 >= -1) | 1
2297 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2298 return getTrue(ITy);
2299 break;
2300 case ICmpInst::ICMP_SLT:
2301 // X <s 0 -> X
2302 if (match(RHS, m_Zero()))
2303 return LHS;
2304 break;
2305 case ICmpInst::ICMP_SLE:
2306 // X <=s -1 -> X
2307 if (match(RHS, m_One()))
2308 return LHS;
2309 break;
2310 case ICmpInst::ICMP_ULE:
2311 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2312 return getTrue(ITy);
2313 break;
2314 }
2315
2316 return nullptr;
2317}
2318
2319/// Try hard to fold icmp with zero RHS because this is a common case.
2320static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2321 Value *RHS, const Query &Q) {
2322 if (!match(RHS, m_Zero()))
2323 return nullptr;
2324
2325 Type *ITy = GetCompareTy(LHS); // The return type.
2326 bool LHSKnownNonNegative, LHSKnownNegative;
2327 switch (Pred) {
2328 default:
2329 llvm_unreachable("Unknown ICmp predicate!");
2330 case ICmpInst::ICMP_ULT:
2331 return getFalse(ITy);
2332 case ICmpInst::ICMP_UGE:
2333 return getTrue(ITy);
2334 case ICmpInst::ICMP_EQ:
2335 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002336 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002337 return getFalse(ITy);
2338 break;
2339 case ICmpInst::ICMP_NE:
2340 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002341 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002342 return getTrue(ITy);
2343 break;
2344 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002345 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2346 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002347 if (LHSKnownNegative)
2348 return getTrue(ITy);
2349 if (LHSKnownNonNegative)
2350 return getFalse(ITy);
2351 break;
2352 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002353 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2354 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002355 if (LHSKnownNegative)
2356 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002357 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002358 return getFalse(ITy);
2359 break;
2360 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002361 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2362 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002363 if (LHSKnownNegative)
2364 return getFalse(ITy);
2365 if (LHSKnownNonNegative)
2366 return getTrue(ITy);
2367 break;
2368 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002369 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2370 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002371 if (LHSKnownNegative)
2372 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002373 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002374 return getTrue(ITy);
2375 break;
2376 }
2377
2378 return nullptr;
2379}
2380
Sanjay Patelbe332132017-01-23 18:22:26 +00002381/// Many binary operators with a constant operand have an easy-to-compute
2382/// range of outputs. This can be used to fold a comparison to always true or
2383/// always false.
2384static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2385 unsigned Width = Lower.getBitWidth();
2386 const APInt *C;
2387 switch (BO.getOpcode()) {
2388 case Instruction::Add:
Sanjay Patel56227252017-01-24 17:03:24 +00002389 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2390 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2391 if (BO.hasNoUnsignedWrap()) {
2392 // 'add nuw x, C' produces [C, UINT_MAX].
2393 Lower = *C;
2394 } else if (BO.hasNoSignedWrap()) {
2395 if (C->isNegative()) {
2396 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2397 Lower = APInt::getSignedMinValue(Width);
2398 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2399 } else {
2400 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2401 Lower = APInt::getSignedMinValue(Width) + *C;
2402 Upper = APInt::getSignedMaxValue(Width) + 1;
2403 }
2404 }
2405 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002406 break;
2407
2408 case Instruction::And:
2409 if (match(BO.getOperand(1), m_APInt(C)))
2410 // 'and x, C' produces [0, C].
2411 Upper = *C + 1;
2412 break;
2413
2414 case Instruction::Or:
2415 if (match(BO.getOperand(1), m_APInt(C)))
2416 // 'or x, C' produces [C, UINT_MAX].
2417 Lower = *C;
2418 break;
2419
2420 case Instruction::AShr:
2421 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2422 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2423 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2424 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2425 } else if (match(BO.getOperand(0), m_APInt(C))) {
2426 unsigned ShiftAmount = Width - 1;
2427 if (*C != 0 && BO.isExact())
2428 ShiftAmount = C->countTrailingZeros();
2429 if (C->isNegative()) {
2430 // 'ashr C, x' produces [C, C >> (Width-1)]
2431 Lower = *C;
2432 Upper = C->ashr(ShiftAmount) + 1;
2433 } else {
2434 // 'ashr C, x' produces [C >> (Width-1), C]
2435 Lower = C->ashr(ShiftAmount);
2436 Upper = *C + 1;
2437 }
2438 }
2439 break;
2440
2441 case Instruction::LShr:
2442 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2443 // 'lshr x, C' produces [0, UINT_MAX >> C].
2444 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2445 } else if (match(BO.getOperand(0), m_APInt(C))) {
2446 // 'lshr C, x' produces [C >> (Width-1), C].
2447 unsigned ShiftAmount = Width - 1;
2448 if (*C != 0 && BO.isExact())
2449 ShiftAmount = C->countTrailingZeros();
2450 Lower = C->lshr(ShiftAmount);
2451 Upper = *C + 1;
2452 }
2453 break;
2454
2455 case Instruction::Shl:
2456 if (match(BO.getOperand(0), m_APInt(C))) {
2457 if (BO.hasNoUnsignedWrap()) {
2458 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2459 Lower = *C;
2460 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2461 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2462 if (C->isNegative()) {
2463 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2464 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2465 Lower = C->shl(ShiftAmount);
2466 Upper = *C + 1;
2467 } else {
2468 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2469 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2470 Lower = *C;
2471 Upper = C->shl(ShiftAmount) + 1;
2472 }
2473 }
2474 }
2475 break;
2476
2477 case Instruction::SDiv:
2478 if (match(BO.getOperand(1), m_APInt(C))) {
2479 APInt IntMin = APInt::getSignedMinValue(Width);
2480 APInt IntMax = APInt::getSignedMaxValue(Width);
2481 if (C->isAllOnesValue()) {
2482 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2483 // where C != -1 and C != 0 and C != 1
2484 Lower = IntMin + 1;
2485 Upper = IntMax + 1;
2486 } else if (C->countLeadingZeros() < Width - 1) {
2487 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2488 // where C != -1 and C != 0 and C != 1
2489 Lower = IntMin.sdiv(*C);
2490 Upper = IntMax.sdiv(*C);
2491 if (Lower.sgt(Upper))
2492 std::swap(Lower, Upper);
2493 Upper = Upper + 1;
2494 assert(Upper != Lower && "Upper part of range has wrapped!");
2495 }
2496 } else if (match(BO.getOperand(0), m_APInt(C))) {
2497 if (C->isMinSignedValue()) {
2498 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2499 Lower = *C;
2500 Upper = Lower.lshr(1) + 1;
2501 } else {
2502 // 'sdiv C, x' produces [-|C|, |C|].
2503 Upper = C->abs() + 1;
2504 Lower = (-Upper) + 1;
2505 }
2506 }
2507 break;
2508
2509 case Instruction::UDiv:
2510 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2511 // 'udiv x, C' produces [0, UINT_MAX / C].
2512 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2513 } else if (match(BO.getOperand(0), m_APInt(C))) {
2514 // 'udiv C, x' produces [0, C].
2515 Upper = *C + 1;
2516 }
2517 break;
2518
2519 case Instruction::SRem:
2520 if (match(BO.getOperand(1), m_APInt(C))) {
2521 // 'srem x, C' produces (-|C|, |C|).
2522 Upper = C->abs();
2523 Lower = (-Upper) + 1;
2524 }
2525 break;
2526
2527 case Instruction::URem:
2528 if (match(BO.getOperand(1), m_APInt(C)))
2529 // 'urem x, C' produces [0, C).
2530 Upper = *C;
2531 break;
2532
2533 default:
2534 break;
2535 }
2536}
2537
Sanjay Patel67bde282016-08-22 23:12:02 +00002538static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2539 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002540 const APInt *C;
2541 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002542 return nullptr;
2543
2544 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002545 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002546 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002547 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002548 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002549 return ConstantInt::getTrue(GetCompareTy(RHS));
2550
Sanjay Patelbe332132017-01-23 18:22:26 +00002551 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002552 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002553 APInt Lower = APInt(Width, 0);
2554 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002555 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2556 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002557
2558 ConstantRange LHS_CR =
2559 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2560
2561 if (auto *I = dyn_cast<Instruction>(LHS))
2562 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2563 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2564
2565 if (!LHS_CR.isFullSet()) {
2566 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002567 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002568 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002569 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002570 }
2571
2572 return nullptr;
2573}
2574
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002575static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2576 Value *RHS, const Query &Q,
2577 unsigned MaxRecurse) {
2578 Type *ITy = GetCompareTy(LHS); // The return type.
2579
2580 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2581 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2582 if (MaxRecurse && (LBO || RBO)) {
2583 // Analyze the case when either LHS or RHS is an add instruction.
2584 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2585 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2586 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2587 if (LBO && LBO->getOpcode() == Instruction::Add) {
2588 A = LBO->getOperand(0);
2589 B = LBO->getOperand(1);
2590 NoLHSWrapProblem =
2591 ICmpInst::isEquality(Pred) ||
2592 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2593 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2594 }
2595 if (RBO && RBO->getOpcode() == Instruction::Add) {
2596 C = RBO->getOperand(0);
2597 D = RBO->getOperand(1);
2598 NoRHSWrapProblem =
2599 ICmpInst::isEquality(Pred) ||
2600 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2601 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2602 }
2603
2604 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2605 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2606 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2607 Constant::getNullValue(RHS->getType()), Q,
2608 MaxRecurse - 1))
2609 return V;
2610
2611 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2612 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2613 if (Value *V =
2614 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2615 C == LHS ? D : C, Q, MaxRecurse - 1))
2616 return V;
2617
2618 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2619 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2620 NoRHSWrapProblem) {
2621 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2622 Value *Y, *Z;
2623 if (A == C) {
2624 // C + B == C + D -> B == D
2625 Y = B;
2626 Z = D;
2627 } else if (A == D) {
2628 // D + B == C + D -> B == C
2629 Y = B;
2630 Z = C;
2631 } else if (B == C) {
2632 // A + C == C + D -> A == D
2633 Y = A;
2634 Z = D;
2635 } else {
2636 assert(B == D);
2637 // A + D == C + D -> A == C
2638 Y = A;
2639 Z = C;
2640 }
2641 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2642 return V;
2643 }
2644 }
2645
2646 {
2647 Value *Y = nullptr;
2648 // icmp pred (or X, Y), X
2649 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2650 if (Pred == ICmpInst::ICMP_ULT)
2651 return getFalse(ITy);
2652 if (Pred == ICmpInst::ICMP_UGE)
2653 return getTrue(ITy);
2654
2655 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2656 bool RHSKnownNonNegative, RHSKnownNegative;
2657 bool YKnownNonNegative, YKnownNegative;
2658 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002659 Q.AC, Q.CxtI, Q.DT);
2660 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002661 Q.CxtI, Q.DT);
2662 if (RHSKnownNonNegative && YKnownNegative)
2663 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2664 if (RHSKnownNegative || YKnownNonNegative)
2665 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2666 }
2667 }
2668 // icmp pred X, (or X, Y)
2669 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2670 if (Pred == ICmpInst::ICMP_ULE)
2671 return getTrue(ITy);
2672 if (Pred == ICmpInst::ICMP_UGT)
2673 return getFalse(ITy);
2674
2675 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2676 bool LHSKnownNonNegative, LHSKnownNegative;
2677 bool YKnownNonNegative, YKnownNegative;
2678 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002679 Q.AC, Q.CxtI, Q.DT);
2680 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002681 Q.CxtI, Q.DT);
2682 if (LHSKnownNonNegative && YKnownNegative)
2683 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2684 if (LHSKnownNegative || YKnownNonNegative)
2685 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2686 }
2687 }
2688 }
2689
2690 // icmp pred (and X, Y), X
2691 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2692 m_And(m_Specific(RHS), m_Value())))) {
2693 if (Pred == ICmpInst::ICMP_UGT)
2694 return getFalse(ITy);
2695 if (Pred == ICmpInst::ICMP_ULE)
2696 return getTrue(ITy);
2697 }
2698 // icmp pred X, (and X, Y)
2699 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2700 m_And(m_Specific(LHS), m_Value())))) {
2701 if (Pred == ICmpInst::ICMP_UGE)
2702 return getTrue(ITy);
2703 if (Pred == ICmpInst::ICMP_ULT)
2704 return getFalse(ITy);
2705 }
2706
2707 // 0 - (zext X) pred C
2708 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2709 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2710 if (RHSC->getValue().isStrictlyPositive()) {
2711 if (Pred == ICmpInst::ICMP_SLT)
2712 return ConstantInt::getTrue(RHSC->getContext());
2713 if (Pred == ICmpInst::ICMP_SGE)
2714 return ConstantInt::getFalse(RHSC->getContext());
2715 if (Pred == ICmpInst::ICMP_EQ)
2716 return ConstantInt::getFalse(RHSC->getContext());
2717 if (Pred == ICmpInst::ICMP_NE)
2718 return ConstantInt::getTrue(RHSC->getContext());
2719 }
2720 if (RHSC->getValue().isNonNegative()) {
2721 if (Pred == ICmpInst::ICMP_SLE)
2722 return ConstantInt::getTrue(RHSC->getContext());
2723 if (Pred == ICmpInst::ICMP_SGT)
2724 return ConstantInt::getFalse(RHSC->getContext());
2725 }
2726 }
2727 }
2728
2729 // icmp pred (urem X, Y), Y
2730 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2731 bool KnownNonNegative, KnownNegative;
2732 switch (Pred) {
2733 default:
2734 break;
2735 case ICmpInst::ICMP_SGT:
2736 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002737 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2738 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002739 if (!KnownNonNegative)
2740 break;
2741 LLVM_FALLTHROUGH;
2742 case ICmpInst::ICMP_EQ:
2743 case ICmpInst::ICMP_UGT:
2744 case ICmpInst::ICMP_UGE:
2745 return getFalse(ITy);
2746 case ICmpInst::ICMP_SLT:
2747 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002748 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2749 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002750 if (!KnownNonNegative)
2751 break;
2752 LLVM_FALLTHROUGH;
2753 case ICmpInst::ICMP_NE:
2754 case ICmpInst::ICMP_ULT:
2755 case ICmpInst::ICMP_ULE:
2756 return getTrue(ITy);
2757 }
2758 }
2759
2760 // icmp pred X, (urem Y, X)
2761 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2762 bool KnownNonNegative, KnownNegative;
2763 switch (Pred) {
2764 default:
2765 break;
2766 case ICmpInst::ICMP_SGT:
2767 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002768 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2769 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002770 if (!KnownNonNegative)
2771 break;
2772 LLVM_FALLTHROUGH;
2773 case ICmpInst::ICMP_NE:
2774 case ICmpInst::ICMP_UGT:
2775 case ICmpInst::ICMP_UGE:
2776 return getTrue(ITy);
2777 case ICmpInst::ICMP_SLT:
2778 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002779 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2780 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002781 if (!KnownNonNegative)
2782 break;
2783 LLVM_FALLTHROUGH;
2784 case ICmpInst::ICMP_EQ:
2785 case ICmpInst::ICMP_ULT:
2786 case ICmpInst::ICMP_ULE:
2787 return getFalse(ITy);
2788 }
2789 }
2790
2791 // x >> y <=u x
2792 // x udiv y <=u x.
2793 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2794 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2795 // icmp pred (X op Y), X
2796 if (Pred == ICmpInst::ICMP_UGT)
2797 return getFalse(ITy);
2798 if (Pred == ICmpInst::ICMP_ULE)
2799 return getTrue(ITy);
2800 }
2801
2802 // x >=u x >> y
2803 // x >=u x udiv y.
2804 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2805 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2806 // icmp pred X, (X op Y)
2807 if (Pred == ICmpInst::ICMP_ULT)
2808 return getFalse(ITy);
2809 if (Pred == ICmpInst::ICMP_UGE)
2810 return getTrue(ITy);
2811 }
2812
2813 // handle:
2814 // CI2 << X == CI
2815 // CI2 << X != CI
2816 //
2817 // where CI2 is a power of 2 and CI isn't
2818 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2819 const APInt *CI2Val, *CIVal = &CI->getValue();
2820 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2821 CI2Val->isPowerOf2()) {
2822 if (!CIVal->isPowerOf2()) {
2823 // CI2 << X can equal zero in some circumstances,
2824 // this simplification is unsafe if CI is zero.
2825 //
2826 // We know it is safe if:
2827 // - The shift is nsw, we can't shift out the one bit.
2828 // - The shift is nuw, we can't shift out the one bit.
2829 // - CI2 is one
2830 // - CI isn't zero
2831 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2832 *CI2Val == 1 || !CI->isZero()) {
2833 if (Pred == ICmpInst::ICMP_EQ)
2834 return ConstantInt::getFalse(RHS->getContext());
2835 if (Pred == ICmpInst::ICMP_NE)
2836 return ConstantInt::getTrue(RHS->getContext());
2837 }
2838 }
2839 if (CIVal->isSignBit() && *CI2Val == 1) {
2840 if (Pred == ICmpInst::ICMP_UGT)
2841 return ConstantInt::getFalse(RHS->getContext());
2842 if (Pred == ICmpInst::ICMP_ULE)
2843 return ConstantInt::getTrue(RHS->getContext());
2844 }
2845 }
2846 }
2847
2848 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2849 LBO->getOperand(1) == RBO->getOperand(1)) {
2850 switch (LBO->getOpcode()) {
2851 default:
2852 break;
2853 case Instruction::UDiv:
2854 case Instruction::LShr:
2855 if (ICmpInst::isSigned(Pred))
2856 break;
2857 LLVM_FALLTHROUGH;
2858 case Instruction::SDiv:
2859 case Instruction::AShr:
2860 if (!LBO->isExact() || !RBO->isExact())
2861 break;
2862 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2863 RBO->getOperand(0), Q, MaxRecurse - 1))
2864 return V;
2865 break;
2866 case Instruction::Shl: {
2867 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2868 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2869 if (!NUW && !NSW)
2870 break;
2871 if (!NSW && ICmpInst::isSigned(Pred))
2872 break;
2873 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2874 RBO->getOperand(0), Q, MaxRecurse - 1))
2875 return V;
2876 break;
2877 }
2878 }
2879 }
2880 return nullptr;
2881}
2882
Sanjay Patel35289c62016-12-10 17:40:47 +00002883/// Simplify integer comparisons where at least one operand of the compare
2884/// matches an integer min/max idiom.
2885static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2886 Value *RHS, const Query &Q,
2887 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002888 Type *ITy = GetCompareTy(LHS); // The return type.
2889 Value *A, *B;
2890 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2891 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2892
2893 // Signed variants on "max(a,b)>=a -> true".
2894 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2895 if (A != RHS)
2896 std::swap(A, B); // smax(A, B) pred A.
2897 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2898 // We analyze this as smax(A, B) pred A.
2899 P = Pred;
2900 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2901 (A == LHS || B == LHS)) {
2902 if (A != LHS)
2903 std::swap(A, B); // A pred smax(A, B).
2904 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2905 // We analyze this as smax(A, B) swapped-pred A.
2906 P = CmpInst::getSwappedPredicate(Pred);
2907 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2908 (A == RHS || B == RHS)) {
2909 if (A != RHS)
2910 std::swap(A, B); // smin(A, B) pred A.
2911 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2912 // We analyze this as smax(-A, -B) swapped-pred -A.
2913 // Note that we do not need to actually form -A or -B thanks to EqP.
2914 P = CmpInst::getSwappedPredicate(Pred);
2915 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2916 (A == LHS || B == LHS)) {
2917 if (A != LHS)
2918 std::swap(A, B); // A pred smin(A, B).
2919 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2920 // We analyze this as smax(-A, -B) pred -A.
2921 // Note that we do not need to actually form -A or -B thanks to EqP.
2922 P = Pred;
2923 }
2924 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2925 // Cases correspond to "max(A, B) p A".
2926 switch (P) {
2927 default:
2928 break;
2929 case CmpInst::ICMP_EQ:
2930 case CmpInst::ICMP_SLE:
2931 // Equivalent to "A EqP B". This may be the same as the condition tested
2932 // in the max/min; if so, we can just return that.
2933 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2934 return V;
2935 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2936 return V;
2937 // Otherwise, see if "A EqP B" simplifies.
2938 if (MaxRecurse)
2939 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2940 return V;
2941 break;
2942 case CmpInst::ICMP_NE:
2943 case CmpInst::ICMP_SGT: {
2944 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2945 // Equivalent to "A InvEqP B". This may be the same as the condition
2946 // tested in the max/min; if so, we can just return that.
2947 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2948 return V;
2949 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2950 return V;
2951 // Otherwise, see if "A InvEqP B" simplifies.
2952 if (MaxRecurse)
2953 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2954 return V;
2955 break;
2956 }
2957 case CmpInst::ICMP_SGE:
2958 // Always true.
2959 return getTrue(ITy);
2960 case CmpInst::ICMP_SLT:
2961 // Always false.
2962 return getFalse(ITy);
2963 }
2964 }
2965
2966 // Unsigned variants on "max(a,b)>=a -> true".
2967 P = CmpInst::BAD_ICMP_PREDICATE;
2968 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2969 if (A != RHS)
2970 std::swap(A, B); // umax(A, B) pred A.
2971 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2972 // We analyze this as umax(A, B) pred A.
2973 P = Pred;
2974 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2975 (A == LHS || B == LHS)) {
2976 if (A != LHS)
2977 std::swap(A, B); // A pred umax(A, B).
2978 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2979 // We analyze this as umax(A, B) swapped-pred A.
2980 P = CmpInst::getSwappedPredicate(Pred);
2981 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2982 (A == RHS || B == RHS)) {
2983 if (A != RHS)
2984 std::swap(A, B); // umin(A, B) pred A.
2985 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2986 // We analyze this as umax(-A, -B) swapped-pred -A.
2987 // Note that we do not need to actually form -A or -B thanks to EqP.
2988 P = CmpInst::getSwappedPredicate(Pred);
2989 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2990 (A == LHS || B == LHS)) {
2991 if (A != LHS)
2992 std::swap(A, B); // A pred umin(A, B).
2993 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2994 // We analyze this as umax(-A, -B) pred -A.
2995 // Note that we do not need to actually form -A or -B thanks to EqP.
2996 P = Pred;
2997 }
2998 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2999 // Cases correspond to "max(A, B) p A".
3000 switch (P) {
3001 default:
3002 break;
3003 case CmpInst::ICMP_EQ:
3004 case CmpInst::ICMP_ULE:
3005 // Equivalent to "A EqP B". This may be the same as the condition tested
3006 // in the max/min; if so, we can just return that.
3007 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
3008 return V;
3009 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
3010 return V;
3011 // Otherwise, see if "A EqP B" simplifies.
3012 if (MaxRecurse)
3013 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3014 return V;
3015 break;
3016 case CmpInst::ICMP_NE:
3017 case CmpInst::ICMP_UGT: {
3018 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3019 // Equivalent to "A InvEqP B". This may be the same as the condition
3020 // tested in the max/min; if so, we can just return that.
3021 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3022 return V;
3023 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3024 return V;
3025 // Otherwise, see if "A InvEqP B" simplifies.
3026 if (MaxRecurse)
3027 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3028 return V;
3029 break;
3030 }
3031 case CmpInst::ICMP_UGE:
3032 // Always true.
3033 return getTrue(ITy);
3034 case CmpInst::ICMP_ULT:
3035 // Always false.
3036 return getFalse(ITy);
3037 }
3038 }
3039
3040 // Variants on "max(x,y) >= min(x,z)".
3041 Value *C, *D;
3042 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3043 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3044 (A == C || A == D || B == C || B == D)) {
3045 // max(x, ?) pred min(x, ?).
3046 if (Pred == CmpInst::ICMP_SGE)
3047 // Always true.
3048 return getTrue(ITy);
3049 if (Pred == CmpInst::ICMP_SLT)
3050 // Always false.
3051 return getFalse(ITy);
3052 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3053 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3054 (A == C || A == D || B == C || B == D)) {
3055 // min(x, ?) pred max(x, ?).
3056 if (Pred == CmpInst::ICMP_SLE)
3057 // Always true.
3058 return getTrue(ITy);
3059 if (Pred == CmpInst::ICMP_SGT)
3060 // Always false.
3061 return getFalse(ITy);
3062 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3063 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3064 (A == C || A == D || B == C || B == D)) {
3065 // max(x, ?) pred min(x, ?).
3066 if (Pred == CmpInst::ICMP_UGE)
3067 // Always true.
3068 return getTrue(ITy);
3069 if (Pred == CmpInst::ICMP_ULT)
3070 // Always false.
3071 return getFalse(ITy);
3072 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3073 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3074 (A == C || A == D || B == C || B == D)) {
3075 // min(x, ?) pred max(x, ?).
3076 if (Pred == CmpInst::ICMP_ULE)
3077 // Always true.
3078 return getTrue(ITy);
3079 if (Pred == CmpInst::ICMP_UGT)
3080 // Always false.
3081 return getFalse(ITy);
3082 }
3083
3084 return nullptr;
3085}
3086
Sanjay Patel472cc782016-01-11 22:14:42 +00003087/// Given operands for an ICmpInst, see if we can fold the result.
3088/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003089static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003090 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003091 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003092 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003093
Chris Lattnera71e9d62009-11-10 00:55:12 +00003094 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003095 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003096 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003097
3098 // If we have a constant, make sure it is on the RHS.
3099 std::swap(LHS, RHS);
3100 Pred = CmpInst::getSwappedPredicate(Pred);
3101 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003102
Chris Lattner229907c2011-07-18 04:54:35 +00003103 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003104
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003105 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003106 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3107 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003108 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003109 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003110
Sanjay Pateldc65a272016-12-03 17:30:22 +00003111 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3112 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003113
Sanjay Pateldc65a272016-12-03 17:30:22 +00003114 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3115 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003116
Sanjay Patel67bde282016-08-22 23:12:02 +00003117 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3118 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003119
Chen Li7452d952015-09-26 03:26:47 +00003120 // If both operands have range metadata, use the metadata
3121 // to simplify the comparison.
3122 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3123 auto RHS_Instr = dyn_cast<Instruction>(RHS);
3124 auto LHS_Instr = dyn_cast<Instruction>(LHS);
3125
3126 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3127 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003128 auto RHS_CR = getConstantRangeFromMetadata(
3129 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3130 auto LHS_CR = getConstantRangeFromMetadata(
3131 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003132
3133 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3134 if (Satisfied_CR.contains(LHS_CR))
3135 return ConstantInt::getTrue(RHS->getContext());
3136
3137 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3138 CmpInst::getInversePredicate(Pred), RHS_CR);
3139 if (InversedSatisfied_CR.contains(LHS_CR))
3140 return ConstantInt::getFalse(RHS->getContext());
3141 }
3142 }
3143
Duncan Sands8fb2c382011-01-20 13:21:55 +00003144 // Compare of cast, for example (zext X) != 0 -> X != 0
3145 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3146 Instruction *LI = cast<CastInst>(LHS);
3147 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003148 Type *SrcTy = SrcOp->getType();
3149 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003150
3151 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3152 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003153 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3154 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003155 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3156 // Transfer the cast to the constant.
3157 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3158 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003159 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003160 return V;
3161 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3162 if (RI->getOperand(0)->getType() == SrcTy)
3163 // Compare without the cast.
3164 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003165 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003166 return V;
3167 }
3168 }
3169
3170 if (isa<ZExtInst>(LHS)) {
3171 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3172 // same type.
3173 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3174 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3175 // Compare X and Y. Note that signed predicates become unsigned.
3176 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003177 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003178 MaxRecurse-1))
3179 return V;
3180 }
3181 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3182 // too. If not, then try to deduce the result of the comparison.
3183 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3184 // Compute the constant that would happen if we truncated to SrcTy then
3185 // reextended to DstTy.
3186 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3187 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3188
3189 // If the re-extended constant didn't change then this is effectively
3190 // also a case of comparing two zero-extended values.
3191 if (RExt == CI && MaxRecurse)
3192 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003193 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003194 return V;
3195
3196 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3197 // there. Use this to work out the result of the comparison.
3198 if (RExt != CI) {
3199 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003200 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003201 // LHS <u RHS.
3202 case ICmpInst::ICMP_EQ:
3203 case ICmpInst::ICMP_UGT:
3204 case ICmpInst::ICMP_UGE:
3205 return ConstantInt::getFalse(CI->getContext());
3206
3207 case ICmpInst::ICMP_NE:
3208 case ICmpInst::ICMP_ULT:
3209 case ICmpInst::ICMP_ULE:
3210 return ConstantInt::getTrue(CI->getContext());
3211
3212 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3213 // is non-negative then LHS <s RHS.
3214 case ICmpInst::ICMP_SGT:
3215 case ICmpInst::ICMP_SGE:
3216 return CI->getValue().isNegative() ?
3217 ConstantInt::getTrue(CI->getContext()) :
3218 ConstantInt::getFalse(CI->getContext());
3219
3220 case ICmpInst::ICMP_SLT:
3221 case ICmpInst::ICMP_SLE:
3222 return CI->getValue().isNegative() ?
3223 ConstantInt::getFalse(CI->getContext()) :
3224 ConstantInt::getTrue(CI->getContext());
3225 }
3226 }
3227 }
3228 }
3229
3230 if (isa<SExtInst>(LHS)) {
3231 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3232 // same type.
3233 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3234 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3235 // Compare X and Y. Note that the predicate does not change.
3236 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003237 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003238 return V;
3239 }
3240 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3241 // too. If not, then try to deduce the result of the comparison.
3242 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3243 // Compute the constant that would happen if we truncated to SrcTy then
3244 // reextended to DstTy.
3245 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3246 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3247
3248 // If the re-extended constant didn't change then this is effectively
3249 // also a case of comparing two sign-extended values.
3250 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003251 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003252 return V;
3253
3254 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3255 // bits there. Use this to work out the result of the comparison.
3256 if (RExt != CI) {
3257 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003258 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003259 case ICmpInst::ICMP_EQ:
3260 return ConstantInt::getFalse(CI->getContext());
3261 case ICmpInst::ICMP_NE:
3262 return ConstantInt::getTrue(CI->getContext());
3263
3264 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3265 // LHS >s RHS.
3266 case ICmpInst::ICMP_SGT:
3267 case ICmpInst::ICMP_SGE:
3268 return CI->getValue().isNegative() ?
3269 ConstantInt::getTrue(CI->getContext()) :
3270 ConstantInt::getFalse(CI->getContext());
3271 case ICmpInst::ICMP_SLT:
3272 case ICmpInst::ICMP_SLE:
3273 return CI->getValue().isNegative() ?
3274 ConstantInt::getFalse(CI->getContext()) :
3275 ConstantInt::getTrue(CI->getContext());
3276
3277 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3278 // LHS >u RHS.
3279 case ICmpInst::ICMP_UGT:
3280 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003281 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003282 if (MaxRecurse)
3283 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3284 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003285 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003286 return V;
3287 break;
3288 case ICmpInst::ICMP_ULT:
3289 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003290 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003291 if (MaxRecurse)
3292 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3293 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003294 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003295 return V;
3296 break;
3297 }
3298 }
3299 }
3300 }
3301 }
3302
James Molloy1d88d6f2015-10-22 13:18:42 +00003303 // icmp eq|ne X, Y -> false|true if X != Y
3304 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003305 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003306 LLVMContext &Ctx = LHS->getType()->getContext();
3307 return Pred == ICmpInst::ICMP_NE ?
3308 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3309 }
Junmo Park53470fc2016-04-05 21:14:31 +00003310
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003311 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3312 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003313
Sanjay Patel35289c62016-12-10 17:40:47 +00003314 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003315 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003316
Chandler Carruth8059c842012-03-25 21:28:14 +00003317 // Simplify comparisons of related pointers using a powerful, recursive
3318 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003319 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003320 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003321 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003322 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3323 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3324 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3325 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3326 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3327 Q.DL.getTypeSizeInBits(CRHS->getType()))
3328 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3329 CLHS->getPointerOperand(),
3330 CRHS->getPointerOperand()))
3331 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003332
Nick Lewycky3db143e2012-02-26 02:09:49 +00003333 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3334 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3335 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3336 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3337 (ICmpInst::isEquality(Pred) ||
3338 (GLHS->isInBounds() && GRHS->isInBounds() &&
3339 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3340 // The bases are equal and the indices are constant. Build a constant
3341 // expression GEP with the same indices and a null base pointer to see
3342 // what constant folding can make out of it.
3343 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3344 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003345 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3346 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003347
3348 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003349 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3350 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003351 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3352 }
3353 }
3354 }
3355
David Majnemer5854e9f2014-11-16 02:20:08 +00003356 // If a bit is known to be zero for A and known to be one for B,
3357 // then A and B cannot be equal.
3358 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003359 const APInt *RHSVal;
3360 if (match(RHS, m_APInt(RHSVal))) {
3361 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003362 APInt LHSKnownZero(BitWidth, 0);
3363 APInt LHSKnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003364 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003365 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003366 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3367 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3368 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003369 }
3370 }
3371
Duncan Sandsf532d312010-11-07 16:12:23 +00003372 // If the comparison is with the result of a select instruction, check whether
3373 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003374 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003375 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003376 return V;
3377
3378 // If the comparison is with the result of a phi instruction, check whether
3379 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003380 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003381 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003382 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003383
Craig Topper9f008862014-04-15 04:59:12 +00003384 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003385}
3386
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003387Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003388 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003389 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003390 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003391 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003392 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003393 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003394}
3395
Sanjay Patel472cc782016-01-11 22:14:42 +00003396/// Given operands for an FCmpInst, see if we can fold the result.
3397/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003398static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003399 FastMathFlags FMF, const Query &Q,
3400 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003401 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3402 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3403
Chris Lattnera71e9d62009-11-10 00:55:12 +00003404 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003405 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003406 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003407
Chris Lattnera71e9d62009-11-10 00:55:12 +00003408 // If we have a constant, make sure it is on the RHS.
3409 std::swap(LHS, RHS);
3410 Pred = CmpInst::getSwappedPredicate(Pred);
3411 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003412
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003413 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003414 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003415 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003416 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003417 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003418 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003419
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003420 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3421 if (FMF.noNaNs()) {
3422 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003423 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003424 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003425 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003426 }
3427
Mehdi Aminieb242a52015-03-09 03:20:25 +00003428 // fcmp pred x, undef and fcmp pred undef, x
3429 // fold to true if unordered, false if ordered
3430 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3431 // Choosing NaN for the undef will always make unordered comparison succeed
3432 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003433 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003434 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003435
3436 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003437 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003438 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003439 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003440 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003441 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003442 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003443
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003444 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003445 const ConstantFP *CFP = nullptr;
3446 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3447 if (RHS->getType()->isVectorTy())
3448 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3449 else
3450 CFP = dyn_cast<ConstantFP>(RHSC);
3451 }
3452 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003453 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003454 if (CFP->getValueAPF().isNaN()) {
3455 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003456 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003457 assert(FCmpInst::isUnordered(Pred) &&
3458 "Comparison must be either ordered or unordered!");
3459 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003460 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003461 }
3462 // Check whether the constant is an infinity.
3463 if (CFP->getValueAPF().isInfinity()) {
3464 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003465 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003466 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003467 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003468 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003469 case FCmpInst::FCMP_UGE:
3470 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003471 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003472 default:
3473 break;
3474 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003475 } else {
3476 switch (Pred) {
3477 case FCmpInst::FCMP_OGT:
3478 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003479 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003480 case FCmpInst::FCMP_ULE:
3481 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003482 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003483 default:
3484 break;
3485 }
3486 }
3487 }
3488 if (CFP->getValueAPF().isZero()) {
3489 switch (Pred) {
3490 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003491 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003492 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003493 break;
3494 case FCmpInst::FCMP_OLT:
3495 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003496 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003497 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003498 break;
3499 default:
3500 break;
3501 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003502 }
3503 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003504
Duncan Sandsa620bd12010-11-07 16:46:25 +00003505 // If the comparison is with the result of a select instruction, check whether
3506 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003507 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003508 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003509 return V;
3510
3511 // If the comparison is with the result of a phi instruction, check whether
3512 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003513 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003514 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003515 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003516
Craig Topper9f008862014-04-15 04:59:12 +00003517 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003518}
3519
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003520Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003521 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003522 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003523 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003524 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003525 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003526 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003527}
3528
Sanjay Patel472cc782016-01-11 22:14:42 +00003529/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003530static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3531 const Query &Q,
3532 unsigned MaxRecurse) {
3533 // Trivial replacement.
3534 if (V == Op)
3535 return RepOp;
3536
3537 auto *I = dyn_cast<Instruction>(V);
3538 if (!I)
3539 return nullptr;
3540
3541 // If this is a binary operator, try to simplify it with the replaced op.
3542 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3543 // Consider:
3544 // %cmp = icmp eq i32 %x, 2147483647
3545 // %add = add nsw i32 %x, 1
3546 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3547 //
3548 // We can't replace %sel with %add unless we strip away the flags.
3549 if (isa<OverflowingBinaryOperator>(B))
3550 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3551 return nullptr;
3552 if (isa<PossiblyExactOperator>(B))
3553 if (B->isExact())
3554 return nullptr;
3555
3556 if (MaxRecurse) {
3557 if (B->getOperand(0) == Op)
3558 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3559 MaxRecurse - 1);
3560 if (B->getOperand(1) == Op)
3561 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3562 MaxRecurse - 1);
3563 }
3564 }
3565
3566 // Same for CmpInsts.
3567 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3568 if (MaxRecurse) {
3569 if (C->getOperand(0) == Op)
3570 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3571 MaxRecurse - 1);
3572 if (C->getOperand(1) == Op)
3573 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3574 MaxRecurse - 1);
3575 }
3576 }
3577
3578 // TODO: We could hand off more cases to instsimplify here.
3579
3580 // If all operands are constant after substituting Op for RepOp then we can
3581 // constant fold the instruction.
3582 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3583 // Build a list of all constant operands.
3584 SmallVector<Constant *, 8> ConstOps;
3585 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3586 if (I->getOperand(i) == Op)
3587 ConstOps.push_back(CRepOp);
3588 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3589 ConstOps.push_back(COp);
3590 else
3591 break;
3592 }
3593
3594 // All operands were constants, fold it.
3595 if (ConstOps.size() == I->getNumOperands()) {
3596 if (CmpInst *C = dyn_cast<CmpInst>(I))
3597 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3598 ConstOps[1], Q.DL, Q.TLI);
3599
3600 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3601 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003602 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003603
Manuel Jacobe9024592016-01-21 06:33:22 +00003604 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003605 }
3606 }
3607
3608 return nullptr;
3609}
3610
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003611/// Try to simplify a select instruction when its condition operand is an
3612/// integer comparison where one operand of the compare is a constant.
3613static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3614 const APInt *Y, bool TrueWhenUnset) {
3615 const APInt *C;
3616
3617 // (X & Y) == 0 ? X & ~Y : X --> X
3618 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3619 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3620 *Y == ~*C)
3621 return TrueWhenUnset ? FalseVal : TrueVal;
3622
3623 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3624 // (X & Y) != 0 ? X : X & ~Y --> X
3625 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3626 *Y == ~*C)
3627 return TrueWhenUnset ? FalseVal : TrueVal;
3628
3629 if (Y->isPowerOf2()) {
3630 // (X & Y) == 0 ? X | Y : X --> X | Y
3631 // (X & Y) != 0 ? X | Y : X --> X
3632 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3633 *Y == *C)
3634 return TrueWhenUnset ? TrueVal : FalseVal;
3635
3636 // (X & Y) == 0 ? X : X | Y --> X
3637 // (X & Y) != 0 ? X : X | Y --> X | Y
3638 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3639 *Y == *C)
3640 return TrueWhenUnset ? TrueVal : FalseVal;
3641 }
Matt Arsenault82606662017-01-11 00:57:54 +00003642
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003643 return nullptr;
3644}
3645
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003646/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3647/// eq/ne.
3648static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3649 Value *FalseVal,
3650 bool TrueWhenUnset) {
3651 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003652 if (!BitWidth)
3653 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00003654
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003655 APInt MinSignedValue;
3656 Value *X;
3657 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3658 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3659 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3660 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3661 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3662 } else {
3663 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3664 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3665 X = CmpLHS;
3666 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3667 }
3668
3669 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3670 TrueWhenUnset))
3671 return V;
3672
3673 return nullptr;
3674}
3675
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003676/// Try to simplify a select instruction when its condition operand is an
3677/// integer comparison.
3678static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3679 Value *FalseVal, const Query &Q,
3680 unsigned MaxRecurse) {
3681 ICmpInst::Predicate Pred;
3682 Value *CmpLHS, *CmpRHS;
3683 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3684 return nullptr;
3685
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003686 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3687 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003688 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3689 Value *X;
3690 const APInt *Y;
3691 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3692 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3693 Pred == ICmpInst::ICMP_EQ))
3694 return V;
3695 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003696 // Comparing signed-less-than 0 checks if the sign bit is set.
3697 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3698 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003699 return V;
3700 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003701 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3702 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3703 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003704 return V;
3705 }
3706
3707 if (CondVal->hasOneUse()) {
3708 const APInt *C;
3709 if (match(CmpRHS, m_APInt(C))) {
3710 // X < MIN ? T : F --> F
3711 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3712 return FalseVal;
3713 // X < MIN ? T : F --> F
3714 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3715 return FalseVal;
3716 // X > MAX ? T : F --> F
3717 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3718 return FalseVal;
3719 // X > MAX ? T : F --> F
3720 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3721 return FalseVal;
3722 }
3723 }
3724
3725 // If we have an equality comparison, then we know the value in one of the
3726 // arms of the select. See if substituting this value into the arm and
3727 // simplifying the result yields the same value as the other arm.
3728 if (Pred == ICmpInst::ICMP_EQ) {
3729 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3730 TrueVal ||
3731 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3732 TrueVal)
3733 return FalseVal;
3734 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3735 FalseVal ||
3736 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3737 FalseVal)
3738 return FalseVal;
3739 } else if (Pred == ICmpInst::ICMP_NE) {
3740 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3741 FalseVal ||
3742 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3743 FalseVal)
3744 return TrueVal;
3745 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3746 TrueVal ||
3747 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3748 TrueVal)
3749 return TrueVal;
3750 }
3751
3752 return nullptr;
3753}
3754
Sanjay Patel472cc782016-01-11 22:14:42 +00003755/// Given operands for a SelectInst, see if we can fold the result.
3756/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003757static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3758 Value *FalseVal, const Query &Q,
3759 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003760 // select true, X, Y -> X
3761 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003762 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3763 if (CB->isAllOnesValue())
3764 return TrueVal;
3765 if (CB->isNullValue())
3766 return FalseVal;
3767 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003768
Chris Lattnerc707fa92010-04-20 05:32:14 +00003769 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003770 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003771 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003772
Chris Lattnerc707fa92010-04-20 05:32:14 +00003773 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3774 if (isa<Constant>(TrueVal))
3775 return TrueVal;
3776 return FalseVal;
3777 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003778 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3779 return FalseVal;
3780 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3781 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003782
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003783 if (Value *V =
3784 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3785 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003786
Craig Topper9f008862014-04-15 04:59:12 +00003787 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003788}
3789
Duncan Sandsb8cee002012-03-13 11:42:19 +00003790Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003791 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003792 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003793 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003794 const Instruction *CxtI) {
3795 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003796 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003797}
3798
Sanjay Patel472cc782016-01-11 22:14:42 +00003799/// Given operands for an GetElementPtrInst, see if we can fold the result.
3800/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003801static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3802 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003803 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003804 unsigned AS =
3805 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003806
Chris Lattner8574aba2009-11-27 00:29:05 +00003807 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003808 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003809 return Ops[0];
3810
Nico Weber48c82402014-08-27 20:06:19 +00003811 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003812 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003813 Type *GEPTy = PointerType::get(LastType, AS);
3814 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3815 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3816
3817 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003818 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003819
Jay Foadb992a632011-07-19 15:07:52 +00003820 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003821 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003822 if (match(Ops[1], m_Zero()))
3823 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003824
David Blaikie4a2e73b2015-04-02 18:55:32 +00003825 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003826 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003827 Value *P;
3828 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003829 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003830 // getelementptr P, N -> P if P points to a type of zero size.
3831 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003832 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003833
3834 // The following transforms are only safe if the ptrtoint cast
3835 // doesn't truncate the pointers.
3836 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003837 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003838 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3839 if (match(P, m_Zero()))
3840 return Constant::getNullValue(GEPTy);
3841 Value *Temp;
3842 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003843 if (Temp->getType() == GEPTy)
3844 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003845 return nullptr;
3846 };
3847
3848 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3849 if (TyAllocSize == 1 &&
3850 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3851 if (Value *R = PtrToIntOrZero(P))
3852 return R;
3853
3854 // getelementptr V, (ashr (sub P, V), C) -> Q
3855 // if P points to a type of size 1 << C.
3856 if (match(Ops[1],
3857 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3858 m_ConstantInt(C))) &&
3859 TyAllocSize == 1ULL << C)
3860 if (Value *R = PtrToIntOrZero(P))
3861 return R;
3862
3863 // getelementptr V, (sdiv (sub P, V), C) -> Q
3864 // if P points to a type of size C.
3865 if (match(Ops[1],
3866 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3867 m_SpecificInt(TyAllocSize))))
3868 if (Value *R = PtrToIntOrZero(P))
3869 return R;
3870 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003871 }
3872 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003873
David Majnemerd1501372016-08-07 07:58:12 +00003874 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3875 all_of(Ops.slice(1).drop_back(1),
3876 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3877 unsigned PtrWidth =
3878 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3879 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3880 APInt BasePtrOffset(PtrWidth, 0);
3881 Value *StrippedBasePtr =
3882 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3883 BasePtrOffset);
3884
David Majnemer5c5df622016-08-16 06:13:46 +00003885 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003886 if (match(Ops.back(),
3887 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3888 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3889 return ConstantExpr::getIntToPtr(CI, GEPTy);
3890 }
David Majnemer5c5df622016-08-16 06:13:46 +00003891 // gep (gep V, C), (xor V, -1) -> C-1
3892 if (match(Ops.back(),
3893 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3894 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3895 return ConstantExpr::getIntToPtr(CI, GEPTy);
3896 }
David Majnemerd1501372016-08-07 07:58:12 +00003897 }
3898 }
3899
Chris Lattner8574aba2009-11-27 00:29:05 +00003900 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003901 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003902 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003903 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003904
David Blaikie4a2e73b2015-04-02 18:55:32 +00003905 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3906 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003907}
3908
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003909Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3910 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003911 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003912 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003913 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003914 return ::SimplifyGEPInst(SrcTy, Ops,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003915 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003916}
3917
Sanjay Patel472cc782016-01-11 22:14:42 +00003918/// Given operands for an InsertValueInst, see if we can fold the result.
3919/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003920static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3921 ArrayRef<unsigned> Idxs, const Query &Q,
3922 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003923 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3924 if (Constant *CVal = dyn_cast<Constant>(Val))
3925 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3926
3927 // insertvalue x, undef, n -> x
3928 if (match(Val, m_Undef()))
3929 return Agg;
3930
3931 // insertvalue x, (extractvalue y, n), n
3932 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003933 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3934 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003935 // insertvalue undef, (extractvalue y, n), n -> y
3936 if (match(Agg, m_Undef()))
3937 return EV->getAggregateOperand();
3938
3939 // insertvalue y, (extractvalue y, n), n -> y
3940 if (Agg == EV->getAggregateOperand())
3941 return Agg;
3942 }
3943
Craig Topper9f008862014-04-15 04:59:12 +00003944 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003945}
3946
Chandler Carruth66b31302015-01-04 12:03:27 +00003947Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003948 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003949 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +00003950 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003951 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003952 RecursionLimit);
3953}
3954
Sanjay Patel472cc782016-01-11 22:14:42 +00003955/// Given operands for an ExtractValueInst, see if we can fold the result.
3956/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003957static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3958 const Query &, unsigned) {
3959 if (auto *CAgg = dyn_cast<Constant>(Agg))
3960 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3961
3962 // extractvalue x, (insertvalue y, elt, n), n -> elt
3963 unsigned NumIdxs = Idxs.size();
3964 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3965 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3966 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3967 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3968 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3969 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3970 Idxs.slice(0, NumCommonIdxs)) {
3971 if (NumIdxs == NumInsertValueIdxs)
3972 return IVI->getInsertedValueOperand();
3973 break;
3974 }
3975 }
3976
3977 return nullptr;
3978}
3979
3980Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3981 const DataLayout &DL,
3982 const TargetLibraryInfo *TLI,
3983 const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003984 AssumptionCache *AC,
David Majnemer25a796e2015-07-13 01:15:46 +00003985 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003986 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003987 RecursionLimit);
3988}
3989
Sanjay Patel472cc782016-01-11 22:14:42 +00003990/// Given operands for an ExtractElementInst, see if we can fold the result.
3991/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003992static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3993 unsigned) {
3994 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3995 if (auto *CIdx = dyn_cast<Constant>(Idx))
3996 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3997
3998 // The index is not relevant if our vector is a splat.
3999 if (auto *Splat = CVec->getSplatValue())
4000 return Splat;
4001
4002 if (isa<UndefValue>(Vec))
4003 return UndefValue::get(Vec->getType()->getVectorElementType());
4004 }
4005
4006 // If extracting a specified index from the vector, see if we can recursively
4007 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00004008 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
4009 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00004010 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00004011
4012 return nullptr;
4013}
4014
4015Value *llvm::SimplifyExtractElementInst(
4016 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004017 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
4018 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00004019 RecursionLimit);
4020}
4021
Sanjay Patel472cc782016-01-11 22:14:42 +00004022/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00004023static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004024 // If all of the PHI's incoming values are the same then replace the PHI node
4025 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004026 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004027 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004028 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004029 // If the incoming value is the phi node itself, it can safely be skipped.
4030 if (Incoming == PN) continue;
4031 if (isa<UndefValue>(Incoming)) {
4032 // Remember that we saw an undef value, but otherwise ignore them.
4033 HasUndefInput = true;
4034 continue;
4035 }
4036 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004037 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004038 CommonValue = Incoming;
4039 }
4040
4041 // If CommonValue is null then all of the incoming values were either undef or
4042 // equal to the phi node itself.
4043 if (!CommonValue)
4044 return UndefValue::get(PN->getType());
4045
4046 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4047 // instruction, we cannot return X as the result of the PHI node unless it
4048 // dominates the PHI block.
4049 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00004050 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004051
4052 return CommonValue;
4053}
4054
David Majnemer6774d612016-07-26 17:58:05 +00004055static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4056 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004057 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004058 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004059
David Majnemer6774d612016-07-26 17:58:05 +00004060 if (auto *CI = dyn_cast<CastInst>(Op)) {
4061 auto *Src = CI->getOperand(0);
4062 Type *SrcTy = Src->getType();
4063 Type *MidTy = CI->getType();
4064 Type *DstTy = Ty;
4065 if (Src->getType() == Ty) {
4066 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4067 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4068 Type *SrcIntPtrTy =
4069 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4070 Type *MidIntPtrTy =
4071 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4072 Type *DstIntPtrTy =
4073 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4074 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4075 SrcIntPtrTy, MidIntPtrTy,
4076 DstIntPtrTy) == Instruction::BitCast)
4077 return Src;
4078 }
4079 }
David Majnemera90a6212016-07-26 05:52:29 +00004080
4081 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004082 if (CastOpc == Instruction::BitCast)
4083 if (Op->getType() == Ty)
4084 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004085
4086 return nullptr;
4087}
4088
David Majnemer6774d612016-07-26 17:58:05 +00004089Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4090 const DataLayout &DL,
4091 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004092 const DominatorTree *DT, AssumptionCache *AC,
David Majnemer6774d612016-07-26 17:58:05 +00004093 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004094 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004095 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004096}
4097
Chris Lattnera71e9d62009-11-10 00:55:12 +00004098//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004099
Sanjay Patel472cc782016-01-11 22:14:42 +00004100/// Given operands for a BinaryOperator, see if we can fold the result.
4101/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004102static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004103 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004104 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004105 case Instruction::Add:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004106 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004107 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004108 case Instruction::FAdd:
4109 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4110
Chris Lattner9e4aa022011-02-09 17:15:04 +00004111 case Instruction::Sub:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004112 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004113 Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004114 case Instruction::FSub:
4115 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4116
Duncan Sandsb8cee002012-03-13 11:42:19 +00004117 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004118 case Instruction::FMul:
4119 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004120 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4121 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004122 case Instruction::FDiv:
4123 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsb8cee002012-03-13 11:42:19 +00004124 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4125 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004126 case Instruction::FRem:
4127 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004128 case Instruction::Shl:
Duncan Sands8b4e2832011-02-09 17:45:03 +00004129 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004130 Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004131 case Instruction::LShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004132 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004133 case Instruction::AShr:
Duncan Sandsb8cee002012-03-13 11:42:19 +00004134 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
4135 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4136 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
4137 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004138 default:
4139 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00004140 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4141 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00004142
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004143 // If the operation is associative, try some generic simplifications.
4144 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004145 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004146 return V;
4147
Duncan Sandsb8cee002012-03-13 11:42:19 +00004148 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00004149 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004150 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004151 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004152 return V;
4153
4154 // If the operation is with the result of a phi instruction, check whether
4155 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004156 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004157 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00004158 return V;
4159
Craig Topper9f008862014-04-15 04:59:12 +00004160 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00004161 }
4162}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004163
Sanjay Patel472cc782016-01-11 22:14:42 +00004164/// Given operands for a BinaryOperator, see if we can fold the result.
4165/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004166/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4167/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4168static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4169 const FastMathFlags &FMF, const Query &Q,
4170 unsigned MaxRecurse) {
4171 switch (Opcode) {
4172 case Instruction::FAdd:
4173 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4174 case Instruction::FSub:
4175 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4176 case Instruction::FMul:
4177 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004178 case Instruction::FDiv:
4179 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004180 default:
4181 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4182 }
4183}
4184
Duncan Sands7e800d62010-11-14 11:23:23 +00004185Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004186 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004187 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004188 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004189 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004190 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004191}
4192
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004193Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004194 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004195 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004196 const DominatorTree *DT, AssumptionCache *AC,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004197 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004198 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004199 RecursionLimit);
4200}
4201
Sanjay Patel472cc782016-01-11 22:14:42 +00004202/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004203static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004204 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004205 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004206 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004207 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004208}
4209
4210Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004211 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004212 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004213 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004214 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004215 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004216}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004217
Michael Ilseman54857292013-02-07 19:26:05 +00004218static bool IsIdempotent(Intrinsic::ID ID) {
4219 switch (ID) {
4220 default: return false;
4221
4222 // Unary idempotent: f(f(x)) = f(x)
4223 case Intrinsic::fabs:
4224 case Intrinsic::floor:
4225 case Intrinsic::ceil:
4226 case Intrinsic::trunc:
4227 case Intrinsic::rint:
4228 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004229 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004230 return true;
4231 }
4232}
4233
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004234static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4235 const DataLayout &DL) {
4236 GlobalValue *PtrSym;
4237 APInt PtrOffset;
4238 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4239 return nullptr;
4240
4241 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4242 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4243 Type *Int32PtrTy = Int32Ty->getPointerTo();
4244 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4245
4246 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4247 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4248 return nullptr;
4249
4250 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4251 if (OffsetInt % 4 != 0)
4252 return nullptr;
4253
4254 Constant *C = ConstantExpr::getGetElementPtr(
4255 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4256 ConstantInt::get(Int64Ty, OffsetInt / 4));
4257 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4258 if (!Loaded)
4259 return nullptr;
4260
4261 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4262 if (!LoadedCE)
4263 return nullptr;
4264
4265 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4266 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4267 if (!LoadedCE)
4268 return nullptr;
4269 }
4270
4271 if (LoadedCE->getOpcode() != Instruction::Sub)
4272 return nullptr;
4273
4274 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4275 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4276 return nullptr;
4277 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4278
4279 Constant *LoadedRHS = LoadedCE->getOperand(1);
4280 GlobalValue *LoadedRHSSym;
4281 APInt LoadedRHSOffset;
4282 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4283 DL) ||
4284 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4285 return nullptr;
4286
4287 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4288}
4289
David Majnemer17a95aa2016-07-14 06:58:37 +00004290static bool maskIsAllZeroOrUndef(Value *Mask) {
4291 auto *ConstMask = dyn_cast<Constant>(Mask);
4292 if (!ConstMask)
4293 return false;
4294 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4295 return true;
4296 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4297 ++I) {
4298 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4299 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4300 continue;
4301 return false;
4302 }
4303 return true;
4304}
4305
Michael Ilseman54857292013-02-07 19:26:05 +00004306template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004307static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004308 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004309 Intrinsic::ID IID = F->getIntrinsicID();
4310 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004311
4312 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004313 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004314 // Perform idempotent optimizations
4315 if (IsIdempotent(IID)) {
4316 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4317 if (II->getIntrinsicID() == IID)
4318 return II;
4319 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004320 }
4321
4322 switch (IID) {
4323 case Intrinsic::fabs: {
4324 if (SignBitMustBeZero(*ArgBegin, Q.TLI))
4325 return *ArgBegin;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004326 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004327 }
4328 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004329 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004330 }
4331 }
Michael Ilseman54857292013-02-07 19:26:05 +00004332
Matt Arsenault82606662017-01-11 00:57:54 +00004333 // Binary Ops
4334 if (NumOperands == 2) {
4335 Value *LHS = *ArgBegin;
4336 Value *RHS = *(ArgBegin + 1);
4337 Type *ReturnType = F->getReturnType();
4338
4339 switch (IID) {
4340 case Intrinsic::usub_with_overflow:
4341 case Intrinsic::ssub_with_overflow: {
4342 // X - X -> { 0, false }
4343 if (LHS == RHS)
4344 return Constant::getNullValue(ReturnType);
4345
4346 // X - undef -> undef
4347 // undef - X -> undef
4348 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4349 return UndefValue::get(ReturnType);
4350
4351 return nullptr;
4352 }
4353 case Intrinsic::uadd_with_overflow:
4354 case Intrinsic::sadd_with_overflow: {
4355 // X + undef -> undef
4356 if (isa<UndefValue>(RHS))
4357 return UndefValue::get(ReturnType);
4358
4359 return nullptr;
4360 }
4361 case Intrinsic::umul_with_overflow:
4362 case Intrinsic::smul_with_overflow: {
4363 // X * 0 -> { 0, false }
4364 if (match(RHS, m_Zero()))
4365 return Constant::getNullValue(ReturnType);
4366
4367 // X * undef -> { 0, false }
4368 if (match(RHS, m_Undef()))
4369 return Constant::getNullValue(ReturnType);
4370
4371 return nullptr;
4372 }
4373 case Intrinsic::load_relative: {
4374 Constant *C0 = dyn_cast<Constant>(LHS);
4375 Constant *C1 = dyn_cast<Constant>(RHS);
4376 if (C0 && C1)
4377 return SimplifyRelativeLoad(C0, C1, Q.DL);
4378 return nullptr;
4379 }
4380 default:
4381 return nullptr;
4382 }
4383 }
4384
4385 // Simplify calls to llvm.masked.load.*
4386 switch (IID) {
4387 case Intrinsic::masked_load: {
4388 Value *MaskArg = ArgBegin[2];
4389 Value *PassthruArg = ArgBegin[3];
4390 // If the mask is all zeros or undef, the "passthru" argument is the result.
4391 if (maskIsAllZeroOrUndef(MaskArg))
4392 return PassthruArg;
4393 return nullptr;
4394 }
4395 default:
4396 return nullptr;
4397 }
Michael Ilseman54857292013-02-07 19:26:05 +00004398}
4399
Chandler Carruth9dc35582012-12-28 11:30:55 +00004400template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004401static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004402 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004403 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004404 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4405 Ty = PTy->getElementType();
4406 FunctionType *FTy = cast<FunctionType>(Ty);
4407
Dan Gohman85977e62011-11-04 18:32:42 +00004408 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004409 // call null -> undef
4410 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004411 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004412
Chandler Carruthf6182152012-12-28 14:23:29 +00004413 Function *F = dyn_cast<Function>(V);
4414 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004415 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004416
David Majnemer15032582015-05-22 03:56:46 +00004417 if (F->isIntrinsic())
4418 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004419 return Ret;
4420
Chandler Carruthf6182152012-12-28 14:23:29 +00004421 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004422 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004423
4424 SmallVector<Constant *, 4> ConstantArgs;
4425 ConstantArgs.reserve(ArgEnd - ArgBegin);
4426 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4427 Constant *C = dyn_cast<Constant>(*I);
4428 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004429 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004430 ConstantArgs.push_back(C);
4431 }
4432
4433 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004434}
4435
Chandler Carruthf6182152012-12-28 14:23:29 +00004436Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004437 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004438 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004439 AssumptionCache *AC, const Instruction *CxtI) {
4440 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004441 RecursionLimit);
4442}
4443
Chandler Carruthf6182152012-12-28 14:23:29 +00004444Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004445 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004446 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004447 const Instruction *CxtI) {
4448 return ::SimplifyCall(V, Args.begin(), Args.end(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004449 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004450}
4451
Sanjay Patel472cc782016-01-11 22:14:42 +00004452/// See if we can compute a simplified version of this instruction.
4453/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004454Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004455 const TargetLibraryInfo *TLI,
Sanjay Patel54656ca2017-02-06 18:26:06 +00004456 const DominatorTree *DT, AssumptionCache *AC,
4457 OptimizationRemarkEmitter *ORE) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004458 Value *Result;
4459
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004460 switch (I->getOpcode()) {
4461 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004462 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004463 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004464 case Instruction::FAdd:
4465 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004466 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004467 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004468 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004469 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4470 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004471 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004472 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004473 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004474 case Instruction::FSub:
4475 Result = SimplifyFSubInst(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;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004478 case Instruction::Sub:
4479 Result = SimplifySubInst(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 Sands0a2c41682010-12-15 14:07:39 +00004483 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004484 case Instruction::FMul:
4485 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004486 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004487 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004488 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004489 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004490 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004491 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004492 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004493 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004494 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004495 break;
4496 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004497 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004498 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004499 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004500 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004501 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004502 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004503 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004504 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004505 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004506 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004507 break;
4508 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004509 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004510 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004511 break;
4512 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004513 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004514 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004515 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004516 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004517 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4518 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004519 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004520 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004521 break;
4522 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004523 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004524 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004525 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004526 break;
4527 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004528 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004529 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004530 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004531 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004532 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004533 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004534 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004535 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004536 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004537 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004538 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004539 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004540 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004541 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004542 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004543 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004544 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004545 Result =
4546 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004547 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004548 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004549 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004550 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4551 I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004552 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004553 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004554 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004555 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004556 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004557 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004558 case Instruction::GetElementPtr: {
4559 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004560 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004561 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004562 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004563 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004564 case Instruction::InsertValue: {
4565 InsertValueInst *IV = cast<InsertValueInst>(I);
4566 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4567 IV->getInsertedValueOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004568 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004569 break;
4570 }
David Majnemer25a796e2015-07-13 01:15:46 +00004571 case Instruction::ExtractValue: {
4572 auto *EVI = cast<ExtractValueInst>(I);
4573 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004574 EVI->getIndices(), DL, TLI, DT, AC, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004575 break;
4576 }
David Majnemer599ca442015-07-13 01:15:53 +00004577 case Instruction::ExtractElement: {
4578 auto *EEI = cast<ExtractElementInst>(I);
4579 Result = SimplifyExtractElementInst(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004580 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
David Majnemer599ca442015-07-13 01:15:53 +00004581 break;
4582 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004583 case Instruction::PHI:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004584 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004585 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004586 case Instruction::Call: {
4587 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004588 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004589 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004590 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004591 }
David Majnemer6774d612016-07-26 17:58:05 +00004592#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4593#include "llvm/IR/Instruction.def"
4594#undef HANDLE_CAST_INST
4595 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004596 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004597 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004598 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004599
Hal Finkelf2199b22015-10-23 20:37:08 +00004600 // In general, it is possible for computeKnownBits to determine all bits in a
4601 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004602 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004603 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4604 APInt KnownZero(BitWidth, 0);
4605 APInt KnownOne(BitWidth, 0);
Sanjay Patel54656ca2017-02-06 18:26:06 +00004606 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT, ORE);
Hal Finkelf2199b22015-10-23 20:37:08 +00004607 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004608 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004609 }
4610
Duncan Sands64e41cf2010-11-17 08:35:29 +00004611 /// If called on unreachable code, the above logic may report that the
4612 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004613 /// detecting that case here, returning a safe value instead.
4614 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004615}
4616
Sanjay Patelf44bd382016-01-20 18:59:48 +00004617/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004618/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004619///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004620/// This is the common implementation of the recursive simplification routines.
4621/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4622/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4623/// instructions to process and attempt to simplify it using
4624/// InstructionSimplify.
4625///
4626/// This routine returns 'true' only when *it* simplifies something. The passed
4627/// in simplified value does not count toward this.
4628static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004629 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004630 const DominatorTree *DT,
4631 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004632 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004633 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004634 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004635
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004636 // If we have an explicit value to collapse to, do that round of the
4637 // simplification loop by hand initially.
4638 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004639 for (User *U : I->users())
4640 if (U != I)
4641 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004642
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004643 // Replace the instruction with its simplified value.
4644 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004645
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004646 // Gracefully handle edge cases where the instruction is not wired into any
4647 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004648 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4649 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004650 I->eraseFromParent();
4651 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004652 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004653 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004654
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004655 // Note that we must test the size on each iteration, the worklist can grow.
4656 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4657 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004658
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004659 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004660 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004661 if (!SimpleV)
4662 continue;
4663
4664 Simplified = true;
4665
4666 // Stash away all the uses of the old instruction so we can check them for
4667 // recursive simplifications after a RAUW. This is cheaper than checking all
4668 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004669 for (User *U : I->users())
4670 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004671
4672 // Replace the instruction with its simplified value.
4673 I->replaceAllUsesWith(SimpleV);
4674
4675 // Gracefully handle edge cases where the instruction is not wired into any
4676 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004677 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4678 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004679 I->eraseFromParent();
4680 }
4681 return Simplified;
4682}
4683
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004684bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004685 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004686 const DominatorTree *DT,
4687 AssumptionCache *AC) {
4688 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004689}
4690
4691bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004692 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004693 const DominatorTree *DT,
4694 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004695 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4696 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004697 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004698}