blob: 5cb93df7395376069ddf32bfa4c4ee98f31151f7 [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 Patel8b5ad3f2017-04-01 19:05:11 +0000531static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
532 Value *&Op0, Value *&Op1,
533 const Query &Q) {
534 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
535 if (auto *CRHS = dyn_cast<Constant>(Op1))
536 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
537
538 // Canonicalize the constant to the RHS if this is a commutative operation.
539 if (Instruction::isCommutative(Opcode))
540 std::swap(Op0, Op1);
541 }
542 return nullptr;
543}
544
Sanjay Patel472cc782016-01-11 22:14:42 +0000545/// Given operands for an Add, see if we can fold the result.
546/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000547static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000548 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000549 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
550 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +0000551
Duncan Sands0a2c41682010-12-15 14:07:39 +0000552 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000553 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000554 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000555
Duncan Sands0a2c41682010-12-15 14:07:39 +0000556 // X + 0 -> X
557 if (match(Op1, m_Zero()))
558 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000559
Duncan Sands0a2c41682010-12-15 14:07:39 +0000560 // X + (Y - X) -> Y
561 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000562 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000563 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000564 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
565 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000566 return Y;
567
568 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000569 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000570 if (match(Op0, m_Not(m_Specific(Op1))) ||
571 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000572 return Constant::getAllOnesValue(Ty);
573
574 // add nsw/nuw (xor Y, signbit), signbit --> Y
575 // The no-wrapping add guarantees that the top bit will be set by the add.
576 // Therefore, the xor must be clearing the already set sign bit of Y.
Craig Topper3a40a392017-03-30 22:21:16 +0000577 if ((isNSW || isNUW) && match(Op1, m_SignBit()) &&
578 match(Op0, m_Xor(m_Value(Y), m_SignBit())))
Sanjay Patelfe672552017-02-18 21:59:09 +0000579 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000580
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000581 /// i1 add -> xor.
Duncan Sands5def0d62010-12-21 14:48:48 +0000582 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000583 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000584 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000585
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000586 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000587 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000588 MaxRecurse))
589 return V;
590
Duncan Sandsb238de02010-11-19 09:20:39 +0000591 // Threading Add over selects and phi nodes is pointless, so don't bother.
592 // Threading over the select in "A + select(cond, B, C)" means evaluating
593 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
594 // only if B and C are equal. If B and C are equal then (since we assume
595 // that operands have already been simplified) "select(cond, B, C)" should
596 // have been simplified to the common value of B and C already. Analysing
597 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
598 // for threading over phi nodes.
599
Craig Topper9f008862014-04-15 04:59:12 +0000600 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000601}
602
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000603Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000604 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000605 const DominatorTree *DT, AssumptionCache *AC,
606 const Instruction *CxtI) {
607 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000608 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000609}
610
Chandler Carrutha0796552012-03-12 11:19:31 +0000611/// \brief Compute the base pointer and cumulative constant offsets for V.
612///
613/// This strips all constant offsets off of V, leaving it the base pointer, and
614/// accumulates the total constant offset applied in the returned constant. It
615/// returns 0 if V is not a pointer, and returns the constant '0' if there are
616/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000617///
618/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
619/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
620/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000621static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000622 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000623 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000624
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000625 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000626 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000627
628 // Even though we don't look through PHI nodes, we could be called on an
629 // instruction in an unreachable block, which may be on a cycle.
630 SmallPtrSet<Value *, 4> Visited;
631 Visited.insert(V);
632 do {
633 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000634 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000635 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000636 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000637 V = GEP->getPointerOperand();
638 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000639 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000640 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000641 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000642 break;
643 V = GA->getAliasee();
644 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000645 if (auto CS = CallSite(V))
646 if (Value *RV = CS.getReturnedArgOperand()) {
647 V = RV;
648 continue;
649 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000650 break;
651 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000652 assert(V->getType()->getScalarType()->isPointerTy() &&
653 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000654 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000655
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000656 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
657 if (V->getType()->isVectorTy())
658 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
659 OffsetIntPtr);
660 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000661}
662
663/// \brief Compute the constant difference between two pointer values.
664/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000665static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
666 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000667 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
668 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000669
670 // If LHS and RHS are not related via constant offsets to the same base
671 // value, there is nothing we can do here.
672 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000673 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000674
675 // Otherwise, the difference of LHS - RHS can be computed as:
676 // LHS - RHS
677 // = (LHSOffset + Base) - (RHSOffset + Base)
678 // = LHSOffset - RHSOffset
679 return ConstantExpr::getSub(LHSOffset, RHSOffset);
680}
681
Sanjay Patel472cc782016-01-11 22:14:42 +0000682/// Given operands for a Sub, see if we can fold the result.
683/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000684static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000685 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000686 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
687 return C;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000688
689 // X - undef -> undef
690 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000691 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000692 return UndefValue::get(Op0->getType());
693
694 // X - 0 -> X
695 if (match(Op1, m_Zero()))
696 return Op0;
697
698 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000699 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000700 return Constant::getNullValue(Op0->getType());
701
Sanjay Patelefd88852016-10-19 21:23:45 +0000702 // Is this a negation?
703 if (match(Op0, m_Zero())) {
704 // 0 - X -> 0 if the sub is NUW.
705 if (isNUW)
706 return Op0;
707
708 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
709 APInt KnownZero(BitWidth, 0);
710 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000711 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Craig Topper6856d342017-03-30 22:10:54 +0000712 if (KnownZero.isMaxSignedValue()) {
Sanjay Patelefd88852016-10-19 21:23:45 +0000713 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
714 // Op1 must be 0 because negating the minimum signed value is undefined.
715 if (isNSW)
716 return Op0;
717
718 // 0 - X -> X if X is 0 or the minimum signed value.
719 return Op1;
720 }
721 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000722
Duncan Sands99589d02011-01-18 11:50:19 +0000723 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
724 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000725 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000726 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
727 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000728 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000729 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000730 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000731 // It does, we successfully reassociated!
732 ++NumReassoc;
733 return W;
734 }
735 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000736 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000737 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000738 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000739 // It does, we successfully reassociated!
740 ++NumReassoc;
741 return W;
742 }
743 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000744
Duncan Sands99589d02011-01-18 11:50:19 +0000745 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
746 // For example, X - (X + 1) -> -1
747 X = Op0;
748 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
749 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000750 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000751 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000752 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000753 // It does, we successfully reassociated!
754 ++NumReassoc;
755 return W;
756 }
757 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000758 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000759 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000760 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000761 // It does, we successfully reassociated!
762 ++NumReassoc;
763 return W;
764 }
765 }
766
767 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
768 // For example, X - (X - Y) -> Y.
769 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000770 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
771 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000772 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000773 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000774 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000775 // It does, we successfully reassociated!
776 ++NumReassoc;
777 return W;
778 }
779
Duncan Sands395ac42d2012-03-13 14:07:05 +0000780 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
781 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
782 match(Op1, m_Trunc(m_Value(Y))))
783 if (X->getType() == Y->getType())
784 // See if "V === X - Y" simplifies.
785 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
786 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000787 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
788 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000789 // It does, return the simplified "trunc V".
790 return W;
791
792 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000793 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000794 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000795 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000796 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
797
Duncan Sands99589d02011-01-18 11:50:19 +0000798 // i1 sub -> xor.
799 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000800 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000801 return V;
802
Duncan Sands0a2c41682010-12-15 14:07:39 +0000803 // Threading Sub over selects and phi nodes is pointless, so don't bother.
804 // Threading over the select in "A - select(cond, B, C)" means evaluating
805 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
806 // only if B and C are equal. If B and C are equal then (since we assume
807 // that operands have already been simplified) "select(cond, B, C)" should
808 // have been simplified to the common value of B and C already. Analysing
809 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
810 // for threading over phi nodes.
811
Craig Topper9f008862014-04-15 04:59:12 +0000812 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000813}
814
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000815Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000816 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000817 const DominatorTree *DT, AssumptionCache *AC,
818 const Instruction *CxtI) {
819 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth66b31302015-01-04 12:03:27 +0000820 RecursionLimit);
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000821}
822
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000823/// Given operands for an FAdd, see if we can fold the result. If not, this
824/// returns null.
825static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
826 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000827 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
828 return C;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000829
830 // fadd X, -0 ==> X
831 if (match(Op1, m_NegZero()))
832 return Op0;
833
834 // fadd X, 0 ==> X, when we know X is not -0
835 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000836 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000837 return Op0;
838
839 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
840 // where nnan and ninf have to occur at least once somewhere in this
841 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000842 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000843 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
844 SubOp = Op1;
845 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
846 SubOp = Op0;
847 if (SubOp) {
848 Instruction *FSub = cast<Instruction>(SubOp);
849 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
850 (FMF.noInfs() || FSub->hasNoInfs()))
851 return Constant::getNullValue(Op0->getType());
852 }
853
Craig Topper9f008862014-04-15 04:59:12 +0000854 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000855}
856
857/// Given operands for an FSub, see if we can fold the result. If not, this
858/// returns null.
859static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
860 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000861 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
862 return C;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000863
864 // fsub X, 0 ==> X
865 if (match(Op1, m_Zero()))
866 return Op0;
867
868 // fsub X, -0 ==> X, when we know X is not -0
869 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000870 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000871 return Op0;
872
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000873 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000874 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000875 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
876 return X;
877
878 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000879 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000880 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
881 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000882
Benjamin Kramer228680d2015-06-14 21:01:20 +0000883 // fsub nnan x, x ==> 0.0
884 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000885 return Constant::getNullValue(Op0->getType());
886
Craig Topper9f008862014-04-15 04:59:12 +0000887 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000888}
889
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000890/// Given the operands for an FMul, see if we can fold the result
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000891static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
892 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000893 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
894 return C;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000895
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000896 // fmul X, 1.0 ==> X
897 if (match(Op1, m_FPOne()))
898 return Op0;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000899
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000900 // fmul nnan nsz X, 0 ==> 0
901 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
902 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000903
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000904 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000905}
906
Sanjay Patel472cc782016-01-11 22:14:42 +0000907/// Given operands for a Mul, see if we can fold the result.
908/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000909static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
910 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000911 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
912 return C;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000913
914 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000915 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000916 return Constant::getNullValue(Op0->getType());
917
918 // X * 0 -> 0
919 if (match(Op1, m_Zero()))
920 return Op1;
921
922 // X * 1 -> X
923 if (match(Op1, m_One()))
924 return Op0;
925
Duncan Sandsb67edc62011-01-30 18:03:50 +0000926 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000927 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000928 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
929 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
930 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000931
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000932 // i1 mul -> and.
Duncan Sands5def0d62010-12-21 14:48:48 +0000933 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000934 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000935 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000936
937 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000938 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000939 MaxRecurse))
940 return V;
941
942 // Mul distributes over Add. Try some generic simplifications based on this.
943 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000944 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000945 return V;
946
947 // If the operation is with the result of a select instruction, check whether
948 // operating on either branch of the select always yields the same value.
949 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000950 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000951 MaxRecurse))
952 return V;
953
954 // If the operation is with the result of a phi instruction, check whether
955 // operating on all incoming values of the phi always yields the same value.
956 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000957 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000958 MaxRecurse))
959 return V;
960
Craig Topper9f008862014-04-15 04:59:12 +0000961 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000962}
963
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000964Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000965 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000966 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000967 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000968 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000969 return ::SimplifyFAddInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000970 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000971}
972
973Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000974 const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +0000975 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000976 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +0000977 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000978 return ::SimplifyFSubInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000979 RecursionLimit);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000980}
981
Chandler Carruth66b31302015-01-04 12:03:27 +0000982Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000983 const DataLayout &DL,
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000984 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000985 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000986 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000987 return ::SimplifyFMulInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000988 RecursionLimit);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000989}
990
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000991Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000992 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000993 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +0000994 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000995 return ::SimplifyMulInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +0000996 RecursionLimit);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000997}
998
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000999/// Check for common or similar folds of integer division or integer remainder.
1000static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
1001 Type *Ty = Op0->getType();
1002
1003 // X / undef -> undef
1004 // X % undef -> undef
1005 if (match(Op1, m_Undef()))
1006 return Op1;
1007
1008 // X / 0 -> undef
1009 // X % 0 -> undef
1010 // We don't need to preserve faults!
1011 if (match(Op1, m_Zero()))
1012 return UndefValue::get(Ty);
1013
Sanjay Patel2b1f6f42017-03-09 16:20:52 +00001014 // If any element of a constant divisor vector is zero, the whole op is undef.
1015 auto *Op1C = dyn_cast<Constant>(Op1);
1016 if (Op1C && Ty->isVectorTy()) {
1017 unsigned NumElts = Ty->getVectorNumElements();
1018 for (unsigned i = 0; i != NumElts; ++i) {
1019 Constant *Elt = Op1C->getAggregateElement(i);
1020 if (Elt && Elt->isNullValue())
1021 return UndefValue::get(Ty);
1022 }
1023 }
1024
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001025 // undef / X -> 0
1026 // undef % X -> 0
1027 if (match(Op0, m_Undef()))
1028 return Constant::getNullValue(Ty);
1029
1030 // 0 / X -> 0
1031 // 0 % X -> 0
1032 if (match(Op0, m_Zero()))
1033 return Op0;
1034
1035 // X / X -> 1
1036 // X % X -> 0
1037 if (Op0 == Op1)
1038 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1039
1040 // X / 1 -> X
1041 // X % 1 -> 0
Sanjay Patel962a8432017-03-09 21:56:03 +00001042 // If this is a boolean op (single-bit element type), we can't have
1043 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
1044 if (match(Op1, m_One()) || Ty->getScalarType()->isIntegerTy(1))
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001045 return IsDiv ? Op0 : Constant::getNullValue(Ty);
1046
1047 return nullptr;
1048}
1049
Sanjay Patel472cc782016-01-11 22:14:42 +00001050/// Given operands for an SDiv or UDiv, see if we can fold the result.
1051/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001052static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001053 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001054 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1055 return C;
Duncan Sands771e82a2011-01-28 16:51:11 +00001056
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001057 if (Value *V = simplifyDivRem(Op0, Op1, true))
1058 return V;
1059
Duncan Sands65995fa2011-01-28 18:50:50 +00001060 bool isSigned = Opcode == Instruction::SDiv;
1061
Duncan Sands771e82a2011-01-28 16:51:11 +00001062 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001063 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001064 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1065 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001066 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001067 // If the Mul knows it does not overflow, then we are good to go.
1068 if ((isSigned && Mul->hasNoSignedWrap()) ||
1069 (!isSigned && Mul->hasNoUnsignedWrap()))
1070 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001071 // If X has the form X = A / Y then X * Y cannot overflow.
1072 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1073 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1074 return X;
1075 }
1076
Duncan Sands65995fa2011-01-28 18:50:50 +00001077 // (X rem Y) / Y -> 0
1078 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1079 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1080 return Constant::getNullValue(Op0->getType());
1081
David Majnemercb9d5962014-10-11 10:20:01 +00001082 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1083 ConstantInt *C1, *C2;
1084 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1085 match(Op1, m_ConstantInt(C2))) {
1086 bool Overflow;
1087 C1->getValue().umul_ov(C2->getValue(), Overflow);
1088 if (Overflow)
1089 return Constant::getNullValue(Op0->getType());
1090 }
1091
Duncan Sands65995fa2011-01-28 18:50:50 +00001092 // If the operation is with the result of a select instruction, check whether
1093 // operating on either branch of the select always yields the same value.
1094 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001095 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001096 return V;
1097
1098 // If the operation is with the result of a phi instruction, check whether
1099 // operating on all incoming values of the phi always yields the same value.
1100 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001101 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001102 return V;
1103
Craig Topper9f008862014-04-15 04:59:12 +00001104 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001105}
1106
Sanjay Patel472cc782016-01-11 22:14:42 +00001107/// Given operands for an SDiv, see if we can fold the result.
1108/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001109static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1110 unsigned MaxRecurse) {
1111 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001112 return V;
1113
Craig Topper9f008862014-04-15 04:59:12 +00001114 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001115}
1116
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001117Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001118 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001119 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001120 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001121 return ::SimplifySDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001122 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001123}
1124
Sanjay Patel472cc782016-01-11 22:14:42 +00001125/// Given operands for a UDiv, see if we can fold the result.
1126/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001127static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1128 unsigned MaxRecurse) {
1129 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001130 return V;
1131
David Majnemer63da0c22017-01-06 22:58:02 +00001132 // udiv %V, C -> 0 if %V < C
1133 if (MaxRecurse) {
1134 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1135 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1136 if (C->isAllOnesValue()) {
1137 return Constant::getNullValue(Op0->getType());
1138 }
1139 }
1140 }
1141
Craig Topper9f008862014-04-15 04:59:12 +00001142 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001143}
1144
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001145Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001146 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001147 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001148 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001149 return ::SimplifyUDivInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001150 RecursionLimit);
Duncan Sands771e82a2011-01-28 16:51:11 +00001151}
1152
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001153static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
1154 const Query &Q, unsigned) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001155 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
1156 return C;
1157
Frits van Bommelc2549662011-01-29 15:26:31 +00001158 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001159 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001160 return Op0;
1161
1162 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001163 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001164 return Op1;
1165
Zia Ansari394cef82016-12-08 23:27:40 +00001166 // X / 1.0 -> X
1167 if (match(Op1, m_FPOne()))
1168 return Op0;
1169
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001170 // 0 / X -> 0
1171 // Requires that NaNs are off (X could be zero) and signed zeroes are
1172 // ignored (X could be positive or negative, so the output sign is unknown).
1173 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1174 return Op0;
1175
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001176 if (FMF.noNaNs()) {
1177 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001178 if (Op0 == Op1)
1179 return ConstantFP::get(Op0->getType(), 1.0);
1180
1181 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001182 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001183 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1184 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1185 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1186 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1187 BinaryOperator::getFNegArgument(Op1) == Op0))
1188 return ConstantFP::get(Op0->getType(), -1.0);
1189 }
1190
Craig Topper9f008862014-04-15 04:59:12 +00001191 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001192}
1193
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001194Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001195 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001196 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001197 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001198 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001199 return ::SimplifyFDivInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001200 RecursionLimit);
Frits van Bommelc2549662011-01-29 15:26:31 +00001201}
1202
Sanjay Patel472cc782016-01-11 22:14:42 +00001203/// Given operands for an SRem or URem, see if we can fold the result.
1204/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001205static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001206 const Query &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001207 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1208 return C;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001209
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001210 if (Value *V = simplifyDivRem(Op0, Op1, false))
1211 return V;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001212
David Majnemerb435a422014-09-17 04:16:35 +00001213 // (X % Y) % Y -> X % Y
1214 if ((Opcode == Instruction::SRem &&
1215 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1216 (Opcode == Instruction::URem &&
1217 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001218 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001219
Duncan Sandsa3e36992011-05-02 16:27:02 +00001220 // If the operation is with the result of a select instruction, check whether
1221 // operating on either branch of the select always yields the same value.
1222 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001223 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001224 return V;
1225
1226 // If the operation is with the result of a phi instruction, check whether
1227 // operating on all incoming values of the phi always yields the same value.
1228 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001229 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001230 return V;
1231
Craig Topper9f008862014-04-15 04:59:12 +00001232 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001233}
1234
Sanjay Patel472cc782016-01-11 22:14:42 +00001235/// Given operands for an SRem, see if we can fold the result.
1236/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001237static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1238 unsigned MaxRecurse) {
1239 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001240 return V;
1241
Craig Topper9f008862014-04-15 04:59:12 +00001242 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001243}
1244
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001245Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001246 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001247 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001248 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001249 return ::SimplifySRemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001250 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001251}
1252
Sanjay Patel472cc782016-01-11 22:14:42 +00001253/// Given operands for a URem, see if we can fold the result.
1254/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001255static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001256 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001257 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001258 return V;
1259
David Majnemer8c0e62f2017-01-06 21:23:51 +00001260 // urem %V, C -> %V if %V < C
1261 if (MaxRecurse) {
1262 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1263 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1264 if (C->isAllOnesValue()) {
1265 return Op0;
1266 }
1267 }
1268 }
1269
Craig Topper9f008862014-04-15 04:59:12 +00001270 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001271}
1272
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001273Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001274 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001275 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001276 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001277 return ::SimplifyURemInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001278 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001279}
1280
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001281static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001282 const Query &Q, unsigned) {
1283 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
1284 return C;
1285
Duncan Sandsa3e36992011-05-02 16:27:02 +00001286 // undef % X -> undef (the undef could be a snan).
1287 if (match(Op0, m_Undef()))
1288 return Op0;
1289
1290 // X % undef -> undef
1291 if (match(Op1, m_Undef()))
1292 return Op1;
1293
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001294 // 0 % X -> 0
1295 // Requires that NaNs are off (X could be zero) and signed zeroes are
1296 // ignored (X could be positive or negative, so the output sign is unknown).
1297 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1298 return Op0;
1299
Craig Topper9f008862014-04-15 04:59:12 +00001300 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001301}
1302
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001303Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001304 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001305 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001306 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001307 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001308 return ::SimplifyFRemInst(Op0, Op1, FMF, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001309 RecursionLimit);
Duncan Sandsa3e36992011-05-02 16:27:02 +00001310}
1311
Sanjay Patel472cc782016-01-11 22:14:42 +00001312/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001313static bool isUndefShift(Value *Amount) {
1314 Constant *C = dyn_cast<Constant>(Amount);
1315 if (!C)
1316 return false;
1317
1318 // X shift by undef -> undef because it may shift by the bitwidth.
1319 if (isa<UndefValue>(C))
1320 return true;
1321
1322 // Shifting by the bitwidth or more is undefined.
1323 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1324 if (CI->getValue().getLimitedValue() >=
1325 CI->getType()->getScalarSizeInBits())
1326 return true;
1327
1328 // If all lanes of a vector shift are undefined the whole shift is.
1329 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1330 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1331 if (!isUndefShift(C->getAggregateElement(I)))
1332 return false;
1333 return true;
1334 }
1335
1336 return false;
1337}
1338
Sanjay Patel472cc782016-01-11 22:14:42 +00001339/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1340/// If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001341static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
1342 Value *Op1, const Query &Q, unsigned MaxRecurse) {
1343 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1344 return C;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001345
Duncan Sands571fd9a2011-01-14 14:44:12 +00001346 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001347 if (match(Op0, m_Zero()))
1348 return Op0;
1349
Duncan Sands571fd9a2011-01-14 14:44:12 +00001350 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001351 if (match(Op1, m_Zero()))
1352 return Op0;
1353
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001354 // Fold undefined shifts.
1355 if (isUndefShift(Op1))
1356 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001357
Duncan Sands571fd9a2011-01-14 14:44:12 +00001358 // If the operation is with the result of a select instruction, check whether
1359 // operating on either branch of the select always yields the same value.
1360 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001361 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001362 return V;
1363
1364 // If the operation is with the result of a phi instruction, check whether
1365 // operating on all incoming values of the phi always yields the same value.
1366 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001367 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001368 return V;
1369
Sanjay Patel6786bc52016-05-10 20:46:54 +00001370 // If any bits in the shift amount make that value greater than or equal to
1371 // the number of bits in the type, the shift is undefined.
1372 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
1373 APInt KnownZero(BitWidth, 0);
1374 APInt KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001375 computeKnownBits(Op1, KnownZero, KnownOne, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Sanjay Patel6786bc52016-05-10 20:46:54 +00001376 if (KnownOne.getLimitedValue() >= BitWidth)
1377 return UndefValue::get(Op0->getType());
1378
1379 // If all valid bits in the shift amount are known zero, the first operand is
1380 // unchanged.
1381 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
1382 APInt ShiftAmountMask = APInt::getLowBitsSet(BitWidth, NumValidShiftBits);
1383 if ((KnownZero & ShiftAmountMask) == ShiftAmountMask)
1384 return Op0;
1385
Craig Topper9f008862014-04-15 04:59:12 +00001386 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001387}
1388
David Majnemerbf7550e2014-11-05 00:59:59 +00001389/// \brief Given operands for an Shl, LShr or AShr, see if we can
1390/// fold the result. If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001391static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
1392 Value *Op1, bool isExact, const Query &Q,
David Majnemerbf7550e2014-11-05 00:59:59 +00001393 unsigned MaxRecurse) {
1394 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1395 return V;
1396
1397 // X >> X -> 0
1398 if (Op0 == Op1)
1399 return Constant::getNullValue(Op0->getType());
1400
David Majnemer65c52ae2014-12-17 01:54:33 +00001401 // undef >> X -> 0
1402 // undef >> X -> undef (if it's exact)
1403 if (match(Op0, m_Undef()))
1404 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1405
David Majnemerbf7550e2014-11-05 00:59:59 +00001406 // The low bit cannot be shifted out of an exact shift if it is set.
1407 if (isExact) {
1408 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
1409 APInt Op0KnownZero(BitWidth, 0);
1410 APInt Op0KnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001411 computeKnownBits(Op0, Op0KnownZero, Op0KnownOne, Q.DL, /*Depth=*/0, Q.AC,
1412 Q.CxtI, Q.DT);
David Majnemerbf7550e2014-11-05 00:59:59 +00001413 if (Op0KnownOne[0])
1414 return Op0;
1415 }
1416
1417 return nullptr;
1418}
1419
Sanjay Patel472cc782016-01-11 22:14:42 +00001420/// Given operands for an Shl, see if we can fold the result.
1421/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001422static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001423 const Query &Q, unsigned MaxRecurse) {
1424 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001425 return V;
1426
1427 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001428 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001429 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001430 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001431
Chris Lattner9e4aa022011-02-09 17:15:04 +00001432 // (X >> A) << A -> X
1433 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001434 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001435 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001436 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001437}
1438
Chris Lattner9e4aa022011-02-09 17:15:04 +00001439Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001440 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001441 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001442 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001443 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001444 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001445}
1446
Sanjay Patel472cc782016-01-11 22:14:42 +00001447/// Given operands for an LShr, see if we can fold the result.
1448/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001449static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001450 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001451 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1452 MaxRecurse))
1453 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001454
Chris Lattner9e4aa022011-02-09 17:15:04 +00001455 // (X << A) >> A -> X
1456 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001457 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001458 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001459
Craig Topper9f008862014-04-15 04:59:12 +00001460 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001461}
1462
Chris Lattner9e4aa022011-02-09 17:15:04 +00001463Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001464 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001465 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001466 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001467 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001468 return ::SimplifyLShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001469 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001470}
1471
Sanjay Patel472cc782016-01-11 22:14:42 +00001472/// Given operands for an AShr, see if we can fold the result.
1473/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001474static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001475 const Query &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001476 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1477 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001478 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001479
1480 // all ones >>a X -> all ones
1481 if (match(Op0, m_AllOnes()))
1482 return Op0;
1483
Chris Lattner9e4aa022011-02-09 17:15:04 +00001484 // (X << A) >> A -> X
1485 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001486 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001487 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001488
Suyog Sarda68862412014-07-17 06:28:15 +00001489 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001490 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001491 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1492 return Op0;
1493
Craig Topper9f008862014-04-15 04:59:12 +00001494 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001495}
1496
Chris Lattner9e4aa022011-02-09 17:15:04 +00001497Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001498 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001499 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001500 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001501 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001502 return ::SimplifyAShrInst(Op0, Op1, isExact, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00001503 RecursionLimit);
Duncan Sands7f60dc12011-01-14 00:37:45 +00001504}
1505
David Majnemer1af36e52014-12-06 10:51:40 +00001506static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1507 ICmpInst *UnsignedICmp, bool IsAnd) {
1508 Value *X, *Y;
1509
1510 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001511 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1512 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001513 return nullptr;
1514
1515 ICmpInst::Predicate UnsignedPred;
1516 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1517 ICmpInst::isUnsigned(UnsignedPred))
1518 ;
1519 else if (match(UnsignedICmp,
1520 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1521 ICmpInst::isUnsigned(UnsignedPred))
1522 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1523 else
1524 return nullptr;
1525
1526 // X < Y && Y != 0 --> X < Y
1527 // X < Y || Y != 0 --> Y != 0
1528 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1529 return IsAnd ? UnsignedICmp : ZeroICmp;
1530
1531 // X >= Y || Y != 0 --> true
1532 // X >= Y || Y == 0 --> X >= Y
1533 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1534 if (EqPred == ICmpInst::ICMP_NE)
1535 return getTrue(UnsignedICmp->getType());
1536 return UnsignedICmp;
1537 }
1538
David Majnemerd5b3aa42014-12-08 18:30:43 +00001539 // X < Y && Y == 0 --> false
1540 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1541 IsAnd)
1542 return getFalse(UnsignedICmp->getType());
1543
David Majnemer1af36e52014-12-06 10:51:40 +00001544 return nullptr;
1545}
1546
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001547/// Commuted variants are assumed to be handled by calling this function again
1548/// with the parameters swapped.
1549static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1550 ICmpInst::Predicate Pred0, Pred1;
1551 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001552 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1553 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001554 return nullptr;
1555
1556 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1557 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1558 // can eliminate Op1 from this 'and'.
1559 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1560 return Op0;
1561
1562 // Check for any combination of predicates that are guaranteed to be disjoint.
1563 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1564 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1565 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1566 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1567 return getFalse(Op0->getType());
1568
1569 return nullptr;
1570}
1571
1572/// Commuted variants are assumed to be handled by calling this function again
1573/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001574static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001575 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1576 return X;
1577
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001578 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1579 return X;
1580
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001581 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001582 Type *ITy = Op0->getType();
1583 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001584 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001585 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001586 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1587 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1588 // Make a constant range that's the intersection of the two icmp ranges.
1589 // If the intersection is empty, we know that the result is false.
1590 auto Range0 = ConstantRange::makeAllowedICmpRegion(Pred0, *C0);
1591 auto Range1 = ConstantRange::makeAllowedICmpRegion(Pred1, *C1);
1592 if (Range0.intersectWith(Range1).isEmptySet())
1593 return getFalse(ITy);
1594 }
1595
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001596 // (icmp (add V, C0), C1) & (icmp V, C0)
1597 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001598 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001599
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001600 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001601 return nullptr;
1602
David Majnemera315bd82014-09-15 08:15:28 +00001603 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001604 if (AddInst->getOperand(1) != Op1->getOperand(1))
1605 return nullptr;
1606
David Majnemera315bd82014-09-15 08:15:28 +00001607 bool isNSW = AddInst->hasNoSignedWrap();
1608 bool isNUW = AddInst->hasNoUnsignedWrap();
1609
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001610 const APInt Delta = *C1 - *C0;
1611 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001612 if (Delta == 2) {
1613 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1614 return getFalse(ITy);
1615 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1616 return getFalse(ITy);
1617 }
1618 if (Delta == 1) {
1619 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1620 return getFalse(ITy);
1621 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1622 return getFalse(ITy);
1623 }
1624 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001625 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001626 if (Delta == 2)
1627 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1628 return getFalse(ITy);
1629 if (Delta == 1)
1630 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1631 return getFalse(ITy);
1632 }
1633
1634 return nullptr;
1635}
1636
Sanjay Patel472cc782016-01-11 22:14:42 +00001637/// Given operands for an And, see if we can fold the result.
1638/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001639static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001640 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001641 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1642 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001643
Chris Lattnera71e9d62009-11-10 00:55:12 +00001644 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001645 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001646 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001647
Chris Lattnera71e9d62009-11-10 00:55:12 +00001648 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001649 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001650 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001651
Duncan Sandsc89ac072010-11-17 18:52:15 +00001652 // X & 0 = 0
1653 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001654 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001655
Duncan Sandsc89ac072010-11-17 18:52:15 +00001656 // X & -1 = X
1657 if (match(Op1, m_AllOnes()))
1658 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001659
Chris Lattnera71e9d62009-11-10 00:55:12 +00001660 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001661 if (match(Op0, m_Not(m_Specific(Op1))) ||
1662 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001663 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001664
Chris Lattnera71e9d62009-11-10 00:55:12 +00001665 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001666 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001667 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001668 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001669 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001670
Chris Lattnera71e9d62009-11-10 00:55:12 +00001671 // A & (A | ?) = A
1672 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001673 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001674 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001675
Duncan Sandsba286d72011-10-26 20:55:21 +00001676 // A & (-A) = A if A is a power of two or zero.
1677 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1678 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001679 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1680 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001681 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001682 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1683 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001684 return Op1;
1685 }
1686
David Majnemera315bd82014-09-15 08:15:28 +00001687 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1688 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1689 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1690 return V;
1691 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1692 return V;
1693 }
1694 }
1695
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001696 // The compares may be hidden behind casts. Look through those and try the
1697 // same folds as above.
1698 auto *Cast0 = dyn_cast<CastInst>(Op0);
1699 auto *Cast1 = dyn_cast<CastInst>(Op1);
1700 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1701 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1702 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1703 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1704 if (Cmp0 && Cmp1) {
1705 Instruction::CastOps CastOpc = Cast0->getOpcode();
1706 Type *ResultType = Cast0->getType();
1707 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1708 return ConstantExpr::getCast(CastOpc, V, ResultType);
1709 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1710 return ConstantExpr::getCast(CastOpc, V, ResultType);
1711 }
1712 }
1713
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001714 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001715 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1716 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001717 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001718
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001719 // And distributes over Or. Try some generic simplifications based on this.
1720 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001721 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001722 return V;
1723
1724 // And distributes over Xor. Try some generic simplifications based on this.
1725 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001726 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001727 return V;
1728
Duncan Sandsb0579e92010-11-10 13:00:08 +00001729 // If the operation is with the result of a select instruction, check whether
1730 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001731 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001732 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1733 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001734 return V;
1735
1736 // If the operation is with the result of a phi instruction, check whether
1737 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001738 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001739 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001740 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001741 return V;
1742
Craig Topper9f008862014-04-15 04:59:12 +00001743 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001744}
1745
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001746Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001747 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001748 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001749 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001750 return ::SimplifyAndInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001751 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001752}
1753
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001754/// Commuted variants are assumed to be handled by calling this function again
1755/// with the parameters swapped.
1756static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1757 ICmpInst::Predicate Pred0, Pred1;
1758 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001759 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1760 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001761 return nullptr;
1762
1763 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1764 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1765 // can eliminate Op0 from this 'or'.
1766 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1767 return Op1;
1768
1769 // Check for any combination of predicates that cover the entire range of
1770 // possibilities.
1771 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1772 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1773 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1774 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1775 return getTrue(Op0->getType());
1776
1777 return nullptr;
1778}
1779
1780/// Commuted variants are assumed to be handled by calling this function again
1781/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001782static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001783 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1784 return X;
1785
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001786 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1787 return X;
1788
Sanjay Patel220a8732016-09-28 14:27:21 +00001789 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001790 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001791 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001792 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001793 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001794 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001795
Sanjay Patel220a8732016-09-28 14:27:21 +00001796 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1797 return nullptr;
1798
1799 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1800 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001801 return nullptr;
1802
1803 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001804 bool isNSW = AddInst->hasNoSignedWrap();
1805 bool isNUW = AddInst->hasNoUnsignedWrap();
1806
Sanjay Patel220a8732016-09-28 14:27:21 +00001807 const APInt Delta = *C1 - *C0;
1808 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001809 if (Delta == 2) {
1810 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1811 return getTrue(ITy);
1812 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1813 return getTrue(ITy);
1814 }
1815 if (Delta == 1) {
1816 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1817 return getTrue(ITy);
1818 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1819 return getTrue(ITy);
1820 }
1821 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001822 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001823 if (Delta == 2)
1824 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1825 return getTrue(ITy);
1826 if (Delta == 1)
1827 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1828 return getTrue(ITy);
1829 }
1830
1831 return nullptr;
1832}
1833
Sanjay Patel472cc782016-01-11 22:14:42 +00001834/// Given operands for an Or, see if we can fold the result.
1835/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001836static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1837 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001838 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1839 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001840
Chris Lattnera71e9d62009-11-10 00:55:12 +00001841 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001842 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001843 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001844
Chris Lattnera71e9d62009-11-10 00:55:12 +00001845 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001846 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001847 return Op0;
1848
Duncan Sandsc89ac072010-11-17 18:52:15 +00001849 // X | 0 = X
1850 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001851 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001852
Duncan Sandsc89ac072010-11-17 18:52:15 +00001853 // X | -1 = -1
1854 if (match(Op1, m_AllOnes()))
1855 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001856
Chris Lattnera71e9d62009-11-10 00:55:12 +00001857 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001858 if (match(Op0, m_Not(m_Specific(Op1))) ||
1859 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001860 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001861
Chris Lattnera71e9d62009-11-10 00:55:12 +00001862 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001863 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001864 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001865 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001866 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001867
Chris Lattnera71e9d62009-11-10 00:55:12 +00001868 // A | (A & ?) = A
1869 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001870 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001871 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001872
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001873 // ~(A & ?) | A = -1
1874 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1875 (A == Op1 || B == Op1))
1876 return Constant::getAllOnesValue(Op1->getType());
1877
1878 // A | ~(A & ?) = -1
1879 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1880 (A == Op0 || B == Op0))
1881 return Constant::getAllOnesValue(Op0->getType());
1882
David Majnemera315bd82014-09-15 08:15:28 +00001883 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1884 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1885 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1886 return V;
1887 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1888 return V;
1889 }
1890 }
1891
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001892 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001893 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1894 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001895 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001896
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001897 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001898 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1899 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001900 return V;
1901
Duncan Sandsb0579e92010-11-10 13:00:08 +00001902 // If the operation is with the result of a select instruction, check whether
1903 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001904 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001905 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001906 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001907 return V;
1908
Nick Lewycky8561a492014-06-19 03:51:46 +00001909 // (A & C)|(B & D)
1910 Value *C = nullptr, *D = nullptr;
1911 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1912 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1913 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1914 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1915 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1916 // (A & C1)|(B & C2)
1917 // If we have: ((V + N) & C1) | (V & C2)
1918 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1919 // replace with V+N.
1920 Value *V1, *V2;
1921 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1922 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1923 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001924 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001925 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001926 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001927 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001928 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001929 return A;
1930 }
1931 // Or commutes, try both ways.
1932 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1933 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1934 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001935 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001936 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001937 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001938 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001939 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001940 return B;
1941 }
1942 }
1943 }
1944
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001945 // If the operation is with the result of a phi instruction, check whether
1946 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001947 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001948 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001949 return V;
1950
Craig Topper9f008862014-04-15 04:59:12 +00001951 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001952}
1953
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001954Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001955 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001956 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00001957 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001958 return ::SimplifyOrInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00001959 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001960}
Chris Lattnera71e9d62009-11-10 00:55:12 +00001961
Sanjay Patel472cc782016-01-11 22:14:42 +00001962/// Given operands for a Xor, see if we can fold the result.
1963/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001964static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1965 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001966 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
1967 return C;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001968
1969 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001970 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001971 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001972
1973 // A ^ 0 = A
1974 if (match(Op1, m_Zero()))
1975 return Op0;
1976
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001977 // A ^ A = 0
1978 if (Op0 == Op1)
1979 return Constant::getNullValue(Op0->getType());
1980
Duncan Sandsc89ac072010-11-17 18:52:15 +00001981 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001982 if (match(Op0, m_Not(m_Specific(Op1))) ||
1983 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001984 return Constant::getAllOnesValue(Op0->getType());
1985
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001986 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001987 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1988 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001989 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001990
Duncan Sandsb238de02010-11-19 09:20:39 +00001991 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1992 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1993 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1994 // only if B and C are equal. If B and C are equal then (since we assume
1995 // that operands have already been simplified) "select(cond, B, C)" should
1996 // have been simplified to the common value of B and C already. Analysing
1997 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1998 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001999
Craig Topper9f008862014-04-15 04:59:12 +00002000 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00002001}
2002
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002003Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00002004 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002005 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00002006 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002007 return ::SimplifyXorInst(Op0, Op1, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00002008 RecursionLimit);
Duncan Sandsc89ac072010-11-17 18:52:15 +00002009}
2010
Chris Lattner229907c2011-07-18 04:54:35 +00002011static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00002012 return CmpInst::makeCmpResultType(Op->getType());
2013}
2014
Sanjay Patel472cc782016-01-11 22:14:42 +00002015/// Rummage around inside V looking for something equivalent to the comparison
2016/// "LHS Pred RHS". Return such a value if found, otherwise return null.
2017/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00002018static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
2019 Value *LHS, Value *RHS) {
2020 SelectInst *SI = dyn_cast<SelectInst>(V);
2021 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00002022 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002023 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2024 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00002025 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002026 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
2027 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
2028 return Cmp;
2029 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
2030 LHS == CmpRHS && RHS == CmpLHS)
2031 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00002032 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00002033}
2034
Dan Gohman9631d902013-02-01 00:49:06 +00002035// A significant optimization not implemented here is assuming that alloca
2036// addresses are not equal to incoming argument values. They don't *alias*,
2037// as we say, but that doesn't mean they aren't equal, so we take a
2038// conservative approach.
2039//
2040// This is inspired in part by C++11 5.10p1:
2041// "Two pointers of the same type compare equal if and only if they are both
2042// null, both point to the same function, or both represent the same
2043// address."
2044//
2045// This is pretty permissive.
2046//
2047// It's also partly due to C11 6.5.9p6:
2048// "Two pointers compare equal if and only if both are null pointers, both are
2049// pointers to the same object (including a pointer to an object and a
2050// subobject at its beginning) or function, both are pointers to one past the
2051// last element of the same array object, or one is a pointer to one past the
2052// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00002053// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00002054// object in the address space.)
2055//
2056// C11's version is more restrictive, however there's no reason why an argument
2057// couldn't be a one-past-the-end value for a stack object in the caller and be
2058// equal to the beginning of a stack object in the callee.
2059//
2060// If the C and C++ standards are ever made sufficiently restrictive in this
2061// area, it may be possible to update LLVM's semantics accordingly and reinstate
2062// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002063static Constant *
2064computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2065 const DominatorTree *DT, CmpInst::Predicate Pred,
2066 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002067 // First, skip past any trivial no-ops.
2068 LHS = LHS->stripPointerCasts();
2069 RHS = RHS->stripPointerCasts();
2070
2071 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002072 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002073 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2074 return ConstantInt::get(GetCompareTy(LHS),
2075 !CmpInst::isTrueWhenEqual(Pred));
2076
Chandler Carruth8059c842012-03-25 21:28:14 +00002077 // We can only fold certain predicates on pointer comparisons.
2078 switch (Pred) {
2079 default:
Craig Topper9f008862014-04-15 04:59:12 +00002080 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002081
2082 // Equality comaprisons are easy to fold.
2083 case CmpInst::ICMP_EQ:
2084 case CmpInst::ICMP_NE:
2085 break;
2086
2087 // We can only handle unsigned relational comparisons because 'inbounds' on
2088 // a GEP only protects against unsigned wrapping.
2089 case CmpInst::ICMP_UGT:
2090 case CmpInst::ICMP_UGE:
2091 case CmpInst::ICMP_ULT:
2092 case CmpInst::ICMP_ULE:
2093 // However, we have to switch them to their signed variants to handle
2094 // negative indices from the base pointer.
2095 Pred = ICmpInst::getSignedPredicate(Pred);
2096 break;
2097 }
2098
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002099 // Strip off any constant offsets so that we can reason about them.
2100 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2101 // here and compare base addresses like AliasAnalysis does, however there are
2102 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2103 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2104 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002105 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2106 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002107
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002108 // If LHS and RHS are related via constant offsets to the same base
2109 // value, we can replace it with an icmp which just compares the offsets.
2110 if (LHS == RHS)
2111 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002112
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002113 // Various optimizations for (in)equality comparisons.
2114 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2115 // Different non-empty allocations that exist at the same time have
2116 // different addresses (if the program can tell). Global variables always
2117 // exist, so they always exist during the lifetime of each other and all
2118 // allocas. Two different allocas usually have different addresses...
2119 //
2120 // However, if there's an @llvm.stackrestore dynamically in between two
2121 // allocas, they may have the same address. It's tempting to reduce the
2122 // scope of the problem by only looking at *static* allocas here. That would
2123 // cover the majority of allocas while significantly reducing the likelihood
2124 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2125 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2126 // an entry block. Also, if we have a block that's not attached to a
2127 // function, we can't tell if it's "static" under the current definition.
2128 // Theoretically, this problem could be fixed by creating a new kind of
2129 // instruction kind specifically for static allocas. Such a new instruction
2130 // could be required to be at the top of the entry block, thus preventing it
2131 // from being subject to a @llvm.stackrestore. Instcombine could even
2132 // convert regular allocas into these special allocas. It'd be nifty.
2133 // However, until then, this problem remains open.
2134 //
2135 // So, we'll assume that two non-empty allocas have different addresses
2136 // for now.
2137 //
2138 // With all that, if the offsets are within the bounds of their allocations
2139 // (and not one-past-the-end! so we can't use inbounds!), and their
2140 // allocations aren't the same, the pointers are not equal.
2141 //
2142 // Note that it's not necessary to check for LHS being a global variable
2143 // address, due to canonicalization and constant folding.
2144 if (isa<AllocaInst>(LHS) &&
2145 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002146 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2147 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002148 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002149 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002150 getObjectSize(LHS, LHSSize, DL, TLI) &&
2151 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002152 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2153 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002154 if (!LHSOffsetValue.isNegative() &&
2155 !RHSOffsetValue.isNegative() &&
2156 LHSOffsetValue.ult(LHSSize) &&
2157 RHSOffsetValue.ult(RHSSize)) {
2158 return ConstantInt::get(GetCompareTy(LHS),
2159 !CmpInst::isTrueWhenEqual(Pred));
2160 }
2161 }
2162
2163 // Repeat the above check but this time without depending on DataLayout
2164 // or being able to compute a precise size.
2165 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2166 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2167 LHSOffset->isNullValue() &&
2168 RHSOffset->isNullValue())
2169 return ConstantInt::get(GetCompareTy(LHS),
2170 !CmpInst::isTrueWhenEqual(Pred));
2171 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002172
2173 // Even if an non-inbounds GEP occurs along the path we can still optimize
2174 // equality comparisons concerning the result. We avoid walking the whole
2175 // chain again by starting where the last calls to
2176 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002177 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2178 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002179 if (LHS == RHS)
2180 return ConstantExpr::getICmp(Pred,
2181 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2182 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002183
2184 // If one side of the equality comparison must come from a noalias call
2185 // (meaning a system memory allocation function), and the other side must
2186 // come from a pointer that cannot overlap with dynamically-allocated
2187 // memory within the lifetime of the current function (allocas, byval
2188 // arguments, globals), then determine the comparison result here.
2189 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2190 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2191 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2192
2193 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002194 auto IsNAC = [](ArrayRef<Value *> Objects) {
2195 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002196 };
2197
2198 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002199 // noalias calls. For allocas, we consider only static ones (dynamic
2200 // allocas might be transformed into calls to malloc not simultaneously
2201 // live with the compared-to allocation). For globals, we exclude symbols
2202 // that might be resolve lazily to symbols in another dynamically-loaded
2203 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002204 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2205 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002206 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2207 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2208 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2209 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002210 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002211 !GV->isThreadLocal();
2212 if (const Argument *A = dyn_cast<Argument>(V))
2213 return A->hasByValAttr();
2214 return false;
2215 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002216 };
2217
2218 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2219 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2220 return ConstantInt::get(GetCompareTy(LHS),
2221 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002222
2223 // Fold comparisons for non-escaping pointer even if the allocation call
2224 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2225 // dynamic allocation call could be either of the operands.
2226 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002227 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002228 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002229 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002230 MI = RHS;
2231 // FIXME: We should also fold the compare when the pointer escapes, but the
2232 // compare dominates the pointer escape
2233 if (MI && !PointerMayBeCaptured(MI, true, true))
2234 return ConstantInt::get(GetCompareTy(LHS),
2235 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002236 }
2237
2238 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002239 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002240}
Chris Lattner01990f02012-02-24 19:01:58 +00002241
Sanjay Pateldc65a272016-12-03 17:30:22 +00002242/// Fold an icmp when its operands have i1 scalar type.
2243static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
2244 Value *RHS, const Query &Q) {
2245 Type *ITy = GetCompareTy(LHS); // The return type.
2246 Type *OpTy = LHS->getType(); // The operand type.
2247 if (!OpTy->getScalarType()->isIntegerTy(1))
2248 return nullptr;
2249
2250 switch (Pred) {
2251 default:
2252 break;
2253 case ICmpInst::ICMP_EQ:
2254 // X == 1 -> X
2255 if (match(RHS, m_One()))
2256 return LHS;
2257 break;
2258 case ICmpInst::ICMP_NE:
2259 // X != 0 -> X
2260 if (match(RHS, m_Zero()))
2261 return LHS;
2262 break;
2263 case ICmpInst::ICMP_UGT:
2264 // X >u 0 -> X
2265 if (match(RHS, m_Zero()))
2266 return LHS;
2267 break;
2268 case ICmpInst::ICMP_UGE:
2269 // X >=u 1 -> X
2270 if (match(RHS, m_One()))
2271 return LHS;
2272 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2273 return getTrue(ITy);
2274 break;
2275 case ICmpInst::ICMP_SGE:
2276 /// For signed comparison, the values for an i1 are 0 and -1
2277 /// respectively. This maps into a truth table of:
2278 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2279 /// 0 | 0 | 1 (0 >= 0) | 1
2280 /// 0 | 1 | 1 (0 >= -1) | 1
2281 /// 1 | 0 | 0 (-1 >= 0) | 0
2282 /// 1 | 1 | 1 (-1 >= -1) | 1
2283 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2284 return getTrue(ITy);
2285 break;
2286 case ICmpInst::ICMP_SLT:
2287 // X <s 0 -> X
2288 if (match(RHS, m_Zero()))
2289 return LHS;
2290 break;
2291 case ICmpInst::ICMP_SLE:
2292 // X <=s -1 -> X
2293 if (match(RHS, m_One()))
2294 return LHS;
2295 break;
2296 case ICmpInst::ICMP_ULE:
2297 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2298 return getTrue(ITy);
2299 break;
2300 }
2301
2302 return nullptr;
2303}
2304
2305/// Try hard to fold icmp with zero RHS because this is a common case.
2306static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
2307 Value *RHS, const Query &Q) {
2308 if (!match(RHS, m_Zero()))
2309 return nullptr;
2310
2311 Type *ITy = GetCompareTy(LHS); // The return type.
2312 bool LHSKnownNonNegative, LHSKnownNegative;
2313 switch (Pred) {
2314 default:
2315 llvm_unreachable("Unknown ICmp predicate!");
2316 case ICmpInst::ICMP_ULT:
2317 return getFalse(ITy);
2318 case ICmpInst::ICMP_UGE:
2319 return getTrue(ITy);
2320 case ICmpInst::ICMP_EQ:
2321 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002322 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002323 return getFalse(ITy);
2324 break;
2325 case ICmpInst::ICMP_NE:
2326 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002327 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002328 return getTrue(ITy);
2329 break;
2330 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002331 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2332 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002333 if (LHSKnownNegative)
2334 return getTrue(ITy);
2335 if (LHSKnownNonNegative)
2336 return getFalse(ITy);
2337 break;
2338 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002339 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2340 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002341 if (LHSKnownNegative)
2342 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002343 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002344 return getFalse(ITy);
2345 break;
2346 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002347 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2348 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002349 if (LHSKnownNegative)
2350 return getFalse(ITy);
2351 if (LHSKnownNonNegative)
2352 return getTrue(ITy);
2353 break;
2354 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002355 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2356 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002357 if (LHSKnownNegative)
2358 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002359 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002360 return getTrue(ITy);
2361 break;
2362 }
2363
2364 return nullptr;
2365}
2366
Sanjay Patelbe332132017-01-23 18:22:26 +00002367/// Many binary operators with a constant operand have an easy-to-compute
2368/// range of outputs. This can be used to fold a comparison to always true or
2369/// always false.
2370static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2371 unsigned Width = Lower.getBitWidth();
2372 const APInt *C;
2373 switch (BO.getOpcode()) {
2374 case Instruction::Add:
Sanjay Patel56227252017-01-24 17:03:24 +00002375 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2376 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2377 if (BO.hasNoUnsignedWrap()) {
2378 // 'add nuw x, C' produces [C, UINT_MAX].
2379 Lower = *C;
2380 } else if (BO.hasNoSignedWrap()) {
2381 if (C->isNegative()) {
2382 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2383 Lower = APInt::getSignedMinValue(Width);
2384 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2385 } else {
2386 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2387 Lower = APInt::getSignedMinValue(Width) + *C;
2388 Upper = APInt::getSignedMaxValue(Width) + 1;
2389 }
2390 }
2391 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002392 break;
2393
2394 case Instruction::And:
2395 if (match(BO.getOperand(1), m_APInt(C)))
2396 // 'and x, C' produces [0, C].
2397 Upper = *C + 1;
2398 break;
2399
2400 case Instruction::Or:
2401 if (match(BO.getOperand(1), m_APInt(C)))
2402 // 'or x, C' produces [C, UINT_MAX].
2403 Lower = *C;
2404 break;
2405
2406 case Instruction::AShr:
2407 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2408 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2409 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2410 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2411 } else if (match(BO.getOperand(0), m_APInt(C))) {
2412 unsigned ShiftAmount = Width - 1;
2413 if (*C != 0 && BO.isExact())
2414 ShiftAmount = C->countTrailingZeros();
2415 if (C->isNegative()) {
2416 // 'ashr C, x' produces [C, C >> (Width-1)]
2417 Lower = *C;
2418 Upper = C->ashr(ShiftAmount) + 1;
2419 } else {
2420 // 'ashr C, x' produces [C >> (Width-1), C]
2421 Lower = C->ashr(ShiftAmount);
2422 Upper = *C + 1;
2423 }
2424 }
2425 break;
2426
2427 case Instruction::LShr:
2428 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2429 // 'lshr x, C' produces [0, UINT_MAX >> C].
2430 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2431 } else if (match(BO.getOperand(0), m_APInt(C))) {
2432 // 'lshr C, x' produces [C >> (Width-1), C].
2433 unsigned ShiftAmount = Width - 1;
2434 if (*C != 0 && BO.isExact())
2435 ShiftAmount = C->countTrailingZeros();
2436 Lower = C->lshr(ShiftAmount);
2437 Upper = *C + 1;
2438 }
2439 break;
2440
2441 case Instruction::Shl:
2442 if (match(BO.getOperand(0), m_APInt(C))) {
2443 if (BO.hasNoUnsignedWrap()) {
2444 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2445 Lower = *C;
2446 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2447 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2448 if (C->isNegative()) {
2449 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2450 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2451 Lower = C->shl(ShiftAmount);
2452 Upper = *C + 1;
2453 } else {
2454 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2455 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2456 Lower = *C;
2457 Upper = C->shl(ShiftAmount) + 1;
2458 }
2459 }
2460 }
2461 break;
2462
2463 case Instruction::SDiv:
2464 if (match(BO.getOperand(1), m_APInt(C))) {
2465 APInt IntMin = APInt::getSignedMinValue(Width);
2466 APInt IntMax = APInt::getSignedMaxValue(Width);
2467 if (C->isAllOnesValue()) {
2468 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2469 // where C != -1 and C != 0 and C != 1
2470 Lower = IntMin + 1;
2471 Upper = IntMax + 1;
2472 } else if (C->countLeadingZeros() < Width - 1) {
2473 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2474 // where C != -1 and C != 0 and C != 1
2475 Lower = IntMin.sdiv(*C);
2476 Upper = IntMax.sdiv(*C);
2477 if (Lower.sgt(Upper))
2478 std::swap(Lower, Upper);
2479 Upper = Upper + 1;
2480 assert(Upper != Lower && "Upper part of range has wrapped!");
2481 }
2482 } else if (match(BO.getOperand(0), m_APInt(C))) {
2483 if (C->isMinSignedValue()) {
2484 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2485 Lower = *C;
2486 Upper = Lower.lshr(1) + 1;
2487 } else {
2488 // 'sdiv C, x' produces [-|C|, |C|].
2489 Upper = C->abs() + 1;
2490 Lower = (-Upper) + 1;
2491 }
2492 }
2493 break;
2494
2495 case Instruction::UDiv:
2496 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2497 // 'udiv x, C' produces [0, UINT_MAX / C].
2498 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2499 } else if (match(BO.getOperand(0), m_APInt(C))) {
2500 // 'udiv C, x' produces [0, C].
2501 Upper = *C + 1;
2502 }
2503 break;
2504
2505 case Instruction::SRem:
2506 if (match(BO.getOperand(1), m_APInt(C))) {
2507 // 'srem x, C' produces (-|C|, |C|).
2508 Upper = C->abs();
2509 Lower = (-Upper) + 1;
2510 }
2511 break;
2512
2513 case Instruction::URem:
2514 if (match(BO.getOperand(1), m_APInt(C)))
2515 // 'urem x, C' produces [0, C).
2516 Upper = *C;
2517 break;
2518
2519 default:
2520 break;
2521 }
2522}
2523
Sanjay Patel67bde282016-08-22 23:12:02 +00002524static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2525 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002526 const APInt *C;
2527 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002528 return nullptr;
2529
2530 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002531 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002532 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002533 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002534 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002535 return ConstantInt::getTrue(GetCompareTy(RHS));
2536
Sanjay Patelbe332132017-01-23 18:22:26 +00002537 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002538 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002539 APInt Lower = APInt(Width, 0);
2540 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002541 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2542 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002543
2544 ConstantRange LHS_CR =
2545 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2546
2547 if (auto *I = dyn_cast<Instruction>(LHS))
2548 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2549 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2550
2551 if (!LHS_CR.isFullSet()) {
2552 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002553 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002554 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002555 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002556 }
2557
2558 return nullptr;
2559}
2560
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002561static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
2562 Value *RHS, const Query &Q,
2563 unsigned MaxRecurse) {
2564 Type *ITy = GetCompareTy(LHS); // The return type.
2565
2566 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2567 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2568 if (MaxRecurse && (LBO || RBO)) {
2569 // Analyze the case when either LHS or RHS is an add instruction.
2570 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2571 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2572 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2573 if (LBO && LBO->getOpcode() == Instruction::Add) {
2574 A = LBO->getOperand(0);
2575 B = LBO->getOperand(1);
2576 NoLHSWrapProblem =
2577 ICmpInst::isEquality(Pred) ||
2578 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2579 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2580 }
2581 if (RBO && RBO->getOpcode() == Instruction::Add) {
2582 C = RBO->getOperand(0);
2583 D = RBO->getOperand(1);
2584 NoRHSWrapProblem =
2585 ICmpInst::isEquality(Pred) ||
2586 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2587 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2588 }
2589
2590 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2591 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2592 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2593 Constant::getNullValue(RHS->getType()), Q,
2594 MaxRecurse - 1))
2595 return V;
2596
2597 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2598 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2599 if (Value *V =
2600 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2601 C == LHS ? D : C, Q, MaxRecurse - 1))
2602 return V;
2603
2604 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2605 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2606 NoRHSWrapProblem) {
2607 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2608 Value *Y, *Z;
2609 if (A == C) {
2610 // C + B == C + D -> B == D
2611 Y = B;
2612 Z = D;
2613 } else if (A == D) {
2614 // D + B == C + D -> B == C
2615 Y = B;
2616 Z = C;
2617 } else if (B == C) {
2618 // A + C == C + D -> A == D
2619 Y = A;
2620 Z = D;
2621 } else {
2622 assert(B == D);
2623 // A + D == C + D -> A == C
2624 Y = A;
2625 Z = C;
2626 }
2627 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2628 return V;
2629 }
2630 }
2631
2632 {
2633 Value *Y = nullptr;
2634 // icmp pred (or X, Y), X
2635 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2636 if (Pred == ICmpInst::ICMP_ULT)
2637 return getFalse(ITy);
2638 if (Pred == ICmpInst::ICMP_UGE)
2639 return getTrue(ITy);
2640
2641 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2642 bool RHSKnownNonNegative, RHSKnownNegative;
2643 bool YKnownNonNegative, YKnownNegative;
2644 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002645 Q.AC, Q.CxtI, Q.DT);
2646 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002647 Q.CxtI, Q.DT);
2648 if (RHSKnownNonNegative && YKnownNegative)
2649 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2650 if (RHSKnownNegative || YKnownNonNegative)
2651 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2652 }
2653 }
2654 // icmp pred X, (or X, Y)
2655 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2656 if (Pred == ICmpInst::ICMP_ULE)
2657 return getTrue(ITy);
2658 if (Pred == ICmpInst::ICMP_UGT)
2659 return getFalse(ITy);
2660
2661 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2662 bool LHSKnownNonNegative, LHSKnownNegative;
2663 bool YKnownNonNegative, YKnownNegative;
2664 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002665 Q.AC, Q.CxtI, Q.DT);
2666 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002667 Q.CxtI, Q.DT);
2668 if (LHSKnownNonNegative && YKnownNegative)
2669 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2670 if (LHSKnownNegative || YKnownNonNegative)
2671 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2672 }
2673 }
2674 }
2675
2676 // icmp pred (and X, Y), X
2677 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2678 m_And(m_Specific(RHS), m_Value())))) {
2679 if (Pred == ICmpInst::ICMP_UGT)
2680 return getFalse(ITy);
2681 if (Pred == ICmpInst::ICMP_ULE)
2682 return getTrue(ITy);
2683 }
2684 // icmp pred X, (and X, Y)
2685 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2686 m_And(m_Specific(LHS), m_Value())))) {
2687 if (Pred == ICmpInst::ICMP_UGE)
2688 return getTrue(ITy);
2689 if (Pred == ICmpInst::ICMP_ULT)
2690 return getFalse(ITy);
2691 }
2692
2693 // 0 - (zext X) pred C
2694 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2695 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2696 if (RHSC->getValue().isStrictlyPositive()) {
2697 if (Pred == ICmpInst::ICMP_SLT)
2698 return ConstantInt::getTrue(RHSC->getContext());
2699 if (Pred == ICmpInst::ICMP_SGE)
2700 return ConstantInt::getFalse(RHSC->getContext());
2701 if (Pred == ICmpInst::ICMP_EQ)
2702 return ConstantInt::getFalse(RHSC->getContext());
2703 if (Pred == ICmpInst::ICMP_NE)
2704 return ConstantInt::getTrue(RHSC->getContext());
2705 }
2706 if (RHSC->getValue().isNonNegative()) {
2707 if (Pred == ICmpInst::ICMP_SLE)
2708 return ConstantInt::getTrue(RHSC->getContext());
2709 if (Pred == ICmpInst::ICMP_SGT)
2710 return ConstantInt::getFalse(RHSC->getContext());
2711 }
2712 }
2713 }
2714
2715 // icmp pred (urem X, Y), Y
2716 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2717 bool KnownNonNegative, KnownNegative;
2718 switch (Pred) {
2719 default:
2720 break;
2721 case ICmpInst::ICMP_SGT:
2722 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002723 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2724 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002725 if (!KnownNonNegative)
2726 break;
2727 LLVM_FALLTHROUGH;
2728 case ICmpInst::ICMP_EQ:
2729 case ICmpInst::ICMP_UGT:
2730 case ICmpInst::ICMP_UGE:
2731 return getFalse(ITy);
2732 case ICmpInst::ICMP_SLT:
2733 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002734 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2735 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002736 if (!KnownNonNegative)
2737 break;
2738 LLVM_FALLTHROUGH;
2739 case ICmpInst::ICMP_NE:
2740 case ICmpInst::ICMP_ULT:
2741 case ICmpInst::ICMP_ULE:
2742 return getTrue(ITy);
2743 }
2744 }
2745
2746 // icmp pred X, (urem Y, X)
2747 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2748 bool KnownNonNegative, KnownNegative;
2749 switch (Pred) {
2750 default:
2751 break;
2752 case ICmpInst::ICMP_SGT:
2753 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002754 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2755 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002756 if (!KnownNonNegative)
2757 break;
2758 LLVM_FALLTHROUGH;
2759 case ICmpInst::ICMP_NE:
2760 case ICmpInst::ICMP_UGT:
2761 case ICmpInst::ICMP_UGE:
2762 return getTrue(ITy);
2763 case ICmpInst::ICMP_SLT:
2764 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002765 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2766 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002767 if (!KnownNonNegative)
2768 break;
2769 LLVM_FALLTHROUGH;
2770 case ICmpInst::ICMP_EQ:
2771 case ICmpInst::ICMP_ULT:
2772 case ICmpInst::ICMP_ULE:
2773 return getFalse(ITy);
2774 }
2775 }
2776
2777 // x >> y <=u x
2778 // x udiv y <=u x.
2779 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2780 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2781 // icmp pred (X op Y), X
2782 if (Pred == ICmpInst::ICMP_UGT)
2783 return getFalse(ITy);
2784 if (Pred == ICmpInst::ICMP_ULE)
2785 return getTrue(ITy);
2786 }
2787
2788 // x >=u x >> y
2789 // x >=u x udiv y.
2790 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2791 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2792 // icmp pred X, (X op Y)
2793 if (Pred == ICmpInst::ICMP_ULT)
2794 return getFalse(ITy);
2795 if (Pred == ICmpInst::ICMP_UGE)
2796 return getTrue(ITy);
2797 }
2798
2799 // handle:
2800 // CI2 << X == CI
2801 // CI2 << X != CI
2802 //
2803 // where CI2 is a power of 2 and CI isn't
2804 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2805 const APInt *CI2Val, *CIVal = &CI->getValue();
2806 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2807 CI2Val->isPowerOf2()) {
2808 if (!CIVal->isPowerOf2()) {
2809 // CI2 << X can equal zero in some circumstances,
2810 // this simplification is unsafe if CI is zero.
2811 //
2812 // We know it is safe if:
2813 // - The shift is nsw, we can't shift out the one bit.
2814 // - The shift is nuw, we can't shift out the one bit.
2815 // - CI2 is one
2816 // - CI isn't zero
2817 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2818 *CI2Val == 1 || !CI->isZero()) {
2819 if (Pred == ICmpInst::ICMP_EQ)
2820 return ConstantInt::getFalse(RHS->getContext());
2821 if (Pred == ICmpInst::ICMP_NE)
2822 return ConstantInt::getTrue(RHS->getContext());
2823 }
2824 }
2825 if (CIVal->isSignBit() && *CI2Val == 1) {
2826 if (Pred == ICmpInst::ICMP_UGT)
2827 return ConstantInt::getFalse(RHS->getContext());
2828 if (Pred == ICmpInst::ICMP_ULE)
2829 return ConstantInt::getTrue(RHS->getContext());
2830 }
2831 }
2832 }
2833
2834 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2835 LBO->getOperand(1) == RBO->getOperand(1)) {
2836 switch (LBO->getOpcode()) {
2837 default:
2838 break;
2839 case Instruction::UDiv:
2840 case Instruction::LShr:
2841 if (ICmpInst::isSigned(Pred))
2842 break;
2843 LLVM_FALLTHROUGH;
2844 case Instruction::SDiv:
2845 case Instruction::AShr:
2846 if (!LBO->isExact() || !RBO->isExact())
2847 break;
2848 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2849 RBO->getOperand(0), Q, MaxRecurse - 1))
2850 return V;
2851 break;
2852 case Instruction::Shl: {
2853 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2854 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2855 if (!NUW && !NSW)
2856 break;
2857 if (!NSW && ICmpInst::isSigned(Pred))
2858 break;
2859 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2860 RBO->getOperand(0), Q, MaxRecurse - 1))
2861 return V;
2862 break;
2863 }
2864 }
2865 }
2866 return nullptr;
2867}
2868
Sanjay Patel35289c62016-12-10 17:40:47 +00002869/// Simplify integer comparisons where at least one operand of the compare
2870/// matches an integer min/max idiom.
2871static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
2872 Value *RHS, const Query &Q,
2873 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002874 Type *ITy = GetCompareTy(LHS); // The return type.
2875 Value *A, *B;
2876 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2877 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2878
2879 // Signed variants on "max(a,b)>=a -> true".
2880 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2881 if (A != RHS)
2882 std::swap(A, B); // smax(A, B) pred A.
2883 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2884 // We analyze this as smax(A, B) pred A.
2885 P = Pred;
2886 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2887 (A == LHS || B == LHS)) {
2888 if (A != LHS)
2889 std::swap(A, B); // A pred smax(A, B).
2890 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2891 // We analyze this as smax(A, B) swapped-pred A.
2892 P = CmpInst::getSwappedPredicate(Pred);
2893 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2894 (A == RHS || B == RHS)) {
2895 if (A != RHS)
2896 std::swap(A, B); // smin(A, B) pred A.
2897 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2898 // We analyze this as smax(-A, -B) swapped-pred -A.
2899 // Note that we do not need to actually form -A or -B thanks to EqP.
2900 P = CmpInst::getSwappedPredicate(Pred);
2901 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2902 (A == LHS || B == LHS)) {
2903 if (A != LHS)
2904 std::swap(A, B); // A pred smin(A, B).
2905 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2906 // We analyze this as smax(-A, -B) pred -A.
2907 // Note that we do not need to actually form -A or -B thanks to EqP.
2908 P = Pred;
2909 }
2910 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2911 // Cases correspond to "max(A, B) p A".
2912 switch (P) {
2913 default:
2914 break;
2915 case CmpInst::ICMP_EQ:
2916 case CmpInst::ICMP_SLE:
2917 // Equivalent to "A EqP B". This may be the same as the condition tested
2918 // in the max/min; if so, we can just return that.
2919 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2920 return V;
2921 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2922 return V;
2923 // Otherwise, see if "A EqP B" simplifies.
2924 if (MaxRecurse)
2925 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2926 return V;
2927 break;
2928 case CmpInst::ICMP_NE:
2929 case CmpInst::ICMP_SGT: {
2930 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2931 // Equivalent to "A InvEqP B". This may be the same as the condition
2932 // tested in the max/min; if so, we can just return that.
2933 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2934 return V;
2935 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2936 return V;
2937 // Otherwise, see if "A InvEqP B" simplifies.
2938 if (MaxRecurse)
2939 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2940 return V;
2941 break;
2942 }
2943 case CmpInst::ICMP_SGE:
2944 // Always true.
2945 return getTrue(ITy);
2946 case CmpInst::ICMP_SLT:
2947 // Always false.
2948 return getFalse(ITy);
2949 }
2950 }
2951
2952 // Unsigned variants on "max(a,b)>=a -> true".
2953 P = CmpInst::BAD_ICMP_PREDICATE;
2954 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2955 if (A != RHS)
2956 std::swap(A, B); // umax(A, B) pred A.
2957 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2958 // We analyze this as umax(A, B) pred A.
2959 P = Pred;
2960 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2961 (A == LHS || B == LHS)) {
2962 if (A != LHS)
2963 std::swap(A, B); // A pred umax(A, B).
2964 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2965 // We analyze this as umax(A, B) swapped-pred A.
2966 P = CmpInst::getSwappedPredicate(Pred);
2967 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2968 (A == RHS || B == RHS)) {
2969 if (A != RHS)
2970 std::swap(A, B); // umin(A, B) pred A.
2971 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2972 // We analyze this as umax(-A, -B) swapped-pred -A.
2973 // Note that we do not need to actually form -A or -B thanks to EqP.
2974 P = CmpInst::getSwappedPredicate(Pred);
2975 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2976 (A == LHS || B == LHS)) {
2977 if (A != LHS)
2978 std::swap(A, B); // A pred umin(A, B).
2979 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2980 // We analyze this as umax(-A, -B) pred -A.
2981 // Note that we do not need to actually form -A or -B thanks to EqP.
2982 P = Pred;
2983 }
2984 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2985 // Cases correspond to "max(A, B) p A".
2986 switch (P) {
2987 default:
2988 break;
2989 case CmpInst::ICMP_EQ:
2990 case CmpInst::ICMP_ULE:
2991 // Equivalent to "A EqP B". This may be the same as the condition tested
2992 // in the max/min; if so, we can just return that.
2993 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2994 return V;
2995 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2996 return V;
2997 // Otherwise, see if "A EqP B" simplifies.
2998 if (MaxRecurse)
2999 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
3000 return V;
3001 break;
3002 case CmpInst::ICMP_NE:
3003 case CmpInst::ICMP_UGT: {
3004 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
3005 // Equivalent to "A InvEqP B". This may be the same as the condition
3006 // tested in the max/min; if so, we can just return that.
3007 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
3008 return V;
3009 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
3010 return V;
3011 // Otherwise, see if "A InvEqP B" simplifies.
3012 if (MaxRecurse)
3013 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
3014 return V;
3015 break;
3016 }
3017 case CmpInst::ICMP_UGE:
3018 // Always true.
3019 return getTrue(ITy);
3020 case CmpInst::ICMP_ULT:
3021 // Always false.
3022 return getFalse(ITy);
3023 }
3024 }
3025
3026 // Variants on "max(x,y) >= min(x,z)".
3027 Value *C, *D;
3028 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
3029 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
3030 (A == C || A == D || B == C || B == D)) {
3031 // max(x, ?) pred min(x, ?).
3032 if (Pred == CmpInst::ICMP_SGE)
3033 // Always true.
3034 return getTrue(ITy);
3035 if (Pred == CmpInst::ICMP_SLT)
3036 // Always false.
3037 return getFalse(ITy);
3038 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
3039 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
3040 (A == C || A == D || B == C || B == D)) {
3041 // min(x, ?) pred max(x, ?).
3042 if (Pred == CmpInst::ICMP_SLE)
3043 // Always true.
3044 return getTrue(ITy);
3045 if (Pred == CmpInst::ICMP_SGT)
3046 // Always false.
3047 return getFalse(ITy);
3048 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
3049 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
3050 (A == C || A == D || B == C || B == D)) {
3051 // max(x, ?) pred min(x, ?).
3052 if (Pred == CmpInst::ICMP_UGE)
3053 // Always true.
3054 return getTrue(ITy);
3055 if (Pred == CmpInst::ICMP_ULT)
3056 // Always false.
3057 return getFalse(ITy);
3058 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
3059 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
3060 (A == C || A == D || B == C || B == D)) {
3061 // min(x, ?) pred max(x, ?).
3062 if (Pred == CmpInst::ICMP_ULE)
3063 // Always true.
3064 return getTrue(ITy);
3065 if (Pred == CmpInst::ICMP_UGT)
3066 // Always false.
3067 return getFalse(ITy);
3068 }
3069
3070 return nullptr;
3071}
3072
Sanjay Patel472cc782016-01-11 22:14:42 +00003073/// Given operands for an ICmpInst, see if we can fold the result.
3074/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003075static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003076 const Query &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003077 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003078 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003079
Chris Lattnera71e9d62009-11-10 00:55:12 +00003080 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003081 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003082 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003083
3084 // If we have a constant, make sure it is on the RHS.
3085 std::swap(LHS, RHS);
3086 Pred = CmpInst::getSwappedPredicate(Pred);
3087 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003088
Chris Lattner229907c2011-07-18 04:54:35 +00003089 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003090
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003091 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003092 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3093 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003094 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003095 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003096
Sanjay Pateldc65a272016-12-03 17:30:22 +00003097 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3098 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003099
Sanjay Pateldc65a272016-12-03 17:30:22 +00003100 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3101 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003102
Sanjay Patel67bde282016-08-22 23:12:02 +00003103 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3104 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003105
Chen Li7452d952015-09-26 03:26:47 +00003106 // If both operands have range metadata, use the metadata
3107 // to simplify the comparison.
3108 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
3109 auto RHS_Instr = dyn_cast<Instruction>(RHS);
3110 auto LHS_Instr = dyn_cast<Instruction>(LHS);
3111
3112 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3113 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003114 auto RHS_CR = getConstantRangeFromMetadata(
3115 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3116 auto LHS_CR = getConstantRangeFromMetadata(
3117 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003118
3119 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3120 if (Satisfied_CR.contains(LHS_CR))
3121 return ConstantInt::getTrue(RHS->getContext());
3122
3123 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3124 CmpInst::getInversePredicate(Pred), RHS_CR);
3125 if (InversedSatisfied_CR.contains(LHS_CR))
3126 return ConstantInt::getFalse(RHS->getContext());
3127 }
3128 }
3129
Duncan Sands8fb2c382011-01-20 13:21:55 +00003130 // Compare of cast, for example (zext X) != 0 -> X != 0
3131 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3132 Instruction *LI = cast<CastInst>(LHS);
3133 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003134 Type *SrcTy = SrcOp->getType();
3135 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003136
3137 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3138 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003139 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3140 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003141 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3142 // Transfer the cast to the constant.
3143 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3144 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003145 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003146 return V;
3147 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3148 if (RI->getOperand(0)->getType() == SrcTy)
3149 // Compare without the cast.
3150 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003151 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003152 return V;
3153 }
3154 }
3155
3156 if (isa<ZExtInst>(LHS)) {
3157 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3158 // same type.
3159 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3160 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3161 // Compare X and Y. Note that signed predicates become unsigned.
3162 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003163 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003164 MaxRecurse-1))
3165 return V;
3166 }
3167 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3168 // too. If not, then try to deduce the result of the comparison.
3169 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3170 // Compute the constant that would happen if we truncated to SrcTy then
3171 // reextended to DstTy.
3172 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3173 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3174
3175 // If the re-extended constant didn't change then this is effectively
3176 // also a case of comparing two zero-extended values.
3177 if (RExt == CI && MaxRecurse)
3178 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003179 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003180 return V;
3181
3182 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3183 // there. Use this to work out the result of the comparison.
3184 if (RExt != CI) {
3185 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003186 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003187 // LHS <u RHS.
3188 case ICmpInst::ICMP_EQ:
3189 case ICmpInst::ICMP_UGT:
3190 case ICmpInst::ICMP_UGE:
3191 return ConstantInt::getFalse(CI->getContext());
3192
3193 case ICmpInst::ICMP_NE:
3194 case ICmpInst::ICMP_ULT:
3195 case ICmpInst::ICMP_ULE:
3196 return ConstantInt::getTrue(CI->getContext());
3197
3198 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3199 // is non-negative then LHS <s RHS.
3200 case ICmpInst::ICMP_SGT:
3201 case ICmpInst::ICMP_SGE:
3202 return CI->getValue().isNegative() ?
3203 ConstantInt::getTrue(CI->getContext()) :
3204 ConstantInt::getFalse(CI->getContext());
3205
3206 case ICmpInst::ICMP_SLT:
3207 case ICmpInst::ICMP_SLE:
3208 return CI->getValue().isNegative() ?
3209 ConstantInt::getFalse(CI->getContext()) :
3210 ConstantInt::getTrue(CI->getContext());
3211 }
3212 }
3213 }
3214 }
3215
3216 if (isa<SExtInst>(LHS)) {
3217 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3218 // same type.
3219 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3220 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3221 // Compare X and Y. Note that the predicate does not change.
3222 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003223 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003224 return V;
3225 }
3226 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3227 // too. If not, then try to deduce the result of the comparison.
3228 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3229 // Compute the constant that would happen if we truncated to SrcTy then
3230 // reextended to DstTy.
3231 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3232 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3233
3234 // If the re-extended constant didn't change then this is effectively
3235 // also a case of comparing two sign-extended values.
3236 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003237 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003238 return V;
3239
3240 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3241 // bits there. Use this to work out the result of the comparison.
3242 if (RExt != CI) {
3243 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003244 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003245 case ICmpInst::ICMP_EQ:
3246 return ConstantInt::getFalse(CI->getContext());
3247 case ICmpInst::ICMP_NE:
3248 return ConstantInt::getTrue(CI->getContext());
3249
3250 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3251 // LHS >s RHS.
3252 case ICmpInst::ICMP_SGT:
3253 case ICmpInst::ICMP_SGE:
3254 return CI->getValue().isNegative() ?
3255 ConstantInt::getTrue(CI->getContext()) :
3256 ConstantInt::getFalse(CI->getContext());
3257 case ICmpInst::ICMP_SLT:
3258 case ICmpInst::ICMP_SLE:
3259 return CI->getValue().isNegative() ?
3260 ConstantInt::getFalse(CI->getContext()) :
3261 ConstantInt::getTrue(CI->getContext());
3262
3263 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3264 // LHS >u RHS.
3265 case ICmpInst::ICMP_UGT:
3266 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003267 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003268 if (MaxRecurse)
3269 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3270 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003271 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003272 return V;
3273 break;
3274 case ICmpInst::ICMP_ULT:
3275 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003276 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003277 if (MaxRecurse)
3278 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3279 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003280 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003281 return V;
3282 break;
3283 }
3284 }
3285 }
3286 }
3287 }
3288
James Molloy1d88d6f2015-10-22 13:18:42 +00003289 // icmp eq|ne X, Y -> false|true if X != Y
3290 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003291 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003292 LLVMContext &Ctx = LHS->getType()->getContext();
3293 return Pred == ICmpInst::ICMP_NE ?
3294 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3295 }
Junmo Park53470fc2016-04-05 21:14:31 +00003296
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003297 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3298 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003299
Sanjay Patel35289c62016-12-10 17:40:47 +00003300 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003301 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003302
Chandler Carruth8059c842012-03-25 21:28:14 +00003303 // Simplify comparisons of related pointers using a powerful, recursive
3304 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003305 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003306 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003307 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003308 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3309 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3310 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3311 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3312 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3313 Q.DL.getTypeSizeInBits(CRHS->getType()))
3314 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3315 CLHS->getPointerOperand(),
3316 CRHS->getPointerOperand()))
3317 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003318
Nick Lewycky3db143e2012-02-26 02:09:49 +00003319 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3320 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3321 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3322 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3323 (ICmpInst::isEquality(Pred) ||
3324 (GLHS->isInBounds() && GRHS->isInBounds() &&
3325 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3326 // The bases are equal and the indices are constant. Build a constant
3327 // expression GEP with the same indices and a null base pointer to see
3328 // what constant folding can make out of it.
3329 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3330 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003331 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3332 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003333
3334 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003335 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3336 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003337 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3338 }
3339 }
3340 }
3341
David Majnemer5854e9f2014-11-16 02:20:08 +00003342 // If a bit is known to be zero for A and known to be one for B,
3343 // then A and B cannot be equal.
3344 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003345 const APInt *RHSVal;
3346 if (match(RHS, m_APInt(RHSVal))) {
3347 unsigned BitWidth = RHSVal->getBitWidth();
David Majnemer5854e9f2014-11-16 02:20:08 +00003348 APInt LHSKnownZero(BitWidth, 0);
3349 APInt LHSKnownOne(BitWidth, 0);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003350 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL, /*Depth=*/0, Q.AC,
David Majnemer5854e9f2014-11-16 02:20:08 +00003351 Q.CxtI, Q.DT);
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003352 if (((LHSKnownZero & *RHSVal) != 0) || ((LHSKnownOne & ~(*RHSVal)) != 0))
3353 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3354 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003355 }
3356 }
3357
Duncan Sandsf532d312010-11-07 16:12:23 +00003358 // If the comparison is with the result of a select instruction, check whether
3359 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003360 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003361 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003362 return V;
3363
3364 // If the comparison is with the result of a phi instruction, check whether
3365 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003366 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003367 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003368 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003369
Craig Topper9f008862014-04-15 04:59:12 +00003370 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003371}
3372
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003373Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003374 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003375 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003376 const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth85dbea92015-12-24 09:08:08 +00003377 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003378 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003379 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003380}
3381
Sanjay Patel472cc782016-01-11 22:14:42 +00003382/// Given operands for an FCmpInst, see if we can fold the result.
3383/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003384static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003385 FastMathFlags FMF, const Query &Q,
3386 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003387 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3388 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3389
Chris Lattnera71e9d62009-11-10 00:55:12 +00003390 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003391 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003392 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003393
Chris Lattnera71e9d62009-11-10 00:55:12 +00003394 // If we have a constant, make sure it is on the RHS.
3395 std::swap(LHS, RHS);
3396 Pred = CmpInst::getSwappedPredicate(Pred);
3397 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003398
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003399 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003400 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003401 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003402 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003403 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003404 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003405
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003406 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3407 if (FMF.noNaNs()) {
3408 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003409 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003410 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003411 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003412 }
3413
Mehdi Aminieb242a52015-03-09 03:20:25 +00003414 // fcmp pred x, undef and fcmp pred undef, x
3415 // fold to true if unordered, false if ordered
3416 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3417 // Choosing NaN for the undef will always make unordered comparison succeed
3418 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003419 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003420 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003421
3422 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003423 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003424 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003425 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003426 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003427 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003428 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003429
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003430 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003431 const ConstantFP *CFP = nullptr;
3432 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3433 if (RHS->getType()->isVectorTy())
3434 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3435 else
3436 CFP = dyn_cast<ConstantFP>(RHSC);
3437 }
3438 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003439 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003440 if (CFP->getValueAPF().isNaN()) {
3441 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003442 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003443 assert(FCmpInst::isUnordered(Pred) &&
3444 "Comparison must be either ordered or unordered!");
3445 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003446 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003447 }
3448 // Check whether the constant is an infinity.
3449 if (CFP->getValueAPF().isInfinity()) {
3450 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003451 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003452 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003453 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003454 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003455 case FCmpInst::FCMP_UGE:
3456 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003457 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003458 default:
3459 break;
3460 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003461 } else {
3462 switch (Pred) {
3463 case FCmpInst::FCMP_OGT:
3464 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003465 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003466 case FCmpInst::FCMP_ULE:
3467 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003468 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003469 default:
3470 break;
3471 }
3472 }
3473 }
3474 if (CFP->getValueAPF().isZero()) {
3475 switch (Pred) {
3476 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003477 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003478 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003479 break;
3480 case FCmpInst::FCMP_OLT:
3481 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003482 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003483 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003484 break;
3485 default:
3486 break;
3487 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003488 }
3489 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003490
Duncan Sandsa620bd12010-11-07 16:46:25 +00003491 // If the comparison is with the result of a select instruction, check whether
3492 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003493 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003494 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003495 return V;
3496
3497 // If the comparison is with the result of a phi instruction, check whether
3498 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003499 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003500 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003501 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003502
Craig Topper9f008862014-04-15 04:59:12 +00003503 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003504}
3505
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003506Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003507 FastMathFlags FMF, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00003508 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003509 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003510 const Instruction *CxtI) {
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003511 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003512 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003513}
3514
Sanjay Patel472cc782016-01-11 22:14:42 +00003515/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003516static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
3517 const Query &Q,
3518 unsigned MaxRecurse) {
3519 // Trivial replacement.
3520 if (V == Op)
3521 return RepOp;
3522
3523 auto *I = dyn_cast<Instruction>(V);
3524 if (!I)
3525 return nullptr;
3526
3527 // If this is a binary operator, try to simplify it with the replaced op.
3528 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3529 // Consider:
3530 // %cmp = icmp eq i32 %x, 2147483647
3531 // %add = add nsw i32 %x, 1
3532 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3533 //
3534 // We can't replace %sel with %add unless we strip away the flags.
3535 if (isa<OverflowingBinaryOperator>(B))
3536 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3537 return nullptr;
3538 if (isa<PossiblyExactOperator>(B))
3539 if (B->isExact())
3540 return nullptr;
3541
3542 if (MaxRecurse) {
3543 if (B->getOperand(0) == Op)
3544 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3545 MaxRecurse - 1);
3546 if (B->getOperand(1) == Op)
3547 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3548 MaxRecurse - 1);
3549 }
3550 }
3551
3552 // Same for CmpInsts.
3553 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3554 if (MaxRecurse) {
3555 if (C->getOperand(0) == Op)
3556 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3557 MaxRecurse - 1);
3558 if (C->getOperand(1) == Op)
3559 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3560 MaxRecurse - 1);
3561 }
3562 }
3563
3564 // TODO: We could hand off more cases to instsimplify here.
3565
3566 // If all operands are constant after substituting Op for RepOp then we can
3567 // constant fold the instruction.
3568 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3569 // Build a list of all constant operands.
3570 SmallVector<Constant *, 8> ConstOps;
3571 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3572 if (I->getOperand(i) == Op)
3573 ConstOps.push_back(CRepOp);
3574 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3575 ConstOps.push_back(COp);
3576 else
3577 break;
3578 }
3579
3580 // All operands were constants, fold it.
3581 if (ConstOps.size() == I->getNumOperands()) {
3582 if (CmpInst *C = dyn_cast<CmpInst>(I))
3583 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3584 ConstOps[1], Q.DL, Q.TLI);
3585
3586 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3587 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003588 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003589
Manuel Jacobe9024592016-01-21 06:33:22 +00003590 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003591 }
3592 }
3593
3594 return nullptr;
3595}
3596
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003597/// Try to simplify a select instruction when its condition operand is an
3598/// integer comparison where one operand of the compare is a constant.
3599static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3600 const APInt *Y, bool TrueWhenUnset) {
3601 const APInt *C;
3602
3603 // (X & Y) == 0 ? X & ~Y : X --> X
3604 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3605 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3606 *Y == ~*C)
3607 return TrueWhenUnset ? FalseVal : TrueVal;
3608
3609 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3610 // (X & Y) != 0 ? X : X & ~Y --> X
3611 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3612 *Y == ~*C)
3613 return TrueWhenUnset ? FalseVal : TrueVal;
3614
3615 if (Y->isPowerOf2()) {
3616 // (X & Y) == 0 ? X | Y : X --> X | Y
3617 // (X & Y) != 0 ? X | Y : X --> X
3618 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3619 *Y == *C)
3620 return TrueWhenUnset ? TrueVal : FalseVal;
3621
3622 // (X & Y) == 0 ? X : X | Y --> X
3623 // (X & Y) != 0 ? X : X | Y --> X | Y
3624 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3625 *Y == *C)
3626 return TrueWhenUnset ? TrueVal : FalseVal;
3627 }
Matt Arsenault82606662017-01-11 00:57:54 +00003628
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003629 return nullptr;
3630}
3631
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003632/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3633/// eq/ne.
3634static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3635 Value *FalseVal,
3636 bool TrueWhenUnset) {
3637 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003638 if (!BitWidth)
3639 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00003640
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003641 APInt MinSignedValue;
3642 Value *X;
3643 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3644 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3645 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3646 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3647 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3648 } else {
3649 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3650 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3651 X = CmpLHS;
3652 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3653 }
3654
3655 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3656 TrueWhenUnset))
3657 return V;
3658
3659 return nullptr;
3660}
3661
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003662/// Try to simplify a select instruction when its condition operand is an
3663/// integer comparison.
3664static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
3665 Value *FalseVal, const Query &Q,
3666 unsigned MaxRecurse) {
3667 ICmpInst::Predicate Pred;
3668 Value *CmpLHS, *CmpRHS;
3669 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3670 return nullptr;
3671
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003672 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3673 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003674 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3675 Value *X;
3676 const APInt *Y;
3677 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3678 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3679 Pred == ICmpInst::ICMP_EQ))
3680 return V;
3681 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003682 // Comparing signed-less-than 0 checks if the sign bit is set.
3683 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3684 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003685 return V;
3686 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003687 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3688 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3689 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003690 return V;
3691 }
3692
3693 if (CondVal->hasOneUse()) {
3694 const APInt *C;
3695 if (match(CmpRHS, m_APInt(C))) {
3696 // X < MIN ? T : F --> F
3697 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3698 return FalseVal;
3699 // X < MIN ? T : F --> F
3700 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3701 return FalseVal;
3702 // X > MAX ? T : F --> F
3703 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3704 return FalseVal;
3705 // X > MAX ? T : F --> F
3706 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3707 return FalseVal;
3708 }
3709 }
3710
3711 // If we have an equality comparison, then we know the value in one of the
3712 // arms of the select. See if substituting this value into the arm and
3713 // simplifying the result yields the same value as the other arm.
3714 if (Pred == ICmpInst::ICMP_EQ) {
3715 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3716 TrueVal ||
3717 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3718 TrueVal)
3719 return FalseVal;
3720 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3721 FalseVal ||
3722 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3723 FalseVal)
3724 return FalseVal;
3725 } else if (Pred == ICmpInst::ICMP_NE) {
3726 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3727 FalseVal ||
3728 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3729 FalseVal)
3730 return TrueVal;
3731 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3732 TrueVal ||
3733 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3734 TrueVal)
3735 return TrueVal;
3736 }
3737
3738 return nullptr;
3739}
3740
Sanjay Patel472cc782016-01-11 22:14:42 +00003741/// Given operands for a SelectInst, see if we can fold the result.
3742/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003743static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
3744 Value *FalseVal, const Query &Q,
3745 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003746 // select true, X, Y -> X
3747 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003748 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3749 if (CB->isAllOnesValue())
3750 return TrueVal;
3751 if (CB->isNullValue())
3752 return FalseVal;
3753 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003754
Chris Lattnerc707fa92010-04-20 05:32:14 +00003755 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003756 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003757 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003758
Chris Lattnerc707fa92010-04-20 05:32:14 +00003759 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3760 if (isa<Constant>(TrueVal))
3761 return TrueVal;
3762 return FalseVal;
3763 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003764 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3765 return FalseVal;
3766 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3767 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003768
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003769 if (Value *V =
3770 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3771 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003772
Craig Topper9f008862014-04-15 04:59:12 +00003773 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003774}
3775
Duncan Sandsb8cee002012-03-13 11:42:19 +00003776Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003777 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003778 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003779 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003780 const Instruction *CxtI) {
3781 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003782 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003783}
3784
Sanjay Patel472cc782016-01-11 22:14:42 +00003785/// Given operands for an GetElementPtrInst, see if we can fold the result.
3786/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003787static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3788 const Query &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003789 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003790 unsigned AS =
3791 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003792
Chris Lattner8574aba2009-11-27 00:29:05 +00003793 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003794 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003795 return Ops[0];
3796
Nico Weber48c82402014-08-27 20:06:19 +00003797 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003798 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003799 Type *GEPTy = PointerType::get(LastType, AS);
3800 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3801 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
3802
3803 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003804 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003805
Jay Foadb992a632011-07-19 15:07:52 +00003806 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003807 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003808 if (match(Ops[1], m_Zero()))
3809 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003810
David Blaikie4a2e73b2015-04-02 18:55:32 +00003811 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003812 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003813 Value *P;
3814 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003815 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003816 // getelementptr P, N -> P if P points to a type of zero size.
3817 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003818 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003819
3820 // The following transforms are only safe if the ptrtoint cast
3821 // doesn't truncate the pointers.
3822 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003823 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003824 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3825 if (match(P, m_Zero()))
3826 return Constant::getNullValue(GEPTy);
3827 Value *Temp;
3828 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003829 if (Temp->getType() == GEPTy)
3830 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003831 return nullptr;
3832 };
3833
3834 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3835 if (TyAllocSize == 1 &&
3836 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3837 if (Value *R = PtrToIntOrZero(P))
3838 return R;
3839
3840 // getelementptr V, (ashr (sub P, V), C) -> Q
3841 // if P points to a type of size 1 << C.
3842 if (match(Ops[1],
3843 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3844 m_ConstantInt(C))) &&
3845 TyAllocSize == 1ULL << C)
3846 if (Value *R = PtrToIntOrZero(P))
3847 return R;
3848
3849 // getelementptr V, (sdiv (sub P, V), C) -> Q
3850 // if P points to a type of size C.
3851 if (match(Ops[1],
3852 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3853 m_SpecificInt(TyAllocSize))))
3854 if (Value *R = PtrToIntOrZero(P))
3855 return R;
3856 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003857 }
3858 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003859
David Majnemerd1501372016-08-07 07:58:12 +00003860 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3861 all_of(Ops.slice(1).drop_back(1),
3862 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3863 unsigned PtrWidth =
3864 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3865 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3866 APInt BasePtrOffset(PtrWidth, 0);
3867 Value *StrippedBasePtr =
3868 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3869 BasePtrOffset);
3870
David Majnemer5c5df622016-08-16 06:13:46 +00003871 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003872 if (match(Ops.back(),
3873 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3874 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3875 return ConstantExpr::getIntToPtr(CI, GEPTy);
3876 }
David Majnemer5c5df622016-08-16 06:13:46 +00003877 // gep (gep V, C), (xor V, -1) -> C-1
3878 if (match(Ops.back(),
3879 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3880 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3881 return ConstantExpr::getIntToPtr(CI, GEPTy);
3882 }
David Majnemerd1501372016-08-07 07:58:12 +00003883 }
3884 }
3885
Chris Lattner8574aba2009-11-27 00:29:05 +00003886 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003887 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003888 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003889 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003890
David Blaikie4a2e73b2015-04-02 18:55:32 +00003891 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3892 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003893}
3894
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003895Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
3896 const DataLayout &DL,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003897 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003898 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00003899 const Instruction *CxtI) {
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003900 return ::SimplifyGEPInst(SrcTy, Ops,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003901 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003902}
3903
Sanjay Patel472cc782016-01-11 22:14:42 +00003904/// Given operands for an InsertValueInst, see if we can fold the result.
3905/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003906static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
3907 ArrayRef<unsigned> Idxs, const Query &Q,
3908 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003909 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3910 if (Constant *CVal = dyn_cast<Constant>(Val))
3911 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3912
3913 // insertvalue x, undef, n -> x
3914 if (match(Val, m_Undef()))
3915 return Agg;
3916
3917 // insertvalue x, (extractvalue y, n), n
3918 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003919 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3920 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003921 // insertvalue undef, (extractvalue y, n), n -> y
3922 if (match(Agg, m_Undef()))
3923 return EV->getAggregateOperand();
3924
3925 // insertvalue y, (extractvalue y, n), n -> y
3926 if (Agg == EV->getAggregateOperand())
3927 return Agg;
3928 }
3929
Craig Topper9f008862014-04-15 04:59:12 +00003930 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003931}
3932
Chandler Carruth66b31302015-01-04 12:03:27 +00003933Value *llvm::SimplifyInsertValueInst(
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003934 Value *Agg, Value *Val, ArrayRef<unsigned> Idxs, const DataLayout &DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003935 const TargetLibraryInfo *TLI, const DominatorTree *DT, AssumptionCache *AC,
Chandler Carruth66b31302015-01-04 12:03:27 +00003936 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003937 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003938 RecursionLimit);
3939}
3940
Sanjay Patel472cc782016-01-11 22:14:42 +00003941/// Given operands for an ExtractValueInst, see if we can fold the result.
3942/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003943static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3944 const Query &, unsigned) {
3945 if (auto *CAgg = dyn_cast<Constant>(Agg))
3946 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3947
3948 // extractvalue x, (insertvalue y, elt, n), n -> elt
3949 unsigned NumIdxs = Idxs.size();
3950 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3951 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3952 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3953 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3954 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3955 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3956 Idxs.slice(0, NumCommonIdxs)) {
3957 if (NumIdxs == NumInsertValueIdxs)
3958 return IVI->getInsertedValueOperand();
3959 break;
3960 }
3961 }
3962
3963 return nullptr;
3964}
3965
3966Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
3967 const DataLayout &DL,
3968 const TargetLibraryInfo *TLI,
3969 const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003970 AssumptionCache *AC,
David Majnemer25a796e2015-07-13 01:15:46 +00003971 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003972 return ::SimplifyExtractValueInst(Agg, Idxs, Query(DL, TLI, DT, AC, CxtI),
David Majnemer25a796e2015-07-13 01:15:46 +00003973 RecursionLimit);
3974}
3975
Sanjay Patel472cc782016-01-11 22:14:42 +00003976/// Given operands for an ExtractElementInst, see if we can fold the result.
3977/// If not, this returns null.
David Majnemer599ca442015-07-13 01:15:53 +00003978static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const Query &,
3979 unsigned) {
3980 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3981 if (auto *CIdx = dyn_cast<Constant>(Idx))
3982 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3983
3984 // The index is not relevant if our vector is a splat.
3985 if (auto *Splat = CVec->getSplatValue())
3986 return Splat;
3987
3988 if (isa<UndefValue>(Vec))
3989 return UndefValue::get(Vec->getType()->getVectorElementType());
3990 }
3991
3992 // If extracting a specified index from the vector, see if we can recursively
3993 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003994 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3995 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003996 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003997
3998 return nullptr;
3999}
4000
4001Value *llvm::SimplifyExtractElementInst(
4002 Value *Vec, Value *Idx, const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004003 const DominatorTree *DT, AssumptionCache *AC, const Instruction *CxtI) {
4004 return ::SimplifyExtractElementInst(Vec, Idx, Query(DL, TLI, DT, AC, CxtI),
David Majnemer599ca442015-07-13 01:15:53 +00004005 RecursionLimit);
4006}
4007
Sanjay Patel472cc782016-01-11 22:14:42 +00004008/// See if we can fold the given phi. If not, returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00004009static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004010 // If all of the PHI's incoming values are the same then replace the PHI node
4011 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00004012 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004013 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00004014 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00004015 // If the incoming value is the phi node itself, it can safely be skipped.
4016 if (Incoming == PN) continue;
4017 if (isa<UndefValue>(Incoming)) {
4018 // Remember that we saw an undef value, but otherwise ignore them.
4019 HasUndefInput = true;
4020 continue;
4021 }
4022 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00004023 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00004024 CommonValue = Incoming;
4025 }
4026
4027 // If CommonValue is null then all of the incoming values were either undef or
4028 // equal to the phi node itself.
4029 if (!CommonValue)
4030 return UndefValue::get(PN->getType());
4031
4032 // If we have a PHI node like phi(X, undef, X), where X is defined by some
4033 // instruction, we cannot return X as the result of the PHI node unless it
4034 // dominates the PHI block.
4035 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00004036 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00004037
4038 return CommonValue;
4039}
4040
David Majnemer6774d612016-07-26 17:58:05 +00004041static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
4042 Type *Ty, const Query &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00004043 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00004044 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00004045
David Majnemer6774d612016-07-26 17:58:05 +00004046 if (auto *CI = dyn_cast<CastInst>(Op)) {
4047 auto *Src = CI->getOperand(0);
4048 Type *SrcTy = Src->getType();
4049 Type *MidTy = CI->getType();
4050 Type *DstTy = Ty;
4051 if (Src->getType() == Ty) {
4052 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
4053 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
4054 Type *SrcIntPtrTy =
4055 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
4056 Type *MidIntPtrTy =
4057 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
4058 Type *DstIntPtrTy =
4059 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
4060 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
4061 SrcIntPtrTy, MidIntPtrTy,
4062 DstIntPtrTy) == Instruction::BitCast)
4063 return Src;
4064 }
4065 }
David Majnemera90a6212016-07-26 05:52:29 +00004066
4067 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00004068 if (CastOpc == Instruction::BitCast)
4069 if (Op->getType() == Ty)
4070 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00004071
4072 return nullptr;
4073}
4074
David Majnemer6774d612016-07-26 17:58:05 +00004075Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
4076 const DataLayout &DL,
4077 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004078 const DominatorTree *DT, AssumptionCache *AC,
David Majnemer6774d612016-07-26 17:58:05 +00004079 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004080 return ::SimplifyCastInst(CastOpc, Op, Ty, Query(DL, TLI, DT, AC, CxtI),
David Majnemer6774d612016-07-26 17:58:05 +00004081 RecursionLimit);
David Majnemera90a6212016-07-26 05:52:29 +00004082}
4083
Zvi Rackover8f460652017-04-03 22:05:30 +00004084static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4085 Type *RetTy, const Query &Q,
4086 unsigned MaxRecurse) {
4087 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
4088 unsigned InVecNumElts = Op0->getType()->getVectorNumElements();
4089
4090 auto *Op0Const = dyn_cast<Constant>(Op0);
4091 auto *Op1Const = dyn_cast<Constant>(Op1);
4092
4093 // If all operands are constant, constant fold the shuffle.
4094 if (Op0Const && Op1Const)
4095 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4096
4097 // If only one of the operands is constant, constant fold the shuffle if the
4098 // mask does not select elements from the variable operand.
4099 bool MaskSelects0 = false, MaskSelects1 = false;
4100 for (unsigned i = 0; i != MaskNumElts; ++i) {
4101 int Idx = ShuffleVectorInst::getMaskValue(Mask, i);
4102 if (Idx == -1)
4103 continue;
4104 if ((unsigned)Idx < InVecNumElts)
4105 MaskSelects0 = true;
4106 else
4107 MaskSelects1 = true;
4108 }
4109 if (!MaskSelects0 && Op1Const)
4110 return ConstantFoldShuffleVectorInstruction(UndefValue::get(Op0->getType()),
4111 Op1Const, Mask);
4112 if (!MaskSelects1 && Op0Const)
4113 return ConstantFoldShuffleVectorInstruction(
4114 Op0Const, UndefValue::get(Op0->getType()), Mask);
4115
4116 return nullptr;
4117}
4118
4119/// Given operands for a ShuffleVectorInst, fold the result or return null.
4120Value *llvm::SimplifyShuffleVectorInst(
4121 Value *Op0, Value *Op1, Constant *Mask, Type *RetTy,
4122 const DataLayout &DL, const TargetLibraryInfo *TLI, const DominatorTree *DT,
4123 AssumptionCache *AC, const Instruction *CxtI) {
4124 return ::SimplifyShuffleVectorInst(
4125 Op0, Op1, Mask, RetTy, Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
4126}
4127
Chris Lattnera71e9d62009-11-10 00:55:12 +00004128//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004129
Sanjay Patel472cc782016-01-11 22:14:42 +00004130/// Given operands for a BinaryOperator, see if we can fold the result.
4131/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004132static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004133 const Query &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004134 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004135 case Instruction::Add:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004136 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004137 case Instruction::FAdd:
4138 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004139 case Instruction::Sub:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004140 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004141 case Instruction::FSub:
4142 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004143 case Instruction::Mul:
4144 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004145 case Instruction::FMul:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004146 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4147 case Instruction::SDiv:
4148 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4149 case Instruction::UDiv:
4150 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004151 case Instruction::FDiv:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004152 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4153 case Instruction::SRem:
4154 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4155 case Instruction::URem:
4156 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004157 case Instruction::FRem:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004158 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004159 case Instruction::Shl:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004160 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004161 case Instruction::LShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004162 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004163 case Instruction::AShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004164 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4165 case Instruction::And:
4166 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4167 case Instruction::Or:
4168 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4169 case Instruction::Xor:
4170 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004171 default:
4172 if (Constant *CLHS = dyn_cast<Constant>(LHS))
Manuel Jacoba61ca372016-01-21 06:26:35 +00004173 if (Constant *CRHS = dyn_cast<Constant>(RHS))
4174 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
Duncan Sandsb0579e92010-11-10 13:00:08 +00004175
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004176 // If the operation is associative, try some generic simplifications.
4177 if (Instruction::isAssociative(Opcode))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004178 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00004179 return V;
4180
Duncan Sandsb8cee002012-03-13 11:42:19 +00004181 // If the operation is with the result of a select instruction check whether
Duncan Sandsb0579e92010-11-10 13:00:08 +00004182 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004183 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004184 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004185 return V;
4186
4187 // If the operation is with the result of a phi instruction, check whether
4188 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00004189 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004190 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00004191 return V;
4192
Craig Topper9f008862014-04-15 04:59:12 +00004193 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00004194 }
4195}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004196
Sanjay Patel472cc782016-01-11 22:14:42 +00004197/// Given operands for a BinaryOperator, see if we can fold the result.
4198/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004199/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4200/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4201static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
4202 const FastMathFlags &FMF, const Query &Q,
4203 unsigned MaxRecurse) {
4204 switch (Opcode) {
4205 case Instruction::FAdd:
4206 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4207 case Instruction::FSub:
4208 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4209 case Instruction::FMul:
4210 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004211 case Instruction::FDiv:
4212 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004213 default:
4214 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4215 }
4216}
4217
Duncan Sands7e800d62010-11-14 11:23:23 +00004218Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004219 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004220 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004221 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004222 return ::SimplifyBinOp(Opcode, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Hal Finkel60db0582014-09-07 18:57:58 +00004223 RecursionLimit);
Chris Lattnerc1f19072009-11-09 23:28:39 +00004224}
4225
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004226Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004227 const FastMathFlags &FMF, const DataLayout &DL,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004228 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004229 const DominatorTree *DT, AssumptionCache *AC,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004230 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004231 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Query(DL, TLI, DT, AC, CxtI),
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004232 RecursionLimit);
4233}
4234
Sanjay Patel472cc782016-01-11 22:14:42 +00004235/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004236static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sandsb8cee002012-03-13 11:42:19 +00004237 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004238 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004239 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004240 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004241}
4242
4243Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004244 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004245 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004246 const Instruction *CxtI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004247 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query(DL, TLI, DT, AC, CxtI),
Duncan Sandsb8cee002012-03-13 11:42:19 +00004248 RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004249}
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004250
Michael Ilseman54857292013-02-07 19:26:05 +00004251static bool IsIdempotent(Intrinsic::ID ID) {
4252 switch (ID) {
4253 default: return false;
4254
4255 // Unary idempotent: f(f(x)) = f(x)
4256 case Intrinsic::fabs:
4257 case Intrinsic::floor:
4258 case Intrinsic::ceil:
4259 case Intrinsic::trunc:
4260 case Intrinsic::rint:
4261 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004262 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004263 return true;
4264 }
4265}
4266
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004267static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4268 const DataLayout &DL) {
4269 GlobalValue *PtrSym;
4270 APInt PtrOffset;
4271 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4272 return nullptr;
4273
4274 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4275 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4276 Type *Int32PtrTy = Int32Ty->getPointerTo();
4277 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4278
4279 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4280 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4281 return nullptr;
4282
4283 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4284 if (OffsetInt % 4 != 0)
4285 return nullptr;
4286
4287 Constant *C = ConstantExpr::getGetElementPtr(
4288 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4289 ConstantInt::get(Int64Ty, OffsetInt / 4));
4290 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4291 if (!Loaded)
4292 return nullptr;
4293
4294 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4295 if (!LoadedCE)
4296 return nullptr;
4297
4298 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4299 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4300 if (!LoadedCE)
4301 return nullptr;
4302 }
4303
4304 if (LoadedCE->getOpcode() != Instruction::Sub)
4305 return nullptr;
4306
4307 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4308 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4309 return nullptr;
4310 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4311
4312 Constant *LoadedRHS = LoadedCE->getOperand(1);
4313 GlobalValue *LoadedRHSSym;
4314 APInt LoadedRHSOffset;
4315 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4316 DL) ||
4317 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4318 return nullptr;
4319
4320 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4321}
4322
David Majnemer17a95aa2016-07-14 06:58:37 +00004323static bool maskIsAllZeroOrUndef(Value *Mask) {
4324 auto *ConstMask = dyn_cast<Constant>(Mask);
4325 if (!ConstMask)
4326 return false;
4327 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4328 return true;
4329 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4330 ++I) {
4331 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4332 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4333 continue;
4334 return false;
4335 }
4336 return true;
4337}
4338
Michael Ilseman54857292013-02-07 19:26:05 +00004339template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004340static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Michael Ilseman54857292013-02-07 19:26:05 +00004341 const Query &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004342 Intrinsic::ID IID = F->getIntrinsicID();
4343 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004344
4345 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004346 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004347 // Perform idempotent optimizations
4348 if (IsIdempotent(IID)) {
4349 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4350 if (II->getIntrinsicID() == IID)
4351 return II;
4352 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004353 }
4354
4355 switch (IID) {
4356 case Intrinsic::fabs: {
4357 if (SignBitMustBeZero(*ArgBegin, Q.TLI))
4358 return *ArgBegin;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004359 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004360 }
4361 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004362 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004363 }
4364 }
Michael Ilseman54857292013-02-07 19:26:05 +00004365
Matt Arsenault82606662017-01-11 00:57:54 +00004366 // Binary Ops
4367 if (NumOperands == 2) {
4368 Value *LHS = *ArgBegin;
4369 Value *RHS = *(ArgBegin + 1);
4370 Type *ReturnType = F->getReturnType();
4371
4372 switch (IID) {
4373 case Intrinsic::usub_with_overflow:
4374 case Intrinsic::ssub_with_overflow: {
4375 // X - X -> { 0, false }
4376 if (LHS == RHS)
4377 return Constant::getNullValue(ReturnType);
4378
4379 // X - undef -> undef
4380 // undef - X -> undef
4381 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4382 return UndefValue::get(ReturnType);
4383
4384 return nullptr;
4385 }
4386 case Intrinsic::uadd_with_overflow:
4387 case Intrinsic::sadd_with_overflow: {
4388 // X + undef -> undef
4389 if (isa<UndefValue>(RHS))
4390 return UndefValue::get(ReturnType);
4391
4392 return nullptr;
4393 }
4394 case Intrinsic::umul_with_overflow:
4395 case Intrinsic::smul_with_overflow: {
4396 // X * 0 -> { 0, false }
4397 if (match(RHS, m_Zero()))
4398 return Constant::getNullValue(ReturnType);
4399
4400 // X * undef -> { 0, false }
4401 if (match(RHS, m_Undef()))
4402 return Constant::getNullValue(ReturnType);
4403
4404 return nullptr;
4405 }
4406 case Intrinsic::load_relative: {
4407 Constant *C0 = dyn_cast<Constant>(LHS);
4408 Constant *C1 = dyn_cast<Constant>(RHS);
4409 if (C0 && C1)
4410 return SimplifyRelativeLoad(C0, C1, Q.DL);
4411 return nullptr;
4412 }
4413 default:
4414 return nullptr;
4415 }
4416 }
4417
4418 // Simplify calls to llvm.masked.load.*
4419 switch (IID) {
4420 case Intrinsic::masked_load: {
4421 Value *MaskArg = ArgBegin[2];
4422 Value *PassthruArg = ArgBegin[3];
4423 // If the mask is all zeros or undef, the "passthru" argument is the result.
4424 if (maskIsAllZeroOrUndef(MaskArg))
4425 return PassthruArg;
4426 return nullptr;
4427 }
4428 default:
4429 return nullptr;
4430 }
Michael Ilseman54857292013-02-07 19:26:05 +00004431}
4432
Chandler Carruth9dc35582012-12-28 11:30:55 +00004433template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004434static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Chandler Carruth9dc35582012-12-28 11:30:55 +00004435 const Query &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004436 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004437 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4438 Ty = PTy->getElementType();
4439 FunctionType *FTy = cast<FunctionType>(Ty);
4440
Dan Gohman85977e62011-11-04 18:32:42 +00004441 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004442 // call null -> undef
4443 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004444 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004445
Chandler Carruthf6182152012-12-28 14:23:29 +00004446 Function *F = dyn_cast<Function>(V);
4447 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004448 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004449
David Majnemer15032582015-05-22 03:56:46 +00004450 if (F->isIntrinsic())
4451 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004452 return Ret;
4453
Chandler Carruthf6182152012-12-28 14:23:29 +00004454 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004455 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004456
4457 SmallVector<Constant *, 4> ConstantArgs;
4458 ConstantArgs.reserve(ArgEnd - ArgBegin);
4459 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4460 Constant *C = dyn_cast<Constant>(*I);
4461 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004462 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004463 ConstantArgs.push_back(C);
4464 }
4465
4466 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004467}
4468
Chandler Carruthf6182152012-12-28 14:23:29 +00004469Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004470 User::op_iterator ArgEnd, const DataLayout &DL,
Chandler Carruth66b31302015-01-04 12:03:27 +00004471 const TargetLibraryInfo *TLI, const DominatorTree *DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004472 AssumptionCache *AC, const Instruction *CxtI) {
4473 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AC, CxtI),
Chandler Carruth9dc35582012-12-28 11:30:55 +00004474 RecursionLimit);
4475}
4476
Chandler Carruthf6182152012-12-28 14:23:29 +00004477Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004478 const DataLayout &DL, const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004479 const DominatorTree *DT, AssumptionCache *AC,
Hal Finkel60db0582014-09-07 18:57:58 +00004480 const Instruction *CxtI) {
4481 return ::SimplifyCall(V, Args.begin(), Args.end(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004482 Query(DL, TLI, DT, AC, CxtI), RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004483}
4484
Sanjay Patel472cc782016-01-11 22:14:42 +00004485/// See if we can compute a simplified version of this instruction.
4486/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004487Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004488 const TargetLibraryInfo *TLI,
Sanjay Patel54656ca2017-02-06 18:26:06 +00004489 const DominatorTree *DT, AssumptionCache *AC,
4490 OptimizationRemarkEmitter *ORE) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004491 Value *Result;
4492
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004493 switch (I->getOpcode()) {
4494 default:
Rafael Espindola37dc9e12014-02-21 00:06:31 +00004495 Result = ConstantFoldInstruction(I, DL, TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004496 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004497 case Instruction::FAdd:
4498 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004499 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004500 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004501 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004502 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4503 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004504 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004505 TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004506 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004507 case Instruction::FSub:
4508 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004509 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004510 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004511 case Instruction::Sub:
4512 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4513 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004514 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004515 TLI, DT, AC, I);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004516 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004517 case Instruction::FMul:
4518 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004519 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004520 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004521 case Instruction::Mul:
Chandler Carruth66b31302015-01-04 12:03:27 +00004522 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004523 SimplifyMulInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004524 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004525 case Instruction::SDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004526 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004527 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004528 break;
4529 case Instruction::UDiv:
Chandler Carruth66b31302015-01-04 12:03:27 +00004530 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004531 AC, I);
Duncan Sands771e82a2011-01-28 16:51:11 +00004532 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004533 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004534 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004535 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Frits van Bommelc2549662011-01-29 15:26:31 +00004536 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004537 case Instruction::SRem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004538 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004539 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004540 break;
4541 case Instruction::URem:
Chandler Carruth66b31302015-01-04 12:03:27 +00004542 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004543 AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004544 break;
4545 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004546 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004547 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004548 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004549 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004550 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4551 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Chandler Carruth66b31302015-01-04 12:03:27 +00004552 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004553 TLI, DT, AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004554 break;
4555 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004556 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004557 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004558 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004559 break;
4560 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004561 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Chandler Carruth66b31302015-01-04 12:03:27 +00004562 cast<BinaryOperator>(I)->isExact(), DL, TLI, DT,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004563 AC, I);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004564 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004565 case Instruction::And:
Chandler Carruth66b31302015-01-04 12:03:27 +00004566 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004567 SimplifyAndInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004568 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004569 case Instruction::Or:
Chandler Carruth66b31302015-01-04 12:03:27 +00004570 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004571 SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004572 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004573 case Instruction::Xor:
Chandler Carruth66b31302015-01-04 12:03:27 +00004574 Result =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004575 SimplifyXorInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004576 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004577 case Instruction::ICmp:
Chandler Carruth66b31302015-01-04 12:03:27 +00004578 Result =
4579 SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), I->getOperand(0),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004580 I->getOperand(1), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004581 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004582 case Instruction::FCmp:
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004583 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
4584 I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004585 I->getFastMathFlags(), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004586 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004587 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004588 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004589 I->getOperand(2), DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004590 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004591 case Instruction::GetElementPtr: {
4592 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004593 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004594 Ops, DL, TLI, DT, AC, I);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004595 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004596 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004597 case Instruction::InsertValue: {
4598 InsertValueInst *IV = cast<InsertValueInst>(I);
4599 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4600 IV->getInsertedValueOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004601 IV->getIndices(), DL, TLI, DT, AC, I);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004602 break;
4603 }
David Majnemer25a796e2015-07-13 01:15:46 +00004604 case Instruction::ExtractValue: {
4605 auto *EVI = cast<ExtractValueInst>(I);
4606 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004607 EVI->getIndices(), DL, TLI, DT, AC, I);
David Majnemer25a796e2015-07-13 01:15:46 +00004608 break;
4609 }
David Majnemer599ca442015-07-13 01:15:53 +00004610 case Instruction::ExtractElement: {
4611 auto *EEI = cast<ExtractElementInst>(I);
4612 Result = SimplifyExtractElementInst(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004613 EEI->getVectorOperand(), EEI->getIndexOperand(), DL, TLI, DT, AC, I);
David Majnemer599ca442015-07-13 01:15:53 +00004614 break;
4615 }
Zvi Rackover8f460652017-04-03 22:05:30 +00004616 case Instruction::ShuffleVector: {
4617 auto *SVI = cast<ShuffleVectorInst>(I);
4618 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
4619 SVI->getMask(), SVI->getType(), DL, TLI,
4620 DT, AC, I);
4621 break;
4622 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004623 case Instruction::PHI:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004624 Result = SimplifyPHINode(cast<PHINode>(I), Query(DL, TLI, DT, AC, I));
Duncan Sands64e41cf2010-11-17 08:35:29 +00004625 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004626 case Instruction::Call: {
4627 CallSite CS(cast<CallInst>(I));
Chandler Carruth66b31302015-01-04 12:03:27 +00004628 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004629 TLI, DT, AC, I);
Dan Gohman85977e62011-11-04 18:32:42 +00004630 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004631 }
David Majnemer6774d612016-07-26 17:58:05 +00004632#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4633#include "llvm/IR/Instruction.def"
4634#undef HANDLE_CAST_INST
4635 Result = SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(),
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004636 DL, TLI, DT, AC, I);
David Majnemera90a6212016-07-26 05:52:29 +00004637 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004638 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004639
Hal Finkelf2199b22015-10-23 20:37:08 +00004640 // In general, it is possible for computeKnownBits to determine all bits in a
4641 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004642 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004643 unsigned BitWidth = I->getType()->getScalarSizeInBits();
4644 APInt KnownZero(BitWidth, 0);
4645 APInt KnownOne(BitWidth, 0);
Sanjay Patel54656ca2017-02-06 18:26:06 +00004646 computeKnownBits(I, KnownZero, KnownOne, DL, /*Depth*/0, AC, I, DT, ORE);
Hal Finkelf2199b22015-10-23 20:37:08 +00004647 if ((KnownZero | KnownOne).isAllOnesValue())
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004648 Result = ConstantInt::get(I->getType(), KnownOne);
Hal Finkelf2199b22015-10-23 20:37:08 +00004649 }
4650
Duncan Sands64e41cf2010-11-17 08:35:29 +00004651 /// If called on unreachable code, the above logic may report that the
4652 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004653 /// detecting that case here, returning a safe value instead.
4654 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004655}
4656
Sanjay Patelf44bd382016-01-20 18:59:48 +00004657/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004658/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004659///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004660/// This is the common implementation of the recursive simplification routines.
4661/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4662/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4663/// instructions to process and attempt to simplify it using
4664/// InstructionSimplify.
4665///
4666/// This routine returns 'true' only when *it* simplifies something. The passed
4667/// in simplified value does not count toward this.
4668static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004669 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004670 const DominatorTree *DT,
4671 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004672 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004673 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004674 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004675
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004676 // If we have an explicit value to collapse to, do that round of the
4677 // simplification loop by hand initially.
4678 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004679 for (User *U : I->users())
4680 if (U != I)
4681 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004682
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004683 // Replace the instruction with its simplified value.
4684 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004685
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004686 // Gracefully handle edge cases where the instruction is not wired into any
4687 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004688 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4689 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004690 I->eraseFromParent();
4691 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004692 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004693 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004694
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004695 // Note that we must test the size on each iteration, the worklist can grow.
4696 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4697 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004698
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004699 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004700 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004701 if (!SimpleV)
4702 continue;
4703
4704 Simplified = true;
4705
4706 // Stash away all the uses of the old instruction so we can check them for
4707 // recursive simplifications after a RAUW. This is cheaper than checking all
4708 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004709 for (User *U : I->users())
4710 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004711
4712 // Replace the instruction with its simplified value.
4713 I->replaceAllUsesWith(SimpleV);
4714
4715 // Gracefully handle edge cases where the instruction is not wired into any
4716 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004717 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4718 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004719 I->eraseFromParent();
4720 }
4721 return Simplified;
4722}
4723
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004724bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004725 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004726 const DominatorTree *DT,
4727 AssumptionCache *AC) {
4728 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004729}
4730
4731bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004732 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004733 const DominatorTree *DT,
4734 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004735 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4736 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004737 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004738}