blob: 92ca34def0a6258b7b6b078ed50297a5c4599e80 [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"
Craig Topperb45eabc2017-04-26 16:39:58 +000038#include "llvm/Support/KnownBits.h"
Hal Finkelafcd8db2014-12-01 23:38:06 +000039#include <algorithm>
Chris Lattner084a1b52009-11-09 22:57:59 +000040using namespace llvm;
Chris Lattnera71e9d62009-11-10 00:55:12 +000041using namespace llvm::PatternMatch;
Chris Lattner084a1b52009-11-09 22:57:59 +000042
Chandler Carruthf1221bd2014-04-22 02:48:03 +000043#define DEBUG_TYPE "instsimplify"
44
Chris Lattner9e4aa022011-02-09 17:15:04 +000045enum { RecursionLimit = 3 };
Duncan Sandsf3b1bf12010-11-10 18:23:01 +000046
Duncan Sands3547d2e2010-12-22 09:40:51 +000047STATISTIC(NumExpand, "Number of expansions");
Duncan Sands3547d2e2010-12-22 09:40:51 +000048STATISTIC(NumReassoc, "Number of reassociations");
49
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000050static Value *SimplifyAndInst(Value *, Value *, const SimplifyQuery &, unsigned);
51static Value *SimplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000052 unsigned);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +000053static Value *SimplifyFPBinOp(unsigned, Value *, Value *, const FastMathFlags &,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000054 const SimplifyQuery &, unsigned);
55static Value *SimplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
Chad Rosierc24b86f2011-12-01 03:08:23 +000056 unsigned);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +000057static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000058 const SimplifyQuery &Q, unsigned MaxRecurse);
59static Value *SimplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
60static Value *SimplifyXorInst(Value *, Value *, const SimplifyQuery &, unsigned);
David Majnemer6774d612016-07-26 17:58:05 +000061static Value *SimplifyCastInst(unsigned, Value *, Type *,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +000062 const SimplifyQuery &, unsigned);
Duncan Sands5ffc2982010-11-16 12:16:38 +000063
Sanjay Patel35ed2412017-04-16 17:43:11 +000064/// For a boolean type or a vector of boolean type, return false or a vector
65/// with every element false.
Duncan Sandsc1c92712011-07-26 15:03:53 +000066static Constant *getFalse(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +000067 return ConstantInt::getFalse(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +000068}
69
Sanjay Patel35ed2412017-04-16 17:43:11 +000070/// For a boolean type or a vector of boolean type, return true or a vector
71/// with every element true.
Duncan Sandsc1c92712011-07-26 15:03:53 +000072static Constant *getTrue(Type *Ty) {
Sanjay Patel35ed2412017-04-16 17:43:11 +000073 return ConstantInt::getTrue(Ty);
Duncan Sandsc1c92712011-07-26 15:03:53 +000074}
75
Duncan Sands3d5692a2011-10-30 19:56:36 +000076/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
77static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
78 Value *RHS) {
79 CmpInst *Cmp = dyn_cast<CmpInst>(V);
80 if (!Cmp)
81 return false;
82 CmpInst::Predicate CPred = Cmp->getPredicate();
83 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
84 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
85 return true;
86 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
87 CRHS == LHS;
88}
89
Sanjay Patel472cc782016-01-11 22:14:42 +000090/// Does the given value dominate the specified phi node?
Duncan Sands5ffc2982010-11-16 12:16:38 +000091static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
92 Instruction *I = dyn_cast<Instruction>(V);
93 if (!I)
94 // Arguments and constants dominate all instructions.
95 return true;
96
Chandler Carruth3ffccb32012-03-21 10:58:47 +000097 // If we are processing instructions (and/or basic blocks) that have not been
98 // fully added to a function, the parent nodes may still be null. Simply
99 // return the conservative answer in these cases.
100 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
101 return false;
102
Duncan Sands5ffc2982010-11-16 12:16:38 +0000103 // If we have a DominatorTree then do a precise test.
Eli Friedmanc8cbd062012-03-13 01:06:07 +0000104 if (DT) {
105 if (!DT->isReachableFromEntry(P->getParent()))
106 return true;
107 if (!DT->isReachableFromEntry(I->getParent()))
108 return false;
109 return DT->dominates(I, P);
110 }
Duncan Sands5ffc2982010-11-16 12:16:38 +0000111
David Majnemer8a1c45d2015-12-12 05:38:55 +0000112 // Otherwise, if the instruction is in the entry block and is not an invoke,
113 // then it obviously dominates all phi nodes.
Duncan Sands5ffc2982010-11-16 12:16:38 +0000114 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
David Majnemer8a1c45d2015-12-12 05:38:55 +0000115 !isa<InvokeInst>(I))
Duncan Sands5ffc2982010-11-16 12:16:38 +0000116 return true;
117
118 return false;
119}
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000120
Sanjay Patel472cc782016-01-11 22:14:42 +0000121/// Simplify "A op (B op' C)" by distributing op over op', turning it into
122/// "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000123/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
124/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
125/// Returns the simplified value, or null if no simplification was performed.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000126static Value *ExpandBinOp(Instruction::BinaryOps Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000127 Instruction::BinaryOps OpcodeToExpand, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000128 unsigned MaxRecurse) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000129 // Recursion is always used, so bail out at once if we already hit the limit.
130 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000131 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000132
133 // Check whether the expression has the form "(A op' B) op C".
134 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
135 if (Op0->getOpcode() == OpcodeToExpand) {
136 // It does! Try turning it into "(A op C) op' (B op C)".
137 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
138 // Do "A op C" and "B op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000139 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
140 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000141 // They do! Return "L op' R" if it simplifies or is already available.
142 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000143 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
144 && L == B && R == A)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000145 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000146 return LHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000147 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000148 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000149 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000150 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000151 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000152 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000153 }
154 }
155
156 // Check whether the expression has the form "A op (B op' C)".
157 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
158 if (Op1->getOpcode() == OpcodeToExpand) {
159 // It does! Try turning it into "(A op B) op' (A op C)".
160 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
161 // Do "A op B" and "A op C" both simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000162 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
163 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000164 // They do! Return "L op' R" if it simplifies or is already available.
165 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000166 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
167 && L == C && R == B)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000168 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000169 return RHS;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000170 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000171 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000172 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000173 ++NumExpand;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000174 return V;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000175 }
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000176 }
177 }
178
Craig Topper9f008862014-04-15 04:59:12 +0000179 return nullptr;
Duncan Sandsee3ec6e2010-12-21 13:32:22 +0000180}
181
Sanjay Patel472cc782016-01-11 22:14:42 +0000182/// Generic simplifications for associative binary operations.
183/// Returns the simpler value, or null if none was found.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000184static Value *SimplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000185 Value *LHS, Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000186 unsigned MaxRecurse) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000187 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
188
189 // Recursion is always used, so bail out at once if we already hit the limit.
190 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000191 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000192
193 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
194 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
195
196 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
197 if (Op0 && Op0->getOpcode() == Opcode) {
198 Value *A = Op0->getOperand(0);
199 Value *B = Op0->getOperand(1);
200 Value *C = RHS;
201
202 // Does "B op C" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000203 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000204 // It does! Return "A op V" if it simplifies or is already available.
205 // If V equals B then "A op V" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000206 if (V == B) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000207 // Otherwise return "A op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000208 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000209 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000210 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000211 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000212 }
213 }
214
215 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
216 if (Op1 && Op1->getOpcode() == Opcode) {
217 Value *A = LHS;
218 Value *B = Op1->getOperand(0);
219 Value *C = Op1->getOperand(1);
220
221 // Does "A op B" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000222 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000223 // It does! Return "V op C" if it simplifies or is already available.
224 // If V equals B then "V op C" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000225 if (V == B) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000226 // Otherwise return "V op C" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000227 if (Value *W = SimplifyBinOp(Opcode, V, C, 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 // The remaining transforms require commutativity as well as associativity.
235 if (!Instruction::isCommutative(Opcode))
Craig Topper9f008862014-04-15 04:59:12 +0000236 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000237
238 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
239 if (Op0 && Op0->getOpcode() == Opcode) {
240 Value *A = Op0->getOperand(0);
241 Value *B = Op0->getOperand(1);
242 Value *C = RHS;
243
244 // Does "C op A" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000245 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000246 // It does! Return "V op B" if it simplifies or is already available.
247 // If V equals A then "V op B" is just the LHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000248 if (V == A) return LHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000249 // Otherwise return "V op B" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000250 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sands3547d2e2010-12-22 09:40:51 +0000251 ++NumReassoc;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000252 return W;
Duncan Sands3547d2e2010-12-22 09:40:51 +0000253 }
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000254 }
255 }
256
257 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
258 if (Op1 && Op1->getOpcode() == Opcode) {
259 Value *A = LHS;
260 Value *B = Op1->getOperand(0);
261 Value *C = Op1->getOperand(1);
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 "B op V" if it simplifies or is already available.
266 // If V equals C then "B op V" is just the RHS.
Duncan Sands772749a2011-01-01 20:08:02 +0000267 if (V == C) return RHS;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000268 // Otherwise return "B op V" if it simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000269 if (Value *W = SimplifyBinOp(Opcode, B, V, 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
Craig Topper9f008862014-04-15 04:59:12 +0000276 return nullptr;
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000277}
278
Sanjay Patel472cc782016-01-11 22:14:42 +0000279/// In the case of a binary operation with a select instruction as an operand,
280/// try to simplify the binop by seeing whether evaluating it on both branches
281/// of the select results in the same value. Returns the common value if so,
282/// otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000283static Value *ThreadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000284 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000285 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000286 // Recursion is always used, so bail out at once if we already hit the limit.
287 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000288 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000289
Duncan Sandsb0579e92010-11-10 13:00:08 +0000290 SelectInst *SI;
291 if (isa<SelectInst>(LHS)) {
292 SI = cast<SelectInst>(LHS);
293 } else {
294 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
295 SI = cast<SelectInst>(RHS);
296 }
297
298 // Evaluate the BinOp on the true and false branches of the select.
299 Value *TV;
300 Value *FV;
301 if (SI == LHS) {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000302 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
303 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000304 } else {
Duncan Sandsb8cee002012-03-13 11:42:19 +0000305 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
306 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb0579e92010-11-10 13:00:08 +0000307 }
308
Duncan Sandse3c53952011-01-01 16:12:09 +0000309 // If they simplified to the same value, then return the common value.
Duncan Sands772749a2011-01-01 20:08:02 +0000310 // If they both failed to simplify then return null.
311 if (TV == FV)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000312 return TV;
313
314 // If one branch simplified to undef, return the other one.
315 if (TV && isa<UndefValue>(TV))
316 return FV;
317 if (FV && isa<UndefValue>(FV))
318 return TV;
319
320 // If applying the operation did not change the true and false select values,
321 // then the result of the binop is the select itself.
Duncan Sands772749a2011-01-01 20:08:02 +0000322 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb0579e92010-11-10 13:00:08 +0000323 return SI;
324
325 // If one branch simplified and the other did not, and the simplified
326 // value is equal to the unsimplified one, return the simplified value.
327 // For example, select (cond, X, X & Z) & Z -> X & Z.
328 if ((FV && !TV) || (TV && !FV)) {
329 // Check that the simplified value has the form "X op Y" where "op" is the
330 // same as the original operation.
331 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
332 if (Simplified && Simplified->getOpcode() == Opcode) {
333 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
334 // We already know that "op" is the same as for the simplified value. See
335 // if the operands match too. If so, return the simplified value.
336 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
337 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
338 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands772749a2011-01-01 20:08:02 +0000339 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
340 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000341 return Simplified;
342 if (Simplified->isCommutative() &&
Duncan Sands772749a2011-01-01 20:08:02 +0000343 Simplified->getOperand(1) == UnsimplifiedLHS &&
344 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb0579e92010-11-10 13:00:08 +0000345 return Simplified;
346 }
347 }
348
Craig Topper9f008862014-04-15 04:59:12 +0000349 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000350}
351
Sanjay Patel472cc782016-01-11 22:14:42 +0000352/// In the case of a comparison with a select instruction, try to simplify the
353/// comparison by seeing whether both branches of the select result in the same
354/// value. Returns the common value if so, otherwise returns null.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000355static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000356 Value *RHS, const SimplifyQuery &Q,
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000357 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000358 // Recursion is always used, so bail out at once if we already hit the limit.
359 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000360 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000361
Duncan Sandsb0579e92010-11-10 13:00:08 +0000362 // Make sure the select is on the LHS.
363 if (!isa<SelectInst>(LHS)) {
364 std::swap(LHS, RHS);
365 Pred = CmpInst::getSwappedPredicate(Pred);
366 }
367 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
368 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000369 Value *Cond = SI->getCondition();
370 Value *TV = SI->getTrueValue();
371 Value *FV = SI->getFalseValue();
Duncan Sandsb0579e92010-11-10 13:00:08 +0000372
Duncan Sands06504022011-02-03 09:37:39 +0000373 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb0579e92010-11-10 13:00:08 +0000374 // Does "cmp TV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000375 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000376 if (TCmp == Cond) {
377 // It not only simplified, it simplified to the select condition. Replace
378 // it with 'true'.
379 TCmp = getTrue(Cond->getType());
380 } else if (!TCmp) {
381 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
382 // condition then we can replace it with 'true'. Otherwise give up.
383 if (!isSameCompare(Cond, Pred, TV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000384 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000385 TCmp = getTrue(Cond->getType());
Duncan Sands06504022011-02-03 09:37:39 +0000386 }
387
Duncan Sands3d5692a2011-10-30 19:56:36 +0000388 // Does "cmp FV, RHS" simplify?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000389 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands3d5692a2011-10-30 19:56:36 +0000390 if (FCmp == Cond) {
391 // It not only simplified, it simplified to the select condition. Replace
392 // it with 'false'.
393 FCmp = getFalse(Cond->getType());
394 } else if (!FCmp) {
395 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
396 // condition then we can replace it with 'false'. Otherwise give up.
397 if (!isSameCompare(Cond, Pred, FV, RHS))
Craig Topper9f008862014-04-15 04:59:12 +0000398 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000399 FCmp = getFalse(Cond->getType());
400 }
401
402 // If both sides simplified to the same value, then use it as the result of
403 // the original comparison.
404 if (TCmp == FCmp)
405 return TCmp;
Duncan Sands26641d72012-02-10 14:31:24 +0000406
407 // The remaining cases only make sense if the select condition has the same
408 // type as the result of the comparison, so bail out if this is not so.
409 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
Craig Topper9f008862014-04-15 04:59:12 +0000410 return nullptr;
Duncan Sands3d5692a2011-10-30 19:56:36 +0000411 // If the false value simplified to false, then the result of the compare
412 // is equal to "Cond && TCmp". This also catches the case when the false
413 // value simplified to false and the true value to true, returning "Cond".
414 if (match(FCmp, m_Zero()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000415 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000416 return V;
417 // If the true value simplified to true, then the result of the compare
418 // is equal to "Cond || FCmp".
419 if (match(TCmp, m_One()))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000420 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000421 return V;
422 // Finally, if the false value simplified to true and the true value to
423 // false, then the result of the compare is equal to "!Cond".
424 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
425 if (Value *V =
426 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sandsb8cee002012-03-13 11:42:19 +0000427 Q, MaxRecurse))
Duncan Sands3d5692a2011-10-30 19:56:36 +0000428 return V;
429
Craig Topper9f008862014-04-15 04:59:12 +0000430 return nullptr;
Duncan Sandsb0579e92010-11-10 13:00:08 +0000431}
432
Sanjay Patel472cc782016-01-11 22:14:42 +0000433/// In the case of a binary operation with an operand that is a PHI instruction,
434/// try to simplify the binop by seeing whether evaluating it on the incoming
435/// phi values yields the same result for every value. If so returns the common
436/// value, otherwise returns null.
Craig Topper60dd9cd2017-04-07 05:57:51 +0000437static Value *ThreadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000438 Value *RHS, const SimplifyQuery &Q,
Craig Topper60dd9cd2017-04-07 05:57:51 +0000439 unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000440 // Recursion is always used, so bail out at once if we already hit the limit.
441 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000442 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000443
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000444 PHINode *PI;
445 if (isa<PHINode>(LHS)) {
446 PI = cast<PHINode>(LHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000447 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000448 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000449 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000450 } else {
451 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
452 PI = cast<PHINode>(RHS);
Duncan Sands5ffc2982010-11-16 12:16:38 +0000453 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000454 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000455 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000456 }
457
458 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000459 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000460 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000461 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000462 if (Incoming == PI) continue;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000463 Value *V = PI == LHS ?
Duncan Sandsb8cee002012-03-13 11:42:19 +0000464 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
465 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000466 // If the operation failed to simplify, or simplified to a different value
467 // to previously, then give up.
468 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000469 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000470 CommonValue = V;
471 }
472
473 return CommonValue;
474}
475
Sanjay Patel472cc782016-01-11 22:14:42 +0000476/// In the case of a comparison with a PHI instruction, try to simplify the
477/// comparison by seeing whether comparing with all of the incoming phi values
478/// yields the same result every time. If so returns the common result,
479/// otherwise returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000480static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000481 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf64e6902010-12-21 09:09:15 +0000482 // Recursion is always used, so bail out at once if we already hit the limit.
483 if (!MaxRecurse--)
Craig Topper9f008862014-04-15 04:59:12 +0000484 return nullptr;
Duncan Sandsf64e6902010-12-21 09:09:15 +0000485
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000486 // Make sure the phi is on the LHS.
487 if (!isa<PHINode>(LHS)) {
488 std::swap(LHS, RHS);
489 Pred = CmpInst::getSwappedPredicate(Pred);
490 }
491 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
492 PHINode *PI = cast<PHINode>(LHS);
493
Duncan Sands5ffc2982010-11-16 12:16:38 +0000494 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000495 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Craig Topper9f008862014-04-15 04:59:12 +0000496 return nullptr;
Duncan Sands5ffc2982010-11-16 12:16:38 +0000497
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000498 // Evaluate the BinOp on the incoming phi values.
Craig Topper9f008862014-04-15 04:59:12 +0000499 Value *CommonValue = nullptr;
Pete Cooper833f34d2015-05-12 20:05:31 +0000500 for (Value *Incoming : PI->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +0000501 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sandsf12ba1d2010-11-15 17:52:45 +0000502 if (Incoming == PI) continue;
Duncan Sandsb8cee002012-03-13 11:42:19 +0000503 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000504 // If the operation failed to simplify, or simplified to a different value
505 // to previously, then give up.
506 if (!V || (CommonValue && V != CommonValue))
Craig Topper9f008862014-04-15 04:59:12 +0000507 return nullptr;
Duncan Sandsf3b1bf12010-11-10 18:23:01 +0000508 CommonValue = V;
509 }
510
511 return CommonValue;
512}
513
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000514static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
515 Value *&Op0, Value *&Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000516 const SimplifyQuery &Q) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000517 if (auto *CLHS = dyn_cast<Constant>(Op0)) {
518 if (auto *CRHS = dyn_cast<Constant>(Op1))
519 return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
520
521 // Canonicalize the constant to the RHS if this is a commutative operation.
522 if (Instruction::isCommutative(Opcode))
523 std::swap(Op0, Op1);
524 }
525 return nullptr;
526}
527
Sanjay Patel472cc782016-01-11 22:14:42 +0000528/// Given operands for an Add, see if we can fold the result.
529/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000530static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000531 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000532 if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
533 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +0000534
Duncan Sands0a2c41682010-12-15 14:07:39 +0000535 // X + undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000536 if (match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000537 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +0000538
Duncan Sands0a2c41682010-12-15 14:07:39 +0000539 // X + 0 -> X
540 if (match(Op1, m_Zero()))
541 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +0000542
Duncan Sands0a2c41682010-12-15 14:07:39 +0000543 // X + (Y - X) -> Y
544 // (Y - X) + X -> Y
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000545 // Eg: X + -X -> 0
Craig Topper9f008862014-04-15 04:59:12 +0000546 Value *Y = nullptr;
Duncan Sands772749a2011-01-01 20:08:02 +0000547 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
548 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000549 return Y;
550
551 // X + ~X -> -1 since ~X = -X-1
Sanjay Patelfe672552017-02-18 21:59:09 +0000552 Type *Ty = Op0->getType();
Duncan Sands772749a2011-01-01 20:08:02 +0000553 if (match(Op0, m_Not(m_Specific(Op1))) ||
554 match(Op1, m_Not(m_Specific(Op0))))
Sanjay Patelfe672552017-02-18 21:59:09 +0000555 return Constant::getAllOnesValue(Ty);
556
Craig Topperbcfd2d12017-04-20 16:56:25 +0000557 // add nsw/nuw (xor Y, signmask), signmask --> Y
Sanjay Patelfe672552017-02-18 21:59:09 +0000558 // The no-wrapping add guarantees that the top bit will be set by the add.
559 // Therefore, the xor must be clearing the already set sign bit of Y.
Craig Topperbcfd2d12017-04-20 16:56:25 +0000560 if ((isNSW || isNUW) && match(Op1, m_SignMask()) &&
561 match(Op0, m_Xor(m_Value(Y), m_SignMask())))
Sanjay Patelfe672552017-02-18 21:59:09 +0000562 return Y;
Duncan Sandsb238de02010-11-19 09:20:39 +0000563
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000564 /// i1 add -> xor.
Craig Topperaa5f5242017-04-06 05:28:41 +0000565 if (MaxRecurse && Op0->getType()->getScalarType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000566 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000567 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000568
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000569 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000570 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands6c7a52c2010-12-21 08:49:00 +0000571 MaxRecurse))
572 return V;
573
Duncan Sandsb238de02010-11-19 09:20:39 +0000574 // Threading Add over selects and phi nodes is pointless, so don't bother.
575 // Threading over the select in "A + select(cond, B, C)" means evaluating
576 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
577 // only if B and C are equal. If B and C are equal then (since we assume
578 // that operands have already been simplified) "select(cond, B, C)" should
579 // have been simplified to the common value of B and C already. Analysing
580 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
581 // for threading over phi nodes.
582
Craig Topper9f008862014-04-15 04:59:12 +0000583 return nullptr;
Chris Lattner3d9823b2009-11-27 17:42:22 +0000584}
585
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000586Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000587 const SimplifyQuery &Query) {
588 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query, RecursionLimit);
589}
590
Chandler Carrutha0796552012-03-12 11:19:31 +0000591/// \brief Compute the base pointer and cumulative constant offsets for V.
592///
593/// This strips all constant offsets off of V, leaving it the base pointer, and
594/// accumulates the total constant offset applied in the returned constant. It
595/// returns 0 if V is not a pointer, and returns the constant '0' if there are
596/// no constant offsets applied.
Dan Gohman36fa8392013-01-31 02:45:26 +0000597///
598/// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
599/// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
600/// folding.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000601static Constant *stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000602 bool AllowNonInbounds = false) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000603 assert(V->getType()->getScalarType()->isPointerTy());
Chandler Carrutha0796552012-03-12 11:19:31 +0000604
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000605 Type *IntPtrTy = DL.getIntPtrType(V->getType())->getScalarType();
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000606 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
Chandler Carrutha0796552012-03-12 11:19:31 +0000607
608 // Even though we don't look through PHI nodes, we could be called on an
609 // instruction in an unreachable block, which may be on a cycle.
610 SmallPtrSet<Value *, 4> Visited;
611 Visited.insert(V);
612 do {
613 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Benjamin Kramer942dfe62013-09-23 14:16:38 +0000614 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000615 !GEP->accumulateConstantOffset(DL, Offset))
Chandler Carrutha0796552012-03-12 11:19:31 +0000616 break;
Chandler Carrutha0796552012-03-12 11:19:31 +0000617 V = GEP->getPointerOperand();
618 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
Matt Arsenault2f9cce22013-08-03 01:03:12 +0000619 V = cast<Operator>(V)->getOperand(0);
Chandler Carrutha0796552012-03-12 11:19:31 +0000620 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
Sanjoy Das5ce32722016-04-08 00:48:30 +0000621 if (GA->isInterposable())
Chandler Carrutha0796552012-03-12 11:19:31 +0000622 break;
623 V = GA->getAliasee();
624 } else {
Hal Finkel2cac58f2016-07-11 03:37:59 +0000625 if (auto CS = CallSite(V))
626 if (Value *RV = CS.getReturnedArgOperand()) {
627 V = RV;
628 continue;
629 }
Chandler Carrutha0796552012-03-12 11:19:31 +0000630 break;
631 }
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000632 assert(V->getType()->getScalarType()->isPointerTy() &&
633 "Unexpected operand type!");
David Blaikie70573dc2014-11-19 07:49:26 +0000634 } while (Visited.insert(V).second);
Chandler Carrutha0796552012-03-12 11:19:31 +0000635
Benjamin Kramerc05aa952013-02-01 15:21:10 +0000636 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
637 if (V->getType()->isVectorTy())
638 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
639 OffsetIntPtr);
640 return OffsetIntPtr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000641}
642
643/// \brief Compute the constant difference between two pointer values.
644/// If the difference is not a constant, returns zero.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000645static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
646 Value *RHS) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000647 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
648 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carrutha0796552012-03-12 11:19:31 +0000649
650 // If LHS and RHS are not related via constant offsets to the same base
651 // value, there is nothing we can do here.
652 if (LHS != RHS)
Craig Topper9f008862014-04-15 04:59:12 +0000653 return nullptr;
Chandler Carrutha0796552012-03-12 11:19:31 +0000654
655 // Otherwise, the difference of LHS - RHS can be computed as:
656 // LHS - RHS
657 // = (LHSOffset + Base) - (RHSOffset + Base)
658 // = LHSOffset - RHSOffset
659 return ConstantExpr::getSub(LHSOffset, RHSOffset);
660}
661
Sanjay Patel472cc782016-01-11 22:14:42 +0000662/// Given operands for a Sub, see if we can fold the result.
663/// If not, this returns null.
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000664static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000665 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000666 if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
667 return C;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000668
669 // X - undef -> undef
670 // undef - X -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000671 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sands0a2c41682010-12-15 14:07:39 +0000672 return UndefValue::get(Op0->getType());
673
674 // X - 0 -> X
675 if (match(Op1, m_Zero()))
676 return Op0;
677
678 // X - X -> 0
Duncan Sands772749a2011-01-01 20:08:02 +0000679 if (Op0 == Op1)
Duncan Sands0a2c41682010-12-15 14:07:39 +0000680 return Constant::getNullValue(Op0->getType());
681
Sanjay Patelefd88852016-10-19 21:23:45 +0000682 // Is this a negation?
683 if (match(Op0, m_Zero())) {
684 // 0 - X -> 0 if the sub is NUW.
685 if (isNUW)
686 return Op0;
687
688 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +0000689 KnownBits Known(BitWidth);
690 computeKnownBits(Op1, Known, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
691 if (Known.Zero.isMaxSignedValue()) {
Sanjay Patelefd88852016-10-19 21:23:45 +0000692 // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
693 // Op1 must be 0 because negating the minimum signed value is undefined.
694 if (isNSW)
695 return Op0;
696
697 // 0 - X -> X if X is 0 or the minimum signed value.
698 return Op1;
699 }
700 }
David Majnemercd4fbcd2014-07-31 04:49:18 +0000701
Duncan Sands99589d02011-01-18 11:50:19 +0000702 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
703 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
Dinesh Dwivedi99281a02014-06-26 08:57:33 +0000704 Value *X = nullptr, *Y = nullptr, *Z = Op1;
Duncan Sands99589d02011-01-18 11:50:19 +0000705 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
706 // See if "V === Y - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000707 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000708 // It does! Now see if "X + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000709 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000710 // It does, we successfully reassociated!
711 ++NumReassoc;
712 return W;
713 }
714 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000715 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000716 // It does! Now see if "Y + V" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000717 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000718 // It does, we successfully reassociated!
719 ++NumReassoc;
720 return W;
721 }
722 }
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000723
Duncan Sands99589d02011-01-18 11:50:19 +0000724 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
725 // For example, X - (X + 1) -> -1
726 X = Op0;
727 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
728 // See if "V === X - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000729 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000730 // It does! Now see if "V - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000731 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000732 // It does, we successfully reassociated!
733 ++NumReassoc;
734 return W;
735 }
736 // See if "V === X - Z" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000737 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000738 // It does! Now see if "V - Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000739 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sands99589d02011-01-18 11:50:19 +0000740 // It does, we successfully reassociated!
741 ++NumReassoc;
742 return W;
743 }
744 }
745
746 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
747 // For example, X - (X - Y) -> Y.
748 Z = Op0;
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000749 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
750 // See if "V === Z - X" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000751 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000752 // It does! Now see if "V + Y" simplifies.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000753 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsd6f1a952011-01-14 15:26:10 +0000754 // It does, we successfully reassociated!
755 ++NumReassoc;
756 return W;
757 }
758
Duncan Sands395ac42d2012-03-13 14:07:05 +0000759 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
760 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
761 match(Op1, m_Trunc(m_Value(Y))))
762 if (X->getType() == Y->getType())
763 // See if "V === X - Y" simplifies.
764 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
765 // It does! Now see if "trunc V" simplifies.
David Majnemer6774d612016-07-26 17:58:05 +0000766 if (Value *W = SimplifyCastInst(Instruction::Trunc, V, Op0->getType(),
767 Q, MaxRecurse - 1))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000768 // It does, return the simplified "trunc V".
769 return W;
770
771 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
Dan Gohman18c77a12013-01-31 02:50:36 +0000772 if (match(Op0, m_PtrToInt(m_Value(X))) &&
Duncan Sands395ac42d2012-03-13 14:07:05 +0000773 match(Op1, m_PtrToInt(m_Value(Y))))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000774 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
Duncan Sands395ac42d2012-03-13 14:07:05 +0000775 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
776
Duncan Sands99589d02011-01-18 11:50:19 +0000777 // i1 sub -> xor.
Craig Topperaa5f5242017-04-06 05:28:41 +0000778 if (MaxRecurse && Op0->getType()->getScalarType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000779 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands99589d02011-01-18 11:50:19 +0000780 return V;
781
Duncan Sands0a2c41682010-12-15 14:07:39 +0000782 // Threading Sub over selects and phi nodes is pointless, so don't bother.
783 // Threading over the select in "A - select(cond, B, C)" means evaluating
784 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
785 // only if B and C are equal. If B and C are equal then (since we assume
786 // that operands have already been simplified) "select(cond, B, C)" should
787 // have been simplified to the common value of B and C already. Analysing
788 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
789 // for threading over phi nodes.
790
Craig Topper9f008862014-04-15 04:59:12 +0000791 return nullptr;
Duncan Sands0a2c41682010-12-15 14:07:39 +0000792}
793
Duncan Sandsed6d6c32010-12-20 14:47:04 +0000794Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000795 const SimplifyQuery &Q) {
796 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
797}
798
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000799/// Given operands for an FAdd, see if we can fold the result. If not, this
800/// returns null.
801static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000802 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000803 if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
804 return C;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000805
806 // fadd X, -0 ==> X
807 if (match(Op1, m_NegZero()))
808 return Op0;
809
810 // fadd X, 0 ==> X, when we know X is not -0
811 if (match(Op1, m_Zero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000812 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000813 return Op0;
814
815 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
816 // where nnan and ninf have to occur at least once somewhere in this
817 // expression
Craig Topper9f008862014-04-15 04:59:12 +0000818 Value *SubOp = nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000819 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
820 SubOp = Op1;
821 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
822 SubOp = Op0;
823 if (SubOp) {
824 Instruction *FSub = cast<Instruction>(SubOp);
825 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
826 (FMF.noInfs() || FSub->hasNoInfs()))
827 return Constant::getNullValue(Op0->getType());
828 }
829
Craig Topper9f008862014-04-15 04:59:12 +0000830 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000831}
832
833/// Given operands for an FSub, see if we can fold the result. If not, this
834/// returns null.
835static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000836 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000837 if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
838 return C;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000839
840 // fsub X, 0 ==> X
841 if (match(Op1, m_Zero()))
842 return Op0;
843
844 // fsub X, -0 ==> X, when we know X is not -0
845 if (match(Op1, m_NegZero()) &&
David Majnemer3ee5f342016-04-13 06:55:52 +0000846 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000847 return Op0;
848
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000849 // fsub -0.0, (fsub -0.0, X) ==> X
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000850 Value *X;
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000851 if (match(Op0, m_NegZero()) && match(Op1, m_FSub(m_NegZero(), m_Value(X))))
852 return X;
853
854 // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
Benjamin Kramer6bb15022016-02-29 12:18:25 +0000855 if (FMF.noSignedZeros() && match(Op0, m_AnyZero()) &&
Benjamin Kramerf5b2a472016-02-29 11:12:23 +0000856 match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
857 return X;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000858
Benjamin Kramer228680d2015-06-14 21:01:20 +0000859 // fsub nnan x, x ==> 0.0
860 if (FMF.noNaNs() && Op0 == Op1)
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000861 return Constant::getNullValue(Op0->getType());
862
Craig Topper9f008862014-04-15 04:59:12 +0000863 return nullptr;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000864}
865
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000866/// Given the operands for an FMul, see if we can fold the result
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000867static Value *SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000868 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000869 if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
870 return C;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000871
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000872 // fmul X, 1.0 ==> X
873 if (match(Op1, m_FPOne()))
874 return Op0;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000875
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000876 // fmul nnan nsz X, 0 ==> 0
877 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
878 return Op1;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000879
Sanjay Patel1fd16f02017-04-01 18:40:30 +0000880 return nullptr;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +0000881}
882
Sanjay Patel472cc782016-01-11 22:14:42 +0000883/// Given operands for a Mul, see if we can fold the result.
884/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000885static Value *SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000886 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +0000887 if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
888 return C;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000889
890 // X * undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +0000891 if (match(Op1, m_Undef()))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000892 return Constant::getNullValue(Op0->getType());
893
894 // X * 0 -> 0
895 if (match(Op1, m_Zero()))
896 return Op1;
897
898 // X * 1 -> X
899 if (match(Op1, m_One()))
900 return Op0;
901
Duncan Sandsb67edc62011-01-30 18:03:50 +0000902 // (X / Y) * Y -> X if the division is exact.
Craig Topper9f008862014-04-15 04:59:12 +0000903 Value *X = nullptr;
Benjamin Kramer9442cd02012-01-01 17:55:30 +0000904 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
905 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
906 return X;
Duncan Sandsb67edc62011-01-30 18:03:50 +0000907
Nick Lewyckyb89d9a42011-01-29 19:55:23 +0000908 // i1 mul -> and.
Craig Topper2f1e1c32017-04-06 17:33:37 +0000909 if (MaxRecurse && Op0->getType()->getScalarType()->isIntegerTy(1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000910 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsfecc6422010-12-21 15:03:43 +0000911 return V;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000912
913 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +0000914 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000915 MaxRecurse))
916 return V;
917
918 // Mul distributes over Add. Try some generic simplifications based on this.
919 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sandsb8cee002012-03-13 11:42:19 +0000920 Q, MaxRecurse))
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000921 return V;
922
923 // If the operation is with the result of a select instruction, check whether
924 // operating on either branch of the select always yields the same value.
925 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000926 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000927 MaxRecurse))
928 return V;
929
930 // If the operation is with the result of a phi instruction, check whether
931 // operating on all incoming values of the phi always yields the same value.
932 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +0000933 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000934 MaxRecurse))
935 return V;
936
Craig Topper9f008862014-04-15 04:59:12 +0000937 return nullptr;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +0000938}
939
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000940Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000941 const SimplifyQuery &Q) {
942 return ::SimplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit);
943}
944
Michael Ilsemanbb6f6912012-12-12 00:27:46 +0000945
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000946Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
947 const SimplifyQuery &Q) {
948 return ::SimplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit);
949}
950
Chandler Carruth66b31302015-01-04 12:03:27 +0000951Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000952 const SimplifyQuery &Q) {
953 return ::SimplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit);
954}
955
Daniel Berlin5e3fcb12017-04-26 04:09:56 +0000956Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
957 return ::SimplifyMulInst(Op0, Op1, Q, RecursionLimit);
958}
959
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000960/// Check for common or similar folds of integer division or integer remainder.
961static Value *simplifyDivRem(Value *Op0, Value *Op1, bool IsDiv) {
962 Type *Ty = Op0->getType();
963
964 // X / undef -> undef
965 // X % undef -> undef
966 if (match(Op1, m_Undef()))
967 return Op1;
968
969 // X / 0 -> undef
970 // X % 0 -> undef
971 // We don't need to preserve faults!
972 if (match(Op1, m_Zero()))
973 return UndefValue::get(Ty);
974
Sanjay Patel2b1f6f42017-03-09 16:20:52 +0000975 // If any element of a constant divisor vector is zero, the whole op is undef.
976 auto *Op1C = dyn_cast<Constant>(Op1);
977 if (Op1C && Ty->isVectorTy()) {
978 unsigned NumElts = Ty->getVectorNumElements();
979 for (unsigned i = 0; i != NumElts; ++i) {
980 Constant *Elt = Op1C->getAggregateElement(i);
981 if (Elt && Elt->isNullValue())
982 return UndefValue::get(Ty);
983 }
984 }
985
Sanjay Patel0cb2ee92017-03-06 19:08:35 +0000986 // undef / X -> 0
987 // undef % X -> 0
988 if (match(Op0, m_Undef()))
989 return Constant::getNullValue(Ty);
990
991 // 0 / X -> 0
992 // 0 % X -> 0
993 if (match(Op0, m_Zero()))
994 return Op0;
995
996 // X / X -> 1
997 // X % X -> 0
998 if (Op0 == Op1)
999 return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
1000
1001 // X / 1 -> X
1002 // X % 1 -> 0
Sanjay Patel962a8432017-03-09 21:56:03 +00001003 // If this is a boolean op (single-bit element type), we can't have
1004 // division-by-zero or remainder-by-zero, so assume the divisor is 1.
1005 if (match(Op1, m_One()) || Ty->getScalarType()->isIntegerTy(1))
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001006 return IsDiv ? Op0 : Constant::getNullValue(Ty);
1007
1008 return nullptr;
1009}
1010
Sanjay Patel472cc782016-01-11 22:14:42 +00001011/// Given operands for an SDiv or UDiv, see if we can fold the result.
1012/// If not, this returns null.
Anders Carlsson36c6d232011-02-05 18:33:43 +00001013static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001014 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001015 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1016 return C;
Duncan Sands771e82a2011-01-28 16:51:11 +00001017
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001018 if (Value *V = simplifyDivRem(Op0, Op1, true))
1019 return V;
1020
Duncan Sands65995fa2011-01-28 18:50:50 +00001021 bool isSigned = Opcode == Instruction::SDiv;
1022
Duncan Sands771e82a2011-01-28 16:51:11 +00001023 // (X * Y) / Y -> X if the multiplication does not overflow.
Craig Topper9f008862014-04-15 04:59:12 +00001024 Value *X = nullptr, *Y = nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001025 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1026 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands7cb61e52011-10-27 19:16:21 +00001027 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands5747aba2011-02-02 20:52:00 +00001028 // If the Mul knows it does not overflow, then we are good to go.
1029 if ((isSigned && Mul->hasNoSignedWrap()) ||
1030 (!isSigned && Mul->hasNoUnsignedWrap()))
1031 return X;
Duncan Sands771e82a2011-01-28 16:51:11 +00001032 // If X has the form X = A / Y then X * Y cannot overflow.
1033 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1034 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1035 return X;
1036 }
1037
Duncan Sands65995fa2011-01-28 18:50:50 +00001038 // (X rem Y) / Y -> 0
1039 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1040 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1041 return Constant::getNullValue(Op0->getType());
1042
David Majnemercb9d5962014-10-11 10:20:01 +00001043 // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
1044 ConstantInt *C1, *C2;
1045 if (!isSigned && match(Op0, m_UDiv(m_Value(X), m_ConstantInt(C1))) &&
1046 match(Op1, m_ConstantInt(C2))) {
1047 bool Overflow;
Craig Topper9b71a402017-04-19 21:09:45 +00001048 (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
David Majnemercb9d5962014-10-11 10:20:01 +00001049 if (Overflow)
1050 return Constant::getNullValue(Op0->getType());
1051 }
1052
Duncan Sands65995fa2011-01-28 18:50:50 +00001053 // If the operation is with the result of a select instruction, check whether
1054 // operating on either branch of the select always yields the same value.
1055 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001056 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001057 return V;
1058
1059 // If the operation is with the result of a phi instruction, check whether
1060 // operating on all incoming values of the phi always yields the same value.
1061 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001062 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands65995fa2011-01-28 18:50:50 +00001063 return V;
1064
Craig Topper9f008862014-04-15 04:59:12 +00001065 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001066}
1067
Sanjay Patel472cc782016-01-11 22:14:42 +00001068/// Given operands for an SDiv, see if we can fold the result.
1069/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001070static Value *SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001071 unsigned MaxRecurse) {
1072 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001073 return V;
1074
Craig Topper9f008862014-04-15 04:59:12 +00001075 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001076}
1077
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001078Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1079 return ::SimplifySDivInst(Op0, Op1, Q, RecursionLimit);
1080}
1081
Sanjay Patel472cc782016-01-11 22:14:42 +00001082/// Given operands for a UDiv, see if we can fold the result.
1083/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001084static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001085 unsigned MaxRecurse) {
1086 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands771e82a2011-01-28 16:51:11 +00001087 return V;
1088
David Majnemer63da0c22017-01-06 22:58:02 +00001089 // udiv %V, C -> 0 if %V < C
1090 if (MaxRecurse) {
1091 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1092 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1093 if (C->isAllOnesValue()) {
1094 return Constant::getNullValue(Op0->getType());
1095 }
1096 }
1097 }
1098
Craig Topper9f008862014-04-15 04:59:12 +00001099 return nullptr;
Duncan Sands771e82a2011-01-28 16:51:11 +00001100}
1101
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001102Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1103 return ::SimplifyUDivInst(Op0, Op1, Q, RecursionLimit);
1104}
1105
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001106static Value *SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001107 const SimplifyQuery &Q, unsigned) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001108 if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
1109 return C;
1110
Frits van Bommelc2549662011-01-29 15:26:31 +00001111 // undef / X -> undef (the undef could be a snan).
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001112 if (match(Op0, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001113 return Op0;
1114
1115 // X / undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001116 if (match(Op1, m_Undef()))
Frits van Bommelc2549662011-01-29 15:26:31 +00001117 return Op1;
1118
Zia Ansari394cef82016-12-08 23:27:40 +00001119 // X / 1.0 -> X
1120 if (match(Op1, m_FPOne()))
1121 return Op0;
1122
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001123 // 0 / X -> 0
1124 // Requires that NaNs are off (X could be zero) and signed zeroes are
1125 // ignored (X could be positive or negative, so the output sign is unknown).
1126 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1127 return Op0;
1128
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001129 if (FMF.noNaNs()) {
1130 // X / X -> 1.0 is legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001131 if (Op0 == Op1)
1132 return ConstantFP::get(Op0->getType(), 1.0);
1133
1134 // -X / X -> -1.0 and
Benjamin Kramer1ee59cb2015-06-16 14:57:29 +00001135 // X / -X -> -1.0 are legal when NaNs are ignored.
Benjamin Kramer4f052462015-06-14 18:53:58 +00001136 // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
1137 if ((BinaryOperator::isFNeg(Op0, /*IgnoreZeroSign=*/true) &&
1138 BinaryOperator::getFNegArgument(Op0) == Op1) ||
1139 (BinaryOperator::isFNeg(Op1, /*IgnoreZeroSign=*/true) &&
1140 BinaryOperator::getFNegArgument(Op1) == Op0))
1141 return ConstantFP::get(Op0->getType(), -1.0);
1142 }
1143
Craig Topper9f008862014-04-15 04:59:12 +00001144 return nullptr;
Frits van Bommelc2549662011-01-29 15:26:31 +00001145}
1146
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001147Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001148 const SimplifyQuery &Q) {
1149 return ::SimplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit);
1150}
1151
Sanjay Patel472cc782016-01-11 22:14:42 +00001152/// Given operands for an SRem or URem, see if we can fold the result.
1153/// If not, this returns null.
Duncan Sandsa3e36992011-05-02 16:27:02 +00001154static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001155 const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001156 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1157 return C;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001158
Sanjay Patel0cb2ee92017-03-06 19:08:35 +00001159 if (Value *V = simplifyDivRem(Op0, Op1, false))
1160 return V;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001161
David Majnemerb435a422014-09-17 04:16:35 +00001162 // (X % Y) % Y -> X % Y
1163 if ((Opcode == Instruction::SRem &&
1164 match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1165 (Opcode == Instruction::URem &&
1166 match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
David Majnemerac717f02014-09-17 03:34:34 +00001167 return Op0;
David Majnemerac717f02014-09-17 03:34:34 +00001168
Duncan Sandsa3e36992011-05-02 16:27:02 +00001169 // If the operation is with the result of a select instruction, check whether
1170 // operating on either branch of the select always yields the same value.
1171 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001172 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001173 return V;
1174
1175 // If the operation is with the result of a phi instruction, check whether
1176 // operating on all incoming values of the phi always yields the same value.
1177 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001178 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001179 return V;
1180
Craig Topper9f008862014-04-15 04:59:12 +00001181 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001182}
1183
Sanjay Patel472cc782016-01-11 22:14:42 +00001184/// Given operands for an SRem, see if we can fold the result.
1185/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001186static Value *SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001187 unsigned MaxRecurse) {
1188 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001189 return V;
1190
Craig Topper9f008862014-04-15 04:59:12 +00001191 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001192}
1193
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001194Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1195 return ::SimplifySRemInst(Op0, Op1, Q, RecursionLimit);
1196}
1197
Sanjay Patel472cc782016-01-11 22:14:42 +00001198/// Given operands for a URem, see if we can fold the result.
1199/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001200static Value *SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001201 unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001202 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e36992011-05-02 16:27:02 +00001203 return V;
1204
David Majnemer8c0e62f2017-01-06 21:23:51 +00001205 // urem %V, C -> %V if %V < C
1206 if (MaxRecurse) {
1207 if (Constant *C = dyn_cast_or_null<Constant>(SimplifyICmpInst(
1208 ICmpInst::ICMP_ULT, Op0, Op1, Q, MaxRecurse - 1))) {
1209 if (C->isAllOnesValue()) {
1210 return Op0;
1211 }
1212 }
1213 }
1214
Craig Topper9f008862014-04-15 04:59:12 +00001215 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001216}
1217
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001218Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1219 return ::SimplifyURemInst(Op0, Op1, Q, RecursionLimit);
1220}
1221
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001222static Value *SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001223 const SimplifyQuery &Q, unsigned) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001224 if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
1225 return C;
1226
Duncan Sandsa3e36992011-05-02 16:27:02 +00001227 // undef % X -> undef (the undef could be a snan).
1228 if (match(Op0, m_Undef()))
1229 return Op0;
1230
1231 // X % undef -> undef
1232 if (match(Op1, m_Undef()))
1233 return Op1;
1234
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001235 // 0 % X -> 0
1236 // Requires that NaNs are off (X could be zero) and signed zeroes are
1237 // ignored (X could be positive or negative, so the output sign is unknown).
1238 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZero()))
1239 return Op0;
1240
Craig Topper9f008862014-04-15 04:59:12 +00001241 return nullptr;
Duncan Sandsa3e36992011-05-02 16:27:02 +00001242}
1243
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00001244Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001245 const SimplifyQuery &Q) {
1246 return ::SimplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit);
1247}
1248
Sanjay Patel472cc782016-01-11 22:14:42 +00001249/// Returns true if a shift by \c Amount always yields undef.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001250static bool isUndefShift(Value *Amount) {
1251 Constant *C = dyn_cast<Constant>(Amount);
1252 if (!C)
1253 return false;
1254
1255 // X shift by undef -> undef because it may shift by the bitwidth.
1256 if (isa<UndefValue>(C))
1257 return true;
1258
1259 // Shifting by the bitwidth or more is undefined.
1260 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1261 if (CI->getValue().getLimitedValue() >=
1262 CI->getType()->getScalarSizeInBits())
1263 return true;
1264
1265 // If all lanes of a vector shift are undefined the whole shift is.
1266 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1267 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1268 if (!isUndefShift(C->getAggregateElement(I)))
1269 return false;
1270 return true;
1271 }
1272
1273 return false;
1274}
1275
Sanjay Patel472cc782016-01-11 22:14:42 +00001276/// Given operands for an Shl, LShr or AShr, see if we can fold the result.
1277/// If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001278static Value *SimplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001279 Value *Op1, const SimplifyQuery &Q, unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001280 if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
1281 return C;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001282
Duncan Sands571fd9a2011-01-14 14:44:12 +00001283 // 0 shift by X -> 0
Duncan Sands7f60dc12011-01-14 00:37:45 +00001284 if (match(Op0, m_Zero()))
1285 return Op0;
1286
Duncan Sands571fd9a2011-01-14 14:44:12 +00001287 // X shift by 0 -> X
Duncan Sands7f60dc12011-01-14 00:37:45 +00001288 if (match(Op1, m_Zero()))
1289 return Op0;
1290
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00001291 // Fold undefined shifts.
1292 if (isUndefShift(Op1))
1293 return UndefValue::get(Op0->getType());
Duncan Sands7f60dc12011-01-14 00:37:45 +00001294
Duncan Sands571fd9a2011-01-14 14:44:12 +00001295 // If the operation is with the result of a select instruction, check whether
1296 // operating on either branch of the select always yields the same value.
1297 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001298 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001299 return V;
1300
1301 // If the operation is with the result of a phi instruction, check whether
1302 // operating on all incoming values of the phi always yields the same value.
1303 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001304 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001305 return V;
1306
Sanjay Patel6786bc52016-05-10 20:46:54 +00001307 // If any bits in the shift amount make that value greater than or equal to
1308 // the number of bits in the type, the shift is undefined.
1309 unsigned BitWidth = Op1->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001310 KnownBits Known(BitWidth);
1311 computeKnownBits(Op1, Known, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
1312 if (Known.One.getLimitedValue() >= BitWidth)
Sanjay Patel6786bc52016-05-10 20:46:54 +00001313 return UndefValue::get(Op0->getType());
1314
1315 // If all valid bits in the shift amount are known zero, the first operand is
1316 // unchanged.
1317 unsigned NumValidShiftBits = Log2_32_Ceil(BitWidth);
Craig Topperb45eabc2017-04-26 16:39:58 +00001318 if (Known.Zero.countTrailingOnes() >= NumValidShiftBits)
Sanjay Patel6786bc52016-05-10 20:46:54 +00001319 return Op0;
1320
Craig Topper9f008862014-04-15 04:59:12 +00001321 return nullptr;
Duncan Sands571fd9a2011-01-14 14:44:12 +00001322}
1323
David Majnemerbf7550e2014-11-05 00:59:59 +00001324/// \brief Given operands for an Shl, LShr or AShr, see if we can
1325/// fold the result. If not, this returns null.
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001326static Value *SimplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001327 Value *Op1, bool isExact, const SimplifyQuery &Q,
David Majnemerbf7550e2014-11-05 00:59:59 +00001328 unsigned MaxRecurse) {
1329 if (Value *V = SimplifyShift(Opcode, Op0, Op1, Q, MaxRecurse))
1330 return V;
1331
1332 // X >> X -> 0
1333 if (Op0 == Op1)
1334 return Constant::getNullValue(Op0->getType());
1335
David Majnemer65c52ae2014-12-17 01:54:33 +00001336 // undef >> X -> 0
1337 // undef >> X -> undef (if it's exact)
1338 if (match(Op0, m_Undef()))
1339 return isExact ? Op0 : Constant::getNullValue(Op0->getType());
1340
David Majnemerbf7550e2014-11-05 00:59:59 +00001341 // The low bit cannot be shifted out of an exact shift if it is set.
1342 if (isExact) {
1343 unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00001344 KnownBits Op0Known(BitWidth);
1345 computeKnownBits(Op0, Op0Known, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
1346 if (Op0Known.One[0])
David Majnemerbf7550e2014-11-05 00:59:59 +00001347 return Op0;
1348 }
1349
1350 return nullptr;
1351}
1352
Sanjay Patel472cc782016-01-11 22:14:42 +00001353/// Given operands for an Shl, see if we can fold the result.
1354/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001355static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001356 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsb8cee002012-03-13 11:42:19 +00001357 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001358 return V;
1359
1360 // undef << X -> 0
David Majnemer65c52ae2014-12-17 01:54:33 +00001361 // undef << X -> undef if (if it's NSW/NUW)
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001362 if (match(Op0, m_Undef()))
David Majnemer65c52ae2014-12-17 01:54:33 +00001363 return isNSW || isNUW ? Op0 : Constant::getNullValue(Op0->getType());
Duncan Sands571fd9a2011-01-14 14:44:12 +00001364
Chris Lattner9e4aa022011-02-09 17:15:04 +00001365 // (X >> A) << A -> X
1366 Value *X;
Benjamin Kramer9442cd02012-01-01 17:55:30 +00001367 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001368 return X;
Craig Topper9f008862014-04-15 04:59:12 +00001369 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001370}
1371
Chris Lattner9e4aa022011-02-09 17:15:04 +00001372Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001373 const SimplifyQuery &Q) {
1374 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Q, RecursionLimit);
1375}
1376
Sanjay Patel472cc782016-01-11 22:14:42 +00001377/// Given operands for an LShr, see if we can fold the result.
1378/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001379static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001380 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001381 if (Value *V = SimplifyRightShift(Instruction::LShr, Op0, Op1, isExact, Q,
1382 MaxRecurse))
1383 return V;
David Majnemera80fed72013-07-09 22:01:22 +00001384
Chris Lattner9e4aa022011-02-09 17:15:04 +00001385 // (X << A) >> A -> X
1386 Value *X;
David Majnemer4f438372014-11-04 17:38:50 +00001387 if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001388 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001389
Craig Topper9f008862014-04-15 04:59:12 +00001390 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001391}
1392
Chris Lattner9e4aa022011-02-09 17:15:04 +00001393Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001394 const SimplifyQuery &Q) {
1395 return ::SimplifyLShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1396}
1397
Sanjay Patel472cc782016-01-11 22:14:42 +00001398/// Given operands for an AShr, see if we can fold the result.
1399/// If not, this returns null.
Chris Lattner9e4aa022011-02-09 17:15:04 +00001400static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001401 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemerbf7550e2014-11-05 00:59:59 +00001402 if (Value *V = SimplifyRightShift(Instruction::AShr, Op0, Op1, isExact, Q,
1403 MaxRecurse))
Duncan Sands571fd9a2011-01-14 14:44:12 +00001404 return V;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001405
1406 // all ones >>a X -> all ones
1407 if (match(Op0, m_AllOnes()))
1408 return Op0;
1409
Chris Lattner9e4aa022011-02-09 17:15:04 +00001410 // (X << A) >> A -> X
1411 Value *X;
David Majnemer2de97fc2014-11-04 17:47:13 +00001412 if (match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
Chris Lattner9e4aa022011-02-09 17:15:04 +00001413 return X;
Duncan Sandsd114ab32011-02-13 17:15:40 +00001414
Suyog Sarda68862412014-07-17 06:28:15 +00001415 // Arithmetic shifting an all-sign-bit value is a no-op.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001416 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
Suyog Sarda68862412014-07-17 06:28:15 +00001417 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1418 return Op0;
1419
Craig Topper9f008862014-04-15 04:59:12 +00001420 return nullptr;
Duncan Sands7f60dc12011-01-14 00:37:45 +00001421}
1422
Chris Lattner9e4aa022011-02-09 17:15:04 +00001423Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001424 const SimplifyQuery &Q) {
1425 return ::SimplifyAShrInst(Op0, Op1, isExact, Q, RecursionLimit);
1426}
1427
David Majnemer1af36e52014-12-06 10:51:40 +00001428static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
1429 ICmpInst *UnsignedICmp, bool IsAnd) {
1430 Value *X, *Y;
1431
1432 ICmpInst::Predicate EqPred;
David Majnemerd5b3aa42014-12-08 18:30:43 +00001433 if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
1434 !ICmpInst::isEquality(EqPred))
David Majnemer1af36e52014-12-06 10:51:40 +00001435 return nullptr;
1436
1437 ICmpInst::Predicate UnsignedPred;
1438 if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
1439 ICmpInst::isUnsigned(UnsignedPred))
1440 ;
1441 else if (match(UnsignedICmp,
1442 m_ICmp(UnsignedPred, m_Value(Y), m_Specific(X))) &&
1443 ICmpInst::isUnsigned(UnsignedPred))
1444 UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
1445 else
1446 return nullptr;
1447
1448 // X < Y && Y != 0 --> X < Y
1449 // X < Y || Y != 0 --> Y != 0
1450 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
1451 return IsAnd ? UnsignedICmp : ZeroICmp;
1452
1453 // X >= Y || Y != 0 --> true
1454 // X >= Y || Y == 0 --> X >= Y
1455 if (UnsignedPred == ICmpInst::ICMP_UGE && !IsAnd) {
1456 if (EqPred == ICmpInst::ICMP_NE)
1457 return getTrue(UnsignedICmp->getType());
1458 return UnsignedICmp;
1459 }
1460
David Majnemerd5b3aa42014-12-08 18:30:43 +00001461 // X < Y && Y == 0 --> false
1462 if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
1463 IsAnd)
1464 return getFalse(UnsignedICmp->getType());
1465
David Majnemer1af36e52014-12-06 10:51:40 +00001466 return nullptr;
1467}
1468
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001469/// Commuted variants are assumed to be handled by calling this function again
1470/// with the parameters swapped.
1471static Value *simplifyAndOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1472 ICmpInst::Predicate Pred0, Pred1;
1473 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001474 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1475 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001476 return nullptr;
1477
1478 // We have (icmp Pred0, A, B) & (icmp Pred1, A, B).
1479 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1480 // can eliminate Op1 from this 'and'.
1481 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1482 return Op0;
1483
1484 // Check for any combination of predicates that are guaranteed to be disjoint.
1485 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1486 (Pred0 == ICmpInst::ICMP_EQ && ICmpInst::isFalseWhenEqual(Pred1)) ||
1487 (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT) ||
1488 (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT))
1489 return getFalse(Op0->getType());
1490
1491 return nullptr;
1492}
1493
1494/// Commuted variants are assumed to be handled by calling this function again
1495/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001496static Value *SimplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001497 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true))
1498 return X;
1499
Sanjay Patel9b1b2de2016-12-06 19:05:46 +00001500 if (Value *X = simplifyAndOfICmpsWithSameOperands(Op0, Op1))
1501 return X;
1502
Sanjay Patel35c362e2017-04-24 21:52:39 +00001503 // FIXME: This should be shared with or-of-icmps.
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001504 // Look for this pattern: (icmp V, C0) & (icmp V, C1)).
Sanjay Patelb2332e12016-09-20 14:36:14 +00001505 Type *ITy = Op0->getType();
1506 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001507 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001508 Value *V;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001509 if (match(Op0, m_ICmp(Pred0, m_Value(V), m_APInt(C0))) &&
1510 match(Op1, m_ICmp(Pred1, m_Specific(V), m_APInt(C1)))) {
1511 // Make a constant range that's the intersection of the two icmp ranges.
1512 // If the intersection is empty, we know that the result is false.
Sanjay Patel35c362e2017-04-24 21:52:39 +00001513 auto Range0 = ConstantRange::makeExactICmpRegion(Pred0, *C0);
1514 auto Range1 = ConstantRange::makeExactICmpRegion(Pred1, *C1);
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001515 if (Range0.intersectWith(Range1).isEmptySet())
1516 return getFalse(ITy);
Sanjay Patel35c362e2017-04-24 21:52:39 +00001517
1518 // If a range is a superset of the other, the smaller set is all we need.
1519 if (Range0.contains(Range1))
1520 return Op1;
1521 if (Range1.contains(Range0))
1522 return Op0;
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001523 }
1524
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001525 // (icmp (add V, C0), C1) & (icmp V, C0)
1526 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelf8ee0e02016-06-19 17:20:27 +00001527 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001528
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001529 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
David Majnemera315bd82014-09-15 08:15:28 +00001530 return nullptr;
1531
David Majnemera315bd82014-09-15 08:15:28 +00001532 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001533 if (AddInst->getOperand(1) != Op1->getOperand(1))
1534 return nullptr;
1535
David Majnemera315bd82014-09-15 08:15:28 +00001536 bool isNSW = AddInst->hasNoSignedWrap();
1537 bool isNUW = AddInst->hasNoUnsignedWrap();
1538
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001539 const APInt Delta = *C1 - *C0;
1540 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001541 if (Delta == 2) {
1542 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
1543 return getFalse(ITy);
1544 if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1545 return getFalse(ITy);
1546 }
1547 if (Delta == 1) {
1548 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
1549 return getFalse(ITy);
1550 if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && isNSW)
1551 return getFalse(ITy);
1552 }
1553 }
Sanjay Patel1b312ad2016-09-28 13:53:13 +00001554 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001555 if (Delta == 2)
1556 if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
1557 return getFalse(ITy);
1558 if (Delta == 1)
1559 if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
1560 return getFalse(ITy);
1561 }
1562
1563 return nullptr;
1564}
1565
Sanjay Patel472cc782016-01-11 22:14:42 +00001566/// Given operands for an And, see if we can fold the result.
1567/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001568static Value *SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001569 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001570 if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
1571 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001572
Chris Lattnera71e9d62009-11-10 00:55:12 +00001573 // X & undef -> 0
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001574 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001575 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001576
Chris Lattnera71e9d62009-11-10 00:55:12 +00001577 // X & X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001578 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001579 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001580
Duncan Sandsc89ac072010-11-17 18:52:15 +00001581 // X & 0 = 0
1582 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001583 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001584
Duncan Sandsc89ac072010-11-17 18:52:15 +00001585 // X & -1 = X
1586 if (match(Op1, m_AllOnes()))
1587 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001588
Chris Lattnera71e9d62009-11-10 00:55:12 +00001589 // A & ~A = ~A & A = 0
Chris Lattner9e4aa022011-02-09 17:15:04 +00001590 if (match(Op0, m_Not(m_Specific(Op1))) ||
1591 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001592 return Constant::getNullValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001593
Chris Lattnera71e9d62009-11-10 00:55:12 +00001594 // (A | ?) & A = A
Craig Topper9f008862014-04-15 04:59:12 +00001595 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001596 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001597 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001598 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001599
Chris Lattnera71e9d62009-11-10 00:55:12 +00001600 // A & (A | ?) = A
1601 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001602 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001603 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001604
Duncan Sandsba286d72011-10-26 20:55:21 +00001605 // A & (-A) = A if A is a power of two or zero.
1606 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1607 match(Op1, m_Neg(m_Specific(Op0)))) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001608 if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1609 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001610 return Op0;
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001611 if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
1612 Q.DT))
Duncan Sandsba286d72011-10-26 20:55:21 +00001613 return Op1;
1614 }
1615
David Majnemera315bd82014-09-15 08:15:28 +00001616 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1617 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1618 if (Value *V = SimplifyAndOfICmps(ICILHS, ICIRHS))
1619 return V;
1620 if (Value *V = SimplifyAndOfICmps(ICIRHS, ICILHS))
1621 return V;
1622 }
1623 }
1624
Sanjay Patel9ad8fb62016-06-20 20:59:59 +00001625 // The compares may be hidden behind casts. Look through those and try the
1626 // same folds as above.
1627 auto *Cast0 = dyn_cast<CastInst>(Op0);
1628 auto *Cast1 = dyn_cast<CastInst>(Op1);
1629 if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
1630 Cast0->getSrcTy() == Cast1->getSrcTy()) {
1631 auto *Cmp0 = dyn_cast<ICmpInst>(Cast0->getOperand(0));
1632 auto *Cmp1 = dyn_cast<ICmpInst>(Cast1->getOperand(0));
1633 if (Cmp0 && Cmp1) {
1634 Instruction::CastOps CastOpc = Cast0->getOpcode();
1635 Type *ResultType = Cast0->getType();
1636 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp0, Cmp1)))
1637 return ConstantExpr::getCast(CastOpc, V, ResultType);
1638 if (auto *V = dyn_cast_or_null<Constant>(SimplifyAndOfICmps(Cmp1, Cmp0)))
1639 return ConstantExpr::getCast(CastOpc, V, ResultType);
1640 }
1641 }
1642
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001643 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001644 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1645 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001646 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001647
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001648 // And distributes over Or. Try some generic simplifications based on this.
1649 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001650 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001651 return V;
1652
1653 // And distributes over Xor. Try some generic simplifications based on this.
1654 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001655 Q, MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001656 return V;
1657
Duncan Sandsb0579e92010-11-10 13:00:08 +00001658 // If the operation is with the result of a select instruction, check whether
1659 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001660 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001661 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1662 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001663 return V;
1664
1665 // If the operation is with the result of a phi instruction, check whether
1666 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001667 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001668 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001669 MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001670 return V;
1671
Craig Topper9f008862014-04-15 04:59:12 +00001672 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00001673}
1674
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001675Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1676 return ::SimplifyAndInst(Op0, Op1, Q, RecursionLimit);
1677}
1678
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001679/// Commuted variants are assumed to be handled by calling this function again
1680/// with the parameters swapped.
1681static Value *simplifyOrOfICmpsWithSameOperands(ICmpInst *Op0, ICmpInst *Op1) {
1682 ICmpInst::Predicate Pred0, Pred1;
1683 Value *A ,*B;
Sanjay Patel53697752016-12-06 22:09:52 +00001684 if (!match(Op0, m_ICmp(Pred0, m_Value(A), m_Value(B))) ||
1685 !match(Op1, m_ICmp(Pred1, m_Specific(A), m_Specific(B))))
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001686 return nullptr;
1687
1688 // We have (icmp Pred0, A, B) | (icmp Pred1, A, B).
1689 // If Op1 is always implied true by Op0, then Op0 is a subset of Op1, and we
1690 // can eliminate Op0 from this 'or'.
1691 if (ICmpInst::isImpliedTrueByMatchingCmp(Pred0, Pred1))
1692 return Op1;
1693
1694 // Check for any combination of predicates that cover the entire range of
1695 // possibilities.
1696 if ((Pred0 == ICmpInst::getInversePredicate(Pred1)) ||
1697 (Pred0 == ICmpInst::ICMP_NE && ICmpInst::isTrueWhenEqual(Pred1)) ||
1698 (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGE) ||
1699 (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGE))
1700 return getTrue(Op0->getType());
1701
1702 return nullptr;
1703}
1704
1705/// Commuted variants are assumed to be handled by calling this function again
1706/// with the parameters swapped.
David Majnemera315bd82014-09-15 08:15:28 +00001707static Value *SimplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1) {
David Majnemer1af36e52014-12-06 10:51:40 +00001708 if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false))
1709 return X;
1710
Sanjay Pateld0ccdb42016-12-06 18:09:37 +00001711 if (Value *X = simplifyOrOfICmpsWithSameOperands(Op0, Op1))
1712 return X;
1713
Sanjay Patel220a8732016-09-28 14:27:21 +00001714 // (icmp (add V, C0), C1) | (icmp V, C0)
Sanjay Patelb2332e12016-09-20 14:36:14 +00001715 ICmpInst::Predicate Pred0, Pred1;
Sanjay Patel220a8732016-09-28 14:27:21 +00001716 const APInt *C0, *C1;
Sanjay Patelb2332e12016-09-20 14:36:14 +00001717 Value *V;
Sanjay Patel220a8732016-09-28 14:27:21 +00001718 if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
Sanjay Patelb2332e12016-09-20 14:36:14 +00001719 return nullptr;
David Majnemera315bd82014-09-15 08:15:28 +00001720
Sanjay Patel220a8732016-09-28 14:27:21 +00001721 if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
1722 return nullptr;
1723
1724 auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
1725 if (AddInst->getOperand(1) != Op1->getOperand(1))
David Majnemera315bd82014-09-15 08:15:28 +00001726 return nullptr;
1727
1728 Type *ITy = Op0->getType();
David Majnemera315bd82014-09-15 08:15:28 +00001729 bool isNSW = AddInst->hasNoSignedWrap();
1730 bool isNUW = AddInst->hasNoUnsignedWrap();
1731
Sanjay Patel220a8732016-09-28 14:27:21 +00001732 const APInt Delta = *C1 - *C0;
1733 if (C0->isStrictlyPositive()) {
David Majnemera315bd82014-09-15 08:15:28 +00001734 if (Delta == 2) {
1735 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
1736 return getTrue(ITy);
1737 if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1738 return getTrue(ITy);
1739 }
1740 if (Delta == 1) {
1741 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
1742 return getTrue(ITy);
1743 if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && isNSW)
1744 return getTrue(ITy);
1745 }
1746 }
Sanjay Patel220a8732016-09-28 14:27:21 +00001747 if (C0->getBoolValue() && isNUW) {
David Majnemera315bd82014-09-15 08:15:28 +00001748 if (Delta == 2)
1749 if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
1750 return getTrue(ITy);
1751 if (Delta == 1)
1752 if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
1753 return getTrue(ITy);
1754 }
1755
1756 return nullptr;
1757}
1758
Sanjay Patel472cc782016-01-11 22:14:42 +00001759/// Given operands for an Or, see if we can fold the result.
1760/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001761static Value *SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001762 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001763 if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
1764 return C;
Duncan Sands7e800d62010-11-14 11:23:23 +00001765
Chris Lattnera71e9d62009-11-10 00:55:12 +00001766 // X | undef -> -1
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001767 if (match(Op1, m_Undef()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001768 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001769
Chris Lattnera71e9d62009-11-10 00:55:12 +00001770 // X | X = X
Duncan Sands772749a2011-01-01 20:08:02 +00001771 if (Op0 == Op1)
Chris Lattnera71e9d62009-11-10 00:55:12 +00001772 return Op0;
1773
Duncan Sandsc89ac072010-11-17 18:52:15 +00001774 // X | 0 = X
1775 if (match(Op1, m_Zero()))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001776 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001777
Duncan Sandsc89ac072010-11-17 18:52:15 +00001778 // X | -1 = -1
1779 if (match(Op1, m_AllOnes()))
1780 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001781
Chris Lattnera71e9d62009-11-10 00:55:12 +00001782 // A | ~A = ~A | A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001783 if (match(Op0, m_Not(m_Specific(Op1))) ||
1784 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001785 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands7e800d62010-11-14 11:23:23 +00001786
Chris Lattnera71e9d62009-11-10 00:55:12 +00001787 // (A & ?) | A = A
Craig Topper9f008862014-04-15 04:59:12 +00001788 Value *A = nullptr, *B = nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001789 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001790 (A == Op1 || B == Op1))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001791 return Op1;
Duncan Sands7e800d62010-11-14 11:23:23 +00001792
Chris Lattnera71e9d62009-11-10 00:55:12 +00001793 // A | (A & ?) = A
1794 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands772749a2011-01-01 20:08:02 +00001795 (A == Op0 || B == Op0))
Chris Lattnera71e9d62009-11-10 00:55:12 +00001796 return Op0;
Duncan Sands7e800d62010-11-14 11:23:23 +00001797
Benjamin Kramer5b7a4e02011-02-20 15:20:01 +00001798 // ~(A & ?) | A = -1
1799 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1800 (A == Op1 || B == Op1))
1801 return Constant::getAllOnesValue(Op1->getType());
1802
1803 // A | ~(A & ?) = -1
1804 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1805 (A == Op0 || B == Op0))
1806 return Constant::getAllOnesValue(Op0->getType());
1807
Sanjay Patel08892252017-04-24 18:24:36 +00001808 // (A & ~B) | (A ^ B) -> (A ^ B)
1809 // (~B & A) | (A ^ B) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001810 // (A & ~B) | (B ^ A) -> (B ^ A)
1811 // (~B & A) | (B ^ A) -> (B ^ A)
1812 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
1813 (match(Op0, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1814 match(Op0, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001815 return Op1;
1816
1817 // Commute the 'or' operands.
1818 // (A ^ B) | (A & ~B) -> (A ^ B)
1819 // (A ^ B) | (~B & A) -> (A ^ B)
Craig Topper0b650d32017-04-25 17:01:32 +00001820 // (B ^ A) | (A & ~B) -> (B ^ A)
1821 // (B ^ A) | (~B & A) -> (B ^ A)
1822 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
1823 (match(Op1, m_c_And(m_Specific(A), m_Not(m_Specific(B)))) ||
1824 match(Op1, m_c_And(m_Not(m_Specific(A)), m_Specific(B)))))
Sanjay Patel08892252017-04-24 18:24:36 +00001825 return Op0;
1826
David Majnemera315bd82014-09-15 08:15:28 +00001827 if (auto *ICILHS = dyn_cast<ICmpInst>(Op0)) {
1828 if (auto *ICIRHS = dyn_cast<ICmpInst>(Op1)) {
1829 if (Value *V = SimplifyOrOfICmps(ICILHS, ICIRHS))
1830 return V;
1831 if (Value *V = SimplifyOrOfICmps(ICIRHS, ICILHS))
1832 return V;
1833 }
1834 }
1835
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001836 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001837 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1838 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001839 return V;
Benjamin Kramer8c35fb02010-09-10 22:39:55 +00001840
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001841 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001842 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1843 MaxRecurse))
Duncan Sandsee3ec6e2010-12-21 13:32:22 +00001844 return V;
1845
Duncan Sandsb0579e92010-11-10 13:00:08 +00001846 // If the operation is with the result of a select instruction, check whether
1847 // operating on either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001848 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001849 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sandsf64e6902010-12-21 09:09:15 +00001850 MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001851 return V;
1852
Nick Lewycky8561a492014-06-19 03:51:46 +00001853 // (A & C)|(B & D)
1854 Value *C = nullptr, *D = nullptr;
1855 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1856 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1857 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1858 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1859 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1860 // (A & C1)|(B & C2)
1861 // If we have: ((V + N) & C1) | (V & C2)
1862 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1863 // replace with V+N.
1864 Value *V1, *V2;
1865 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1866 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1867 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001868 if (V1 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001869 MaskedValueIsZero(V2, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001870 return A;
Chandler Carruth66b31302015-01-04 12:03:27 +00001871 if (V2 == B &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001872 MaskedValueIsZero(V1, C2->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001873 return A;
1874 }
1875 // Or commutes, try both ways.
1876 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1877 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1878 // Add commutes, try both ways.
Chandler Carruth66b31302015-01-04 12:03:27 +00001879 if (V1 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001880 MaskedValueIsZero(V2, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001881 return B;
Chandler Carruth66b31302015-01-04 12:03:27 +00001882 if (V2 == A &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001883 MaskedValueIsZero(V1, C1->getValue(), Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Nick Lewycky8561a492014-06-19 03:51:46 +00001884 return B;
1885 }
1886 }
1887 }
1888
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00001889 // If the operation is with the result of a phi instruction, check whether
1890 // operating on all incoming values of the phi always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00001891 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sandsb8cee002012-03-13 11:42:19 +00001892 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb0579e92010-11-10 13:00:08 +00001893 return V;
1894
Craig Topper9f008862014-04-15 04:59:12 +00001895 return nullptr;
Chris Lattnera71e9d62009-11-10 00:55:12 +00001896}
1897
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001898Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1899 return ::SimplifyOrInst(Op0, Op1, Q, RecursionLimit);
1900}
1901
Sanjay Patel472cc782016-01-11 22:14:42 +00001902/// Given operands for a Xor, see if we can fold the result.
1903/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001904static Value *SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00001905 unsigned MaxRecurse) {
Sanjay Patel8b5ad3f2017-04-01 19:05:11 +00001906 if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
1907 return C;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001908
1909 // A ^ undef -> undef
Duncan Sandsa29ea9a2011-02-01 09:06:20 +00001910 if (match(Op1, m_Undef()))
Duncan Sands019a4182010-12-15 11:02:22 +00001911 return Op1;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001912
1913 // A ^ 0 = A
1914 if (match(Op1, m_Zero()))
1915 return Op0;
1916
Eli Friedmanad3cfe72011-08-17 19:31:49 +00001917 // A ^ A = 0
1918 if (Op0 == Op1)
1919 return Constant::getNullValue(Op0->getType());
1920
Duncan Sandsc89ac072010-11-17 18:52:15 +00001921 // A ^ ~A = ~A ^ A = -1
Chris Lattner9e4aa022011-02-09 17:15:04 +00001922 if (match(Op0, m_Not(m_Specific(Op1))) ||
1923 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsc89ac072010-11-17 18:52:15 +00001924 return Constant::getAllOnesValue(Op0->getType());
1925
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001926 // Try some generic simplifications for associative operations.
Duncan Sandsb8cee002012-03-13 11:42:19 +00001927 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1928 MaxRecurse))
Duncan Sands6c7a52c2010-12-21 08:49:00 +00001929 return V;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001930
Duncan Sandsb238de02010-11-19 09:20:39 +00001931 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1932 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1933 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1934 // only if B and C are equal. If B and C are equal then (since we assume
1935 // that operands have already been simplified) "select(cond, B, C)" should
1936 // have been simplified to the common value of B and C already. Analysing
1937 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1938 // for threading over phi nodes.
Duncan Sandsc89ac072010-11-17 18:52:15 +00001939
Craig Topper9f008862014-04-15 04:59:12 +00001940 return nullptr;
Duncan Sandsc89ac072010-11-17 18:52:15 +00001941}
1942
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00001943Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
1944 return ::SimplifyXorInst(Op0, Op1, Q, RecursionLimit);
1945}
1946
1947
Chris Lattner229907c2011-07-18 04:54:35 +00001948static Type *GetCompareTy(Value *Op) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00001949 return CmpInst::makeCmpResultType(Op->getType());
1950}
1951
Sanjay Patel472cc782016-01-11 22:14:42 +00001952/// Rummage around inside V looking for something equivalent to the comparison
1953/// "LHS Pred RHS". Return such a value if found, otherwise return null.
1954/// Helper function for analyzing max/min idioms.
Duncan Sandsaf327282011-05-07 16:56:49 +00001955static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1956 Value *LHS, Value *RHS) {
1957 SelectInst *SI = dyn_cast<SelectInst>(V);
1958 if (!SI)
Craig Topper9f008862014-04-15 04:59:12 +00001959 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001960 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1961 if (!Cmp)
Craig Topper9f008862014-04-15 04:59:12 +00001962 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001963 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1964 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1965 return Cmp;
1966 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1967 LHS == CmpRHS && RHS == CmpLHS)
1968 return Cmp;
Craig Topper9f008862014-04-15 04:59:12 +00001969 return nullptr;
Duncan Sandsaf327282011-05-07 16:56:49 +00001970}
1971
Dan Gohman9631d902013-02-01 00:49:06 +00001972// A significant optimization not implemented here is assuming that alloca
1973// addresses are not equal to incoming argument values. They don't *alias*,
1974// as we say, but that doesn't mean they aren't equal, so we take a
1975// conservative approach.
1976//
1977// This is inspired in part by C++11 5.10p1:
1978// "Two pointers of the same type compare equal if and only if they are both
1979// null, both point to the same function, or both represent the same
1980// address."
1981//
1982// This is pretty permissive.
1983//
1984// It's also partly due to C11 6.5.9p6:
1985// "Two pointers compare equal if and only if both are null pointers, both are
1986// pointers to the same object (including a pointer to an object and a
1987// subobject at its beginning) or function, both are pointers to one past the
1988// last element of the same array object, or one is a pointer to one past the
1989// end of one array object and the other is a pointer to the start of a
NAKAMURA Takumi065fd352013-04-08 23:05:21 +00001990// different array object that happens to immediately follow the first array
Dan Gohman9631d902013-02-01 00:49:06 +00001991// object in the address space.)
1992//
1993// C11's version is more restrictive, however there's no reason why an argument
1994// couldn't be a one-past-the-end value for a stack object in the caller and be
1995// equal to the beginning of a stack object in the callee.
1996//
1997// If the C and C++ standards are ever made sufficiently restrictive in this
1998// area, it may be possible to update LLVM's semantics accordingly and reinstate
1999// this optimization.
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002000static Constant *
2001computePointerICmp(const DataLayout &DL, const TargetLibraryInfo *TLI,
2002 const DominatorTree *DT, CmpInst::Predicate Pred,
2003 const Instruction *CxtI, Value *LHS, Value *RHS) {
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002004 // First, skip past any trivial no-ops.
2005 LHS = LHS->stripPointerCasts();
2006 RHS = RHS->stripPointerCasts();
2007
2008 // A non-null pointer is not equal to a null pointer.
Sean Silva45835e72016-07-02 23:47:27 +00002009 if (llvm::isKnownNonNull(LHS) && isa<ConstantPointerNull>(RHS) &&
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002010 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
2011 return ConstantInt::get(GetCompareTy(LHS),
2012 !CmpInst::isTrueWhenEqual(Pred));
2013
Chandler Carruth8059c842012-03-25 21:28:14 +00002014 // We can only fold certain predicates on pointer comparisons.
2015 switch (Pred) {
2016 default:
Craig Topper9f008862014-04-15 04:59:12 +00002017 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002018
2019 // Equality comaprisons are easy to fold.
2020 case CmpInst::ICMP_EQ:
2021 case CmpInst::ICMP_NE:
2022 break;
2023
2024 // We can only handle unsigned relational comparisons because 'inbounds' on
2025 // a GEP only protects against unsigned wrapping.
2026 case CmpInst::ICMP_UGT:
2027 case CmpInst::ICMP_UGE:
2028 case CmpInst::ICMP_ULT:
2029 case CmpInst::ICMP_ULE:
2030 // However, we have to switch them to their signed variants to handle
2031 // negative indices from the base pointer.
2032 Pred = ICmpInst::getSignedPredicate(Pred);
2033 break;
2034 }
2035
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002036 // Strip off any constant offsets so that we can reason about them.
2037 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
2038 // here and compare base addresses like AliasAnalysis does, however there are
2039 // numerous hazards. AliasAnalysis and its utilities rely on special rules
2040 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
2041 // doesn't need to guarantee pointer inequality when it says NoAlias.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002042 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
2043 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
Chandler Carruth8059c842012-03-25 21:28:14 +00002044
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002045 // If LHS and RHS are related via constant offsets to the same base
2046 // value, we can replace it with an icmp which just compares the offsets.
2047 if (LHS == RHS)
2048 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
Chandler Carruth8059c842012-03-25 21:28:14 +00002049
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002050 // Various optimizations for (in)equality comparisons.
2051 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
2052 // Different non-empty allocations that exist at the same time have
2053 // different addresses (if the program can tell). Global variables always
2054 // exist, so they always exist during the lifetime of each other and all
2055 // allocas. Two different allocas usually have different addresses...
2056 //
2057 // However, if there's an @llvm.stackrestore dynamically in between two
2058 // allocas, they may have the same address. It's tempting to reduce the
2059 // scope of the problem by only looking at *static* allocas here. That would
2060 // cover the majority of allocas while significantly reducing the likelihood
2061 // of having an @llvm.stackrestore pop up in the middle. However, it's not
2062 // actually impossible for an @llvm.stackrestore to pop up in the middle of
2063 // an entry block. Also, if we have a block that's not attached to a
2064 // function, we can't tell if it's "static" under the current definition.
2065 // Theoretically, this problem could be fixed by creating a new kind of
2066 // instruction kind specifically for static allocas. Such a new instruction
2067 // could be required to be at the top of the entry block, thus preventing it
2068 // from being subject to a @llvm.stackrestore. Instcombine could even
2069 // convert regular allocas into these special allocas. It'd be nifty.
2070 // However, until then, this problem remains open.
2071 //
2072 // So, we'll assume that two non-empty allocas have different addresses
2073 // for now.
2074 //
2075 // With all that, if the offsets are within the bounds of their allocations
2076 // (and not one-past-the-end! so we can't use inbounds!), and their
2077 // allocations aren't the same, the pointers are not equal.
2078 //
2079 // Note that it's not necessary to check for LHS being a global variable
2080 // address, due to canonicalization and constant folding.
2081 if (isa<AllocaInst>(LHS) &&
2082 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002083 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
2084 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002085 uint64_t LHSSize, RHSSize;
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002086 if (LHSOffsetCI && RHSOffsetCI &&
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002087 getObjectSize(LHS, LHSSize, DL, TLI) &&
2088 getObjectSize(RHS, RHSSize, DL, TLI)) {
Benjamin Kramerc05aa952013-02-01 15:21:10 +00002089 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
2090 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002091 if (!LHSOffsetValue.isNegative() &&
2092 !RHSOffsetValue.isNegative() &&
2093 LHSOffsetValue.ult(LHSSize) &&
2094 RHSOffsetValue.ult(RHSSize)) {
2095 return ConstantInt::get(GetCompareTy(LHS),
2096 !CmpInst::isTrueWhenEqual(Pred));
2097 }
2098 }
2099
2100 // Repeat the above check but this time without depending on DataLayout
2101 // or being able to compute a precise size.
2102 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
2103 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
2104 LHSOffset->isNullValue() &&
2105 RHSOffset->isNullValue())
2106 return ConstantInt::get(GetCompareTy(LHS),
2107 !CmpInst::isTrueWhenEqual(Pred));
2108 }
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002109
2110 // Even if an non-inbounds GEP occurs along the path we can still optimize
2111 // equality comparisons concerning the result. We avoid walking the whole
2112 // chain again by starting where the last calls to
2113 // stripAndComputeConstantOffsets left off and accumulate the offsets.
Rafael Espindola37dc9e12014-02-21 00:06:31 +00002114 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
2115 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
Benjamin Kramer942dfe62013-09-23 14:16:38 +00002116 if (LHS == RHS)
2117 return ConstantExpr::getICmp(Pred,
2118 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
2119 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
Hal Finkelafcd8db2014-12-01 23:38:06 +00002120
2121 // If one side of the equality comparison must come from a noalias call
2122 // (meaning a system memory allocation function), and the other side must
2123 // come from a pointer that cannot overlap with dynamically-allocated
2124 // memory within the lifetime of the current function (allocas, byval
2125 // arguments, globals), then determine the comparison result here.
2126 SmallVector<Value *, 8> LHSUObjs, RHSUObjs;
2127 GetUnderlyingObjects(LHS, LHSUObjs, DL);
2128 GetUnderlyingObjects(RHS, RHSUObjs, DL);
2129
2130 // Is the set of underlying objects all noalias calls?
David Majnemer0a16c222016-08-11 21:15:00 +00002131 auto IsNAC = [](ArrayRef<Value *> Objects) {
2132 return all_of(Objects, isNoAliasCall);
Hal Finkelafcd8db2014-12-01 23:38:06 +00002133 };
2134
2135 // Is the set of underlying objects all things which must be disjoint from
Hal Finkelaa19baf2014-12-04 17:45:19 +00002136 // noalias calls. For allocas, we consider only static ones (dynamic
2137 // allocas might be transformed into calls to malloc not simultaneously
2138 // live with the compared-to allocation). For globals, we exclude symbols
2139 // that might be resolve lazily to symbols in another dynamically-loaded
2140 // library (and, thus, could be malloc'ed by the implementation).
David Majnemer0a16c222016-08-11 21:15:00 +00002141 auto IsAllocDisjoint = [](ArrayRef<Value *> Objects) {
2142 return all_of(Objects, [](Value *V) {
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002143 if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
2144 return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
2145 if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
2146 return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
Peter Collingbourne96efdd62016-06-14 21:01:22 +00002147 GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
Sanjay Patel34ea70a2016-01-11 22:24:35 +00002148 !GV->isThreadLocal();
2149 if (const Argument *A = dyn_cast<Argument>(V))
2150 return A->hasByValAttr();
2151 return false;
2152 });
Hal Finkelafcd8db2014-12-01 23:38:06 +00002153 };
2154
2155 if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
2156 (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
2157 return ConstantInt::get(GetCompareTy(LHS),
2158 !CmpInst::isTrueWhenEqual(Pred));
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002159
2160 // Fold comparisons for non-escaping pointer even if the allocation call
2161 // cannot be elided. We cannot fold malloc comparison to null. Also, the
2162 // dynamic allocation call could be either of the operands.
2163 Value *MI = nullptr;
Sean Silva45835e72016-07-02 23:47:27 +00002164 if (isAllocLikeFn(LHS, TLI) && llvm::isKnownNonNullAt(RHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002165 MI = LHS;
Sean Silva45835e72016-07-02 23:47:27 +00002166 else if (isAllocLikeFn(RHS, TLI) && llvm::isKnownNonNullAt(LHS, CxtI, DT))
Anna Thomas43d7e1c2016-05-03 14:58:21 +00002167 MI = RHS;
2168 // FIXME: We should also fold the compare when the pointer escapes, but the
2169 // compare dominates the pointer escape
2170 if (MI && !PointerMayBeCaptured(MI, true, true))
2171 return ConstantInt::get(GetCompareTy(LHS),
2172 CmpInst::isFalseWhenEqual(Pred));
Dan Gohmanb3e2d3a2013-02-01 00:11:13 +00002173 }
2174
2175 // Otherwise, fail.
Craig Topper9f008862014-04-15 04:59:12 +00002176 return nullptr;
Chandler Carruth8059c842012-03-25 21:28:14 +00002177}
Chris Lattner01990f02012-02-24 19:01:58 +00002178
Sanjay Pateldc65a272016-12-03 17:30:22 +00002179/// Fold an icmp when its operands have i1 scalar type.
2180static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002181 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002182 Type *ITy = GetCompareTy(LHS); // The return type.
2183 Type *OpTy = LHS->getType(); // The operand type.
2184 if (!OpTy->getScalarType()->isIntegerTy(1))
2185 return nullptr;
2186
2187 switch (Pred) {
2188 default:
2189 break;
2190 case ICmpInst::ICMP_EQ:
2191 // X == 1 -> X
2192 if (match(RHS, m_One()))
2193 return LHS;
2194 break;
2195 case ICmpInst::ICMP_NE:
2196 // X != 0 -> X
2197 if (match(RHS, m_Zero()))
2198 return LHS;
2199 break;
2200 case ICmpInst::ICMP_UGT:
2201 // X >u 0 -> X
2202 if (match(RHS, m_Zero()))
2203 return LHS;
2204 break;
2205 case ICmpInst::ICMP_UGE:
2206 // X >=u 1 -> X
2207 if (match(RHS, m_One()))
2208 return LHS;
2209 if (isImpliedCondition(RHS, LHS, Q.DL).getValueOr(false))
2210 return getTrue(ITy);
2211 break;
2212 case ICmpInst::ICMP_SGE:
2213 /// For signed comparison, the values for an i1 are 0 and -1
2214 /// respectively. This maps into a truth table of:
2215 /// LHS | RHS | LHS >=s RHS | LHS implies RHS
2216 /// 0 | 0 | 1 (0 >= 0) | 1
2217 /// 0 | 1 | 1 (0 >= -1) | 1
2218 /// 1 | 0 | 0 (-1 >= 0) | 0
2219 /// 1 | 1 | 1 (-1 >= -1) | 1
2220 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2221 return getTrue(ITy);
2222 break;
2223 case ICmpInst::ICMP_SLT:
2224 // X <s 0 -> X
2225 if (match(RHS, m_Zero()))
2226 return LHS;
2227 break;
2228 case ICmpInst::ICMP_SLE:
2229 // X <=s -1 -> X
2230 if (match(RHS, m_One()))
2231 return LHS;
2232 break;
2233 case ICmpInst::ICMP_ULE:
2234 if (isImpliedCondition(LHS, RHS, Q.DL).getValueOr(false))
2235 return getTrue(ITy);
2236 break;
2237 }
2238
2239 return nullptr;
2240}
2241
2242/// Try hard to fold icmp with zero RHS because this is a common case.
2243static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002244 Value *RHS, const SimplifyQuery &Q) {
Sanjay Pateldc65a272016-12-03 17:30:22 +00002245 if (!match(RHS, m_Zero()))
2246 return nullptr;
2247
2248 Type *ITy = GetCompareTy(LHS); // The return type.
2249 bool LHSKnownNonNegative, LHSKnownNegative;
2250 switch (Pred) {
2251 default:
2252 llvm_unreachable("Unknown ICmp predicate!");
2253 case ICmpInst::ICMP_ULT:
2254 return getFalse(ITy);
2255 case ICmpInst::ICMP_UGE:
2256 return getTrue(ITy);
2257 case ICmpInst::ICMP_EQ:
2258 case ICmpInst::ICMP_ULE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002259 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002260 return getFalse(ITy);
2261 break;
2262 case ICmpInst::ICMP_NE:
2263 case ICmpInst::ICMP_UGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002264 if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002265 return getTrue(ITy);
2266 break;
2267 case ICmpInst::ICMP_SLT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002268 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2269 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002270 if (LHSKnownNegative)
2271 return getTrue(ITy);
2272 if (LHSKnownNonNegative)
2273 return getFalse(ITy);
2274 break;
2275 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002276 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2277 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002278 if (LHSKnownNegative)
2279 return getTrue(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002280 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002281 return getFalse(ITy);
2282 break;
2283 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002284 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2285 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002286 if (LHSKnownNegative)
2287 return getFalse(ITy);
2288 if (LHSKnownNonNegative)
2289 return getTrue(ITy);
2290 break;
2291 case ICmpInst::ICMP_SGT:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002292 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0, Q.AC,
2293 Q.CxtI, Q.DT);
Sanjay Pateldc65a272016-12-03 17:30:22 +00002294 if (LHSKnownNegative)
2295 return getFalse(ITy);
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002296 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
Sanjay Pateldc65a272016-12-03 17:30:22 +00002297 return getTrue(ITy);
2298 break;
2299 }
2300
2301 return nullptr;
2302}
2303
Sanjay Patelbe332132017-01-23 18:22:26 +00002304/// Many binary operators with a constant operand have an easy-to-compute
2305/// range of outputs. This can be used to fold a comparison to always true or
2306/// always false.
2307static void setLimitsForBinOp(BinaryOperator &BO, APInt &Lower, APInt &Upper) {
2308 unsigned Width = Lower.getBitWidth();
2309 const APInt *C;
2310 switch (BO.getOpcode()) {
2311 case Instruction::Add:
Sanjay Patel56227252017-01-24 17:03:24 +00002312 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2313 // FIXME: If we have both nuw and nsw, we should reduce the range further.
2314 if (BO.hasNoUnsignedWrap()) {
2315 // 'add nuw x, C' produces [C, UINT_MAX].
2316 Lower = *C;
2317 } else if (BO.hasNoSignedWrap()) {
2318 if (C->isNegative()) {
2319 // 'add nsw x, -C' produces [SINT_MIN, SINT_MAX - C].
2320 Lower = APInt::getSignedMinValue(Width);
2321 Upper = APInt::getSignedMaxValue(Width) + *C + 1;
2322 } else {
2323 // 'add nsw x, +C' produces [SINT_MIN + C, SINT_MAX].
2324 Lower = APInt::getSignedMinValue(Width) + *C;
2325 Upper = APInt::getSignedMaxValue(Width) + 1;
2326 }
2327 }
2328 }
Sanjay Patelbe332132017-01-23 18:22:26 +00002329 break;
2330
2331 case Instruction::And:
2332 if (match(BO.getOperand(1), m_APInt(C)))
2333 // 'and x, C' produces [0, C].
2334 Upper = *C + 1;
2335 break;
2336
2337 case Instruction::Or:
2338 if (match(BO.getOperand(1), m_APInt(C)))
2339 // 'or x, C' produces [C, UINT_MAX].
2340 Lower = *C;
2341 break;
2342
2343 case Instruction::AShr:
2344 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2345 // 'ashr x, C' produces [INT_MIN >> C, INT_MAX >> C].
2346 Lower = APInt::getSignedMinValue(Width).ashr(*C);
2347 Upper = APInt::getSignedMaxValue(Width).ashr(*C) + 1;
2348 } else if (match(BO.getOperand(0), m_APInt(C))) {
2349 unsigned ShiftAmount = Width - 1;
2350 if (*C != 0 && BO.isExact())
2351 ShiftAmount = C->countTrailingZeros();
2352 if (C->isNegative()) {
2353 // 'ashr C, x' produces [C, C >> (Width-1)]
2354 Lower = *C;
2355 Upper = C->ashr(ShiftAmount) + 1;
2356 } else {
2357 // 'ashr C, x' produces [C >> (Width-1), C]
2358 Lower = C->ashr(ShiftAmount);
2359 Upper = *C + 1;
2360 }
2361 }
2362 break;
2363
2364 case Instruction::LShr:
2365 if (match(BO.getOperand(1), m_APInt(C)) && C->ult(Width)) {
2366 // 'lshr x, C' produces [0, UINT_MAX >> C].
2367 Upper = APInt::getAllOnesValue(Width).lshr(*C) + 1;
2368 } else if (match(BO.getOperand(0), m_APInt(C))) {
2369 // 'lshr C, x' produces [C >> (Width-1), C].
2370 unsigned ShiftAmount = Width - 1;
2371 if (*C != 0 && BO.isExact())
2372 ShiftAmount = C->countTrailingZeros();
2373 Lower = C->lshr(ShiftAmount);
2374 Upper = *C + 1;
2375 }
2376 break;
2377
2378 case Instruction::Shl:
2379 if (match(BO.getOperand(0), m_APInt(C))) {
2380 if (BO.hasNoUnsignedWrap()) {
2381 // 'shl nuw C, x' produces [C, C << CLZ(C)]
2382 Lower = *C;
2383 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2384 } else if (BO.hasNoSignedWrap()) { // TODO: What if both nuw+nsw?
2385 if (C->isNegative()) {
2386 // 'shl nsw C, x' produces [C << CLO(C)-1, C]
2387 unsigned ShiftAmount = C->countLeadingOnes() - 1;
2388 Lower = C->shl(ShiftAmount);
2389 Upper = *C + 1;
2390 } else {
2391 // 'shl nsw C, x' produces [C, C << CLZ(C)-1]
2392 unsigned ShiftAmount = C->countLeadingZeros() - 1;
2393 Lower = *C;
2394 Upper = C->shl(ShiftAmount) + 1;
2395 }
2396 }
2397 }
2398 break;
2399
2400 case Instruction::SDiv:
2401 if (match(BO.getOperand(1), m_APInt(C))) {
2402 APInt IntMin = APInt::getSignedMinValue(Width);
2403 APInt IntMax = APInt::getSignedMaxValue(Width);
2404 if (C->isAllOnesValue()) {
2405 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2406 // where C != -1 and C != 0 and C != 1
2407 Lower = IntMin + 1;
2408 Upper = IntMax + 1;
2409 } else if (C->countLeadingZeros() < Width - 1) {
2410 // 'sdiv x, C' produces [INT_MIN / C, INT_MAX / C]
2411 // where C != -1 and C != 0 and C != 1
2412 Lower = IntMin.sdiv(*C);
2413 Upper = IntMax.sdiv(*C);
2414 if (Lower.sgt(Upper))
2415 std::swap(Lower, Upper);
2416 Upper = Upper + 1;
2417 assert(Upper != Lower && "Upper part of range has wrapped!");
2418 }
2419 } else if (match(BO.getOperand(0), m_APInt(C))) {
2420 if (C->isMinSignedValue()) {
2421 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2422 Lower = *C;
2423 Upper = Lower.lshr(1) + 1;
2424 } else {
2425 // 'sdiv C, x' produces [-|C|, |C|].
2426 Upper = C->abs() + 1;
2427 Lower = (-Upper) + 1;
2428 }
2429 }
2430 break;
2431
2432 case Instruction::UDiv:
2433 if (match(BO.getOperand(1), m_APInt(C)) && *C != 0) {
2434 // 'udiv x, C' produces [0, UINT_MAX / C].
2435 Upper = APInt::getMaxValue(Width).udiv(*C) + 1;
2436 } else if (match(BO.getOperand(0), m_APInt(C))) {
2437 // 'udiv C, x' produces [0, C].
2438 Upper = *C + 1;
2439 }
2440 break;
2441
2442 case Instruction::SRem:
2443 if (match(BO.getOperand(1), m_APInt(C))) {
2444 // 'srem x, C' produces (-|C|, |C|).
2445 Upper = C->abs();
2446 Lower = (-Upper) + 1;
2447 }
2448 break;
2449
2450 case Instruction::URem:
2451 if (match(BO.getOperand(1), m_APInt(C)))
2452 // 'urem x, C' produces [0, C).
2453 Upper = *C;
2454 break;
2455
2456 default:
2457 break;
2458 }
2459}
2460
Sanjay Patel67bde282016-08-22 23:12:02 +00002461static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
2462 Value *RHS) {
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002463 const APInt *C;
2464 if (!match(RHS, m_APInt(C)))
Sanjay Patel67bde282016-08-22 23:12:02 +00002465 return nullptr;
2466
2467 // Rule out tautological comparisons (eg., ult 0 or uge 0).
Sanjoy Das1f7b8132016-10-02 00:09:57 +00002468 ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
Sanjay Patel67bde282016-08-22 23:12:02 +00002469 if (RHS_CR.isEmptySet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002470 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002471 if (RHS_CR.isFullSet())
Sanjay Patel200e3cb2016-08-23 17:30:56 +00002472 return ConstantInt::getTrue(GetCompareTy(RHS));
2473
Sanjay Patelbe332132017-01-23 18:22:26 +00002474 // Find the range of possible values for binary operators.
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002475 unsigned Width = C->getBitWidth();
Sanjay Patel67bde282016-08-22 23:12:02 +00002476 APInt Lower = APInt(Width, 0);
2477 APInt Upper = APInt(Width, 0);
Sanjay Patelbe332132017-01-23 18:22:26 +00002478 if (auto *BO = dyn_cast<BinaryOperator>(LHS))
2479 setLimitsForBinOp(*BO, Lower, Upper);
Sanjay Patel67bde282016-08-22 23:12:02 +00002480
2481 ConstantRange LHS_CR =
2482 Lower != Upper ? ConstantRange(Lower, Upper) : ConstantRange(Width, true);
2483
2484 if (auto *I = dyn_cast<Instruction>(LHS))
2485 if (auto *Ranges = I->getMetadata(LLVMContext::MD_range))
2486 LHS_CR = LHS_CR.intersectWith(getConstantRangeFromMetadata(*Ranges));
2487
2488 if (!LHS_CR.isFullSet()) {
2489 if (RHS_CR.contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002490 return ConstantInt::getTrue(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002491 if (RHS_CR.inverse().contains(LHS_CR))
Sanjay Patel6946e2a2016-08-23 18:00:51 +00002492 return ConstantInt::getFalse(GetCompareTy(RHS));
Sanjay Patel67bde282016-08-22 23:12:02 +00002493 }
2494
2495 return nullptr;
2496}
2497
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002498static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002499 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002500 unsigned MaxRecurse) {
2501 Type *ITy = GetCompareTy(LHS); // The return type.
2502
2503 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2504 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2505 if (MaxRecurse && (LBO || RBO)) {
2506 // Analyze the case when either LHS or RHS is an add instruction.
2507 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2508 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2509 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2510 if (LBO && LBO->getOpcode() == Instruction::Add) {
2511 A = LBO->getOperand(0);
2512 B = LBO->getOperand(1);
2513 NoLHSWrapProblem =
2514 ICmpInst::isEquality(Pred) ||
2515 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2516 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2517 }
2518 if (RBO && RBO->getOpcode() == Instruction::Add) {
2519 C = RBO->getOperand(0);
2520 D = RBO->getOperand(1);
2521 NoRHSWrapProblem =
2522 ICmpInst::isEquality(Pred) ||
2523 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2524 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2525 }
2526
2527 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2528 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2529 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2530 Constant::getNullValue(RHS->getType()), Q,
2531 MaxRecurse - 1))
2532 return V;
2533
2534 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2535 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2536 if (Value *V =
2537 SimplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
2538 C == LHS ? D : C, Q, MaxRecurse - 1))
2539 return V;
2540
2541 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2542 if (A && C && (A == C || A == D || B == C || B == D) && NoLHSWrapProblem &&
2543 NoRHSWrapProblem) {
2544 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2545 Value *Y, *Z;
2546 if (A == C) {
2547 // C + B == C + D -> B == D
2548 Y = B;
2549 Z = D;
2550 } else if (A == D) {
2551 // D + B == C + D -> B == C
2552 Y = B;
2553 Z = C;
2554 } else if (B == C) {
2555 // A + C == C + D -> A == D
2556 Y = A;
2557 Z = D;
2558 } else {
2559 assert(B == D);
2560 // A + D == C + D -> A == C
2561 Y = A;
2562 Z = C;
2563 }
2564 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
2565 return V;
2566 }
2567 }
2568
2569 {
2570 Value *Y = nullptr;
2571 // icmp pred (or X, Y), X
2572 if (LBO && match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
2573 if (Pred == ICmpInst::ICMP_ULT)
2574 return getFalse(ITy);
2575 if (Pred == ICmpInst::ICMP_UGE)
2576 return getTrue(ITy);
2577
2578 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
2579 bool RHSKnownNonNegative, RHSKnownNegative;
2580 bool YKnownNonNegative, YKnownNegative;
2581 ComputeSignBit(RHS, RHSKnownNonNegative, RHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002582 Q.AC, Q.CxtI, Q.DT);
2583 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002584 Q.CxtI, Q.DT);
2585 if (RHSKnownNonNegative && YKnownNegative)
2586 return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
2587 if (RHSKnownNegative || YKnownNonNegative)
2588 return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
2589 }
2590 }
2591 // icmp pred X, (or X, Y)
2592 if (RBO && match(RBO, m_c_Or(m_Value(Y), m_Specific(LHS)))) {
2593 if (Pred == ICmpInst::ICMP_ULE)
2594 return getTrue(ITy);
2595 if (Pred == ICmpInst::ICMP_UGT)
2596 return getFalse(ITy);
2597
2598 if (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE) {
2599 bool LHSKnownNonNegative, LHSKnownNegative;
2600 bool YKnownNonNegative, YKnownNegative;
2601 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL, 0,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002602 Q.AC, Q.CxtI, Q.DT);
2603 ComputeSignBit(Y, YKnownNonNegative, YKnownNegative, Q.DL, 0, Q.AC,
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002604 Q.CxtI, Q.DT);
2605 if (LHSKnownNonNegative && YKnownNegative)
2606 return Pred == ICmpInst::ICMP_SGT ? getTrue(ITy) : getFalse(ITy);
2607 if (LHSKnownNegative || YKnownNonNegative)
2608 return Pred == ICmpInst::ICMP_SGT ? getFalse(ITy) : getTrue(ITy);
2609 }
2610 }
2611 }
2612
2613 // icmp pred (and X, Y), X
2614 if (LBO && match(LBO, m_CombineOr(m_And(m_Value(), m_Specific(RHS)),
2615 m_And(m_Specific(RHS), m_Value())))) {
2616 if (Pred == ICmpInst::ICMP_UGT)
2617 return getFalse(ITy);
2618 if (Pred == ICmpInst::ICMP_ULE)
2619 return getTrue(ITy);
2620 }
2621 // icmp pred X, (and X, Y)
2622 if (RBO && match(RBO, m_CombineOr(m_And(m_Value(), m_Specific(LHS)),
2623 m_And(m_Specific(LHS), m_Value())))) {
2624 if (Pred == ICmpInst::ICMP_UGE)
2625 return getTrue(ITy);
2626 if (Pred == ICmpInst::ICMP_ULT)
2627 return getFalse(ITy);
2628 }
2629
2630 // 0 - (zext X) pred C
2631 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2632 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2633 if (RHSC->getValue().isStrictlyPositive()) {
2634 if (Pred == ICmpInst::ICMP_SLT)
2635 return ConstantInt::getTrue(RHSC->getContext());
2636 if (Pred == ICmpInst::ICMP_SGE)
2637 return ConstantInt::getFalse(RHSC->getContext());
2638 if (Pred == ICmpInst::ICMP_EQ)
2639 return ConstantInt::getFalse(RHSC->getContext());
2640 if (Pred == ICmpInst::ICMP_NE)
2641 return ConstantInt::getTrue(RHSC->getContext());
2642 }
2643 if (RHSC->getValue().isNonNegative()) {
2644 if (Pred == ICmpInst::ICMP_SLE)
2645 return ConstantInt::getTrue(RHSC->getContext());
2646 if (Pred == ICmpInst::ICMP_SGT)
2647 return ConstantInt::getFalse(RHSC->getContext());
2648 }
2649 }
2650 }
2651
2652 // icmp pred (urem X, Y), Y
2653 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2654 bool KnownNonNegative, KnownNegative;
2655 switch (Pred) {
2656 default:
2657 break;
2658 case ICmpInst::ICMP_SGT:
2659 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002660 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2661 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002662 if (!KnownNonNegative)
2663 break;
2664 LLVM_FALLTHROUGH;
2665 case ICmpInst::ICMP_EQ:
2666 case ICmpInst::ICMP_UGT:
2667 case ICmpInst::ICMP_UGE:
2668 return getFalse(ITy);
2669 case ICmpInst::ICMP_SLT:
2670 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002671 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2672 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002673 if (!KnownNonNegative)
2674 break;
2675 LLVM_FALLTHROUGH;
2676 case ICmpInst::ICMP_NE:
2677 case ICmpInst::ICMP_ULT:
2678 case ICmpInst::ICMP_ULE:
2679 return getTrue(ITy);
2680 }
2681 }
2682
2683 // icmp pred X, (urem Y, X)
2684 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2685 bool KnownNonNegative, KnownNegative;
2686 switch (Pred) {
2687 default:
2688 break;
2689 case ICmpInst::ICMP_SGT:
2690 case ICmpInst::ICMP_SGE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002691 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2692 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002693 if (!KnownNonNegative)
2694 break;
2695 LLVM_FALLTHROUGH;
2696 case ICmpInst::ICMP_NE:
2697 case ICmpInst::ICMP_UGT:
2698 case ICmpInst::ICMP_UGE:
2699 return getTrue(ITy);
2700 case ICmpInst::ICMP_SLT:
2701 case ICmpInst::ICMP_SLE:
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002702 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL, 0, Q.AC,
2703 Q.CxtI, Q.DT);
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002704 if (!KnownNonNegative)
2705 break;
2706 LLVM_FALLTHROUGH;
2707 case ICmpInst::ICMP_EQ:
2708 case ICmpInst::ICMP_ULT:
2709 case ICmpInst::ICMP_ULE:
2710 return getFalse(ITy);
2711 }
2712 }
2713
2714 // x >> y <=u x
2715 // x udiv y <=u x.
2716 if (LBO && (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
2717 match(LBO, m_UDiv(m_Specific(RHS), m_Value())))) {
2718 // icmp pred (X op Y), X
2719 if (Pred == ICmpInst::ICMP_UGT)
2720 return getFalse(ITy);
2721 if (Pred == ICmpInst::ICMP_ULE)
2722 return getTrue(ITy);
2723 }
2724
2725 // x >=u x >> y
2726 // x >=u x udiv y.
2727 if (RBO && (match(RBO, m_LShr(m_Specific(LHS), m_Value())) ||
2728 match(RBO, m_UDiv(m_Specific(LHS), m_Value())))) {
2729 // icmp pred X, (X op Y)
2730 if (Pred == ICmpInst::ICMP_ULT)
2731 return getFalse(ITy);
2732 if (Pred == ICmpInst::ICMP_UGE)
2733 return getTrue(ITy);
2734 }
2735
2736 // handle:
2737 // CI2 << X == CI
2738 // CI2 << X != CI
2739 //
2740 // where CI2 is a power of 2 and CI isn't
2741 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2742 const APInt *CI2Val, *CIVal = &CI->getValue();
2743 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2744 CI2Val->isPowerOf2()) {
2745 if (!CIVal->isPowerOf2()) {
2746 // CI2 << X can equal zero in some circumstances,
2747 // this simplification is unsafe if CI is zero.
2748 //
2749 // We know it is safe if:
2750 // - The shift is nsw, we can't shift out the one bit.
2751 // - The shift is nuw, we can't shift out the one bit.
2752 // - CI2 is one
2753 // - CI isn't zero
2754 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2755 *CI2Val == 1 || !CI->isZero()) {
2756 if (Pred == ICmpInst::ICMP_EQ)
2757 return ConstantInt::getFalse(RHS->getContext());
2758 if (Pred == ICmpInst::ICMP_NE)
2759 return ConstantInt::getTrue(RHS->getContext());
2760 }
2761 }
Craig Topperbcfd2d12017-04-20 16:56:25 +00002762 if (CIVal->isSignMask() && *CI2Val == 1) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002763 if (Pred == ICmpInst::ICMP_UGT)
2764 return ConstantInt::getFalse(RHS->getContext());
2765 if (Pred == ICmpInst::ICMP_ULE)
2766 return ConstantInt::getTrue(RHS->getContext());
2767 }
2768 }
2769 }
2770
2771 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2772 LBO->getOperand(1) == RBO->getOperand(1)) {
2773 switch (LBO->getOpcode()) {
2774 default:
2775 break;
2776 case Instruction::UDiv:
2777 case Instruction::LShr:
2778 if (ICmpInst::isSigned(Pred))
2779 break;
2780 LLVM_FALLTHROUGH;
2781 case Instruction::SDiv:
2782 case Instruction::AShr:
2783 if (!LBO->isExact() || !RBO->isExact())
2784 break;
2785 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2786 RBO->getOperand(0), Q, MaxRecurse - 1))
2787 return V;
2788 break;
2789 case Instruction::Shl: {
2790 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2791 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2792 if (!NUW && !NSW)
2793 break;
2794 if (!NSW && ICmpInst::isSigned(Pred))
2795 break;
2796 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2797 RBO->getOperand(0), Q, MaxRecurse - 1))
2798 return V;
2799 break;
2800 }
2801 }
2802 }
2803 return nullptr;
2804}
2805
Sanjay Patel35289c62016-12-10 17:40:47 +00002806/// Simplify integer comparisons where at least one operand of the compare
2807/// matches an integer min/max idiom.
2808static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00002809 Value *RHS, const SimplifyQuery &Q,
Sanjay Patel35289c62016-12-10 17:40:47 +00002810 unsigned MaxRecurse) {
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00002811 Type *ITy = GetCompareTy(LHS); // The return type.
2812 Value *A, *B;
2813 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2814 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2815
2816 // Signed variants on "max(a,b)>=a -> true".
2817 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2818 if (A != RHS)
2819 std::swap(A, B); // smax(A, B) pred A.
2820 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2821 // We analyze this as smax(A, B) pred A.
2822 P = Pred;
2823 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2824 (A == LHS || B == LHS)) {
2825 if (A != LHS)
2826 std::swap(A, B); // A pred smax(A, B).
2827 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2828 // We analyze this as smax(A, B) swapped-pred A.
2829 P = CmpInst::getSwappedPredicate(Pred);
2830 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2831 (A == RHS || B == RHS)) {
2832 if (A != RHS)
2833 std::swap(A, B); // smin(A, B) pred A.
2834 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2835 // We analyze this as smax(-A, -B) swapped-pred -A.
2836 // Note that we do not need to actually form -A or -B thanks to EqP.
2837 P = CmpInst::getSwappedPredicate(Pred);
2838 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2839 (A == LHS || B == LHS)) {
2840 if (A != LHS)
2841 std::swap(A, B); // A pred smin(A, B).
2842 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2843 // We analyze this as smax(-A, -B) pred -A.
2844 // Note that we do not need to actually form -A or -B thanks to EqP.
2845 P = Pred;
2846 }
2847 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2848 // Cases correspond to "max(A, B) p A".
2849 switch (P) {
2850 default:
2851 break;
2852 case CmpInst::ICMP_EQ:
2853 case CmpInst::ICMP_SLE:
2854 // Equivalent to "A EqP B". This may be the same as the condition tested
2855 // in the max/min; if so, we can just return that.
2856 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2857 return V;
2858 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2859 return V;
2860 // Otherwise, see if "A EqP B" simplifies.
2861 if (MaxRecurse)
2862 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2863 return V;
2864 break;
2865 case CmpInst::ICMP_NE:
2866 case CmpInst::ICMP_SGT: {
2867 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2868 // Equivalent to "A InvEqP B". This may be the same as the condition
2869 // tested in the max/min; if so, we can just return that.
2870 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2871 return V;
2872 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2873 return V;
2874 // Otherwise, see if "A InvEqP B" simplifies.
2875 if (MaxRecurse)
2876 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2877 return V;
2878 break;
2879 }
2880 case CmpInst::ICMP_SGE:
2881 // Always true.
2882 return getTrue(ITy);
2883 case CmpInst::ICMP_SLT:
2884 // Always false.
2885 return getFalse(ITy);
2886 }
2887 }
2888
2889 // Unsigned variants on "max(a,b)>=a -> true".
2890 P = CmpInst::BAD_ICMP_PREDICATE;
2891 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2892 if (A != RHS)
2893 std::swap(A, B); // umax(A, B) pred A.
2894 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2895 // We analyze this as umax(A, B) pred A.
2896 P = Pred;
2897 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2898 (A == LHS || B == LHS)) {
2899 if (A != LHS)
2900 std::swap(A, B); // A pred umax(A, B).
2901 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2902 // We analyze this as umax(A, B) swapped-pred A.
2903 P = CmpInst::getSwappedPredicate(Pred);
2904 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2905 (A == RHS || B == RHS)) {
2906 if (A != RHS)
2907 std::swap(A, B); // umin(A, B) pred A.
2908 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2909 // We analyze this as umax(-A, -B) swapped-pred -A.
2910 // Note that we do not need to actually form -A or -B thanks to EqP.
2911 P = CmpInst::getSwappedPredicate(Pred);
2912 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2913 (A == LHS || B == LHS)) {
2914 if (A != LHS)
2915 std::swap(A, B); // A pred umin(A, B).
2916 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2917 // We analyze this as umax(-A, -B) pred -A.
2918 // Note that we do not need to actually form -A or -B thanks to EqP.
2919 P = Pred;
2920 }
2921 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2922 // Cases correspond to "max(A, B) p A".
2923 switch (P) {
2924 default:
2925 break;
2926 case CmpInst::ICMP_EQ:
2927 case CmpInst::ICMP_ULE:
2928 // Equivalent to "A EqP B". This may be the same as the condition tested
2929 // in the max/min; if so, we can just return that.
2930 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2931 return V;
2932 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2933 return V;
2934 // Otherwise, see if "A EqP B" simplifies.
2935 if (MaxRecurse)
2936 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
2937 return V;
2938 break;
2939 case CmpInst::ICMP_NE:
2940 case CmpInst::ICMP_UGT: {
2941 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2942 // Equivalent to "A InvEqP B". This may be the same as the condition
2943 // tested in the max/min; if so, we can just return that.
2944 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2945 return V;
2946 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2947 return V;
2948 // Otherwise, see if "A InvEqP B" simplifies.
2949 if (MaxRecurse)
2950 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
2951 return V;
2952 break;
2953 }
2954 case CmpInst::ICMP_UGE:
2955 // Always true.
2956 return getTrue(ITy);
2957 case CmpInst::ICMP_ULT:
2958 // Always false.
2959 return getFalse(ITy);
2960 }
2961 }
2962
2963 // Variants on "max(x,y) >= min(x,z)".
2964 Value *C, *D;
2965 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2966 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2967 (A == C || A == D || B == C || B == D)) {
2968 // max(x, ?) pred min(x, ?).
2969 if (Pred == CmpInst::ICMP_SGE)
2970 // Always true.
2971 return getTrue(ITy);
2972 if (Pred == CmpInst::ICMP_SLT)
2973 // Always false.
2974 return getFalse(ITy);
2975 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2976 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2977 (A == C || A == D || B == C || B == D)) {
2978 // min(x, ?) pred max(x, ?).
2979 if (Pred == CmpInst::ICMP_SLE)
2980 // Always true.
2981 return getTrue(ITy);
2982 if (Pred == CmpInst::ICMP_SGT)
2983 // Always false.
2984 return getFalse(ITy);
2985 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2986 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2987 (A == C || A == D || B == C || B == D)) {
2988 // max(x, ?) pred min(x, ?).
2989 if (Pred == CmpInst::ICMP_UGE)
2990 // Always true.
2991 return getTrue(ITy);
2992 if (Pred == CmpInst::ICMP_ULT)
2993 // Always false.
2994 return getFalse(ITy);
2995 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2996 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2997 (A == C || A == D || B == C || B == D)) {
2998 // min(x, ?) pred max(x, ?).
2999 if (Pred == CmpInst::ICMP_ULE)
3000 // Always true.
3001 return getTrue(ITy);
3002 if (Pred == CmpInst::ICMP_UGT)
3003 // Always false.
3004 return getFalse(ITy);
3005 }
3006
3007 return nullptr;
3008}
3009
Sanjay Patel472cc782016-01-11 22:14:42 +00003010/// Given operands for an ICmpInst, see if we can fold the result.
3011/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003012static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003013 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattner084a1b52009-11-09 22:57:59 +00003014 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003015 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands7e800d62010-11-14 11:23:23 +00003016
Chris Lattnera71e9d62009-11-10 00:55:12 +00003017 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnercdfb80d2009-11-09 23:06:58 +00003018 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003019 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Chris Lattnera71e9d62009-11-10 00:55:12 +00003020
3021 // If we have a constant, make sure it is on the RHS.
3022 std::swap(LHS, RHS);
3023 Pred = CmpInst::getSwappedPredicate(Pred);
3024 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003025
Chris Lattner229907c2011-07-18 04:54:35 +00003026 Type *ITy = GetCompareTy(LHS); // The return type.
Duncan Sands7e800d62010-11-14 11:23:23 +00003027
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003028 // icmp X, X -> true/false
Chris Lattner3afc0722010-03-03 19:46:03 +00003029 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
3030 // because X could be 0.
Duncan Sands772749a2011-01-01 20:08:02 +00003031 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003032 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands7e800d62010-11-14 11:23:23 +00003033
Sanjay Pateldc65a272016-12-03 17:30:22 +00003034 if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
3035 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003036
Sanjay Pateldc65a272016-12-03 17:30:22 +00003037 if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
3038 return V;
Duncan Sandsd3951082011-01-25 09:38:29 +00003039
Sanjay Patel67bde282016-08-22 23:12:02 +00003040 if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS))
3041 return V;
Duncan Sands8d25a7c2011-01-13 08:56:29 +00003042
Chen Li7452d952015-09-26 03:26:47 +00003043 // If both operands have range metadata, use the metadata
3044 // to simplify the comparison.
3045 if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
Craig Topper0c198612017-04-10 19:37:10 +00003046 auto RHS_Instr = cast<Instruction>(RHS);
3047 auto LHS_Instr = cast<Instruction>(LHS);
Chen Li7452d952015-09-26 03:26:47 +00003048
3049 if (RHS_Instr->getMetadata(LLVMContext::MD_range) &&
3050 LHS_Instr->getMetadata(LLVMContext::MD_range)) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00003051 auto RHS_CR = getConstantRangeFromMetadata(
3052 *RHS_Instr->getMetadata(LLVMContext::MD_range));
3053 auto LHS_CR = getConstantRangeFromMetadata(
3054 *LHS_Instr->getMetadata(LLVMContext::MD_range));
Chen Li7452d952015-09-26 03:26:47 +00003055
3056 auto Satisfied_CR = ConstantRange::makeSatisfyingICmpRegion(Pred, RHS_CR);
3057 if (Satisfied_CR.contains(LHS_CR))
3058 return ConstantInt::getTrue(RHS->getContext());
3059
3060 auto InversedSatisfied_CR = ConstantRange::makeSatisfyingICmpRegion(
3061 CmpInst::getInversePredicate(Pred), RHS_CR);
3062 if (InversedSatisfied_CR.contains(LHS_CR))
3063 return ConstantInt::getFalse(RHS->getContext());
3064 }
3065 }
3066
Duncan Sands8fb2c382011-01-20 13:21:55 +00003067 // Compare of cast, for example (zext X) != 0 -> X != 0
3068 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
3069 Instruction *LI = cast<CastInst>(LHS);
3070 Value *SrcOp = LI->getOperand(0);
Chris Lattner229907c2011-07-18 04:54:35 +00003071 Type *SrcTy = SrcOp->getType();
3072 Type *DstTy = LI->getType();
Duncan Sands8fb2c382011-01-20 13:21:55 +00003073
3074 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
3075 // if the integer type is the same size as the pointer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003076 if (MaxRecurse && isa<PtrToIntInst>(LI) &&
3077 Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands8fb2c382011-01-20 13:21:55 +00003078 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
3079 // Transfer the cast to the constant.
3080 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
3081 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003082 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003083 return V;
3084 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
3085 if (RI->getOperand(0)->getType() == SrcTy)
3086 // Compare without the cast.
3087 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003088 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003089 return V;
3090 }
3091 }
3092
3093 if (isa<ZExtInst>(LHS)) {
3094 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
3095 // same type.
3096 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
3097 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3098 // Compare X and Y. Note that signed predicates become unsigned.
3099 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003100 SrcOp, RI->getOperand(0), Q,
Duncan Sands8fb2c382011-01-20 13:21:55 +00003101 MaxRecurse-1))
3102 return V;
3103 }
3104 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
3105 // too. If not, then try to deduce the result of the comparison.
3106 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3107 // Compute the constant that would happen if we truncated to SrcTy then
3108 // reextended to DstTy.
3109 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3110 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
3111
3112 // If the re-extended constant didn't change then this is effectively
3113 // also a case of comparing two zero-extended values.
3114 if (RExt == CI && MaxRecurse)
3115 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003116 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003117 return V;
3118
3119 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
3120 // there. Use this to work out the result of the comparison.
3121 if (RExt != CI) {
3122 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003123 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003124 // LHS <u RHS.
3125 case ICmpInst::ICMP_EQ:
3126 case ICmpInst::ICMP_UGT:
3127 case ICmpInst::ICMP_UGE:
3128 return ConstantInt::getFalse(CI->getContext());
3129
3130 case ICmpInst::ICMP_NE:
3131 case ICmpInst::ICMP_ULT:
3132 case ICmpInst::ICMP_ULE:
3133 return ConstantInt::getTrue(CI->getContext());
3134
3135 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
3136 // is non-negative then LHS <s RHS.
3137 case ICmpInst::ICMP_SGT:
3138 case ICmpInst::ICMP_SGE:
3139 return CI->getValue().isNegative() ?
3140 ConstantInt::getTrue(CI->getContext()) :
3141 ConstantInt::getFalse(CI->getContext());
3142
3143 case ICmpInst::ICMP_SLT:
3144 case ICmpInst::ICMP_SLE:
3145 return CI->getValue().isNegative() ?
3146 ConstantInt::getFalse(CI->getContext()) :
3147 ConstantInt::getTrue(CI->getContext());
3148 }
3149 }
3150 }
3151 }
3152
3153 if (isa<SExtInst>(LHS)) {
3154 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
3155 // same type.
3156 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
3157 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
3158 // Compare X and Y. Note that the predicate does not change.
3159 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003160 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003161 return V;
3162 }
3163 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
3164 // too. If not, then try to deduce the result of the comparison.
3165 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
3166 // Compute the constant that would happen if we truncated to SrcTy then
3167 // reextended to DstTy.
3168 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
3169 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
3170
3171 // If the re-extended constant didn't change then this is effectively
3172 // also a case of comparing two sign-extended values.
3173 if (RExt == CI && MaxRecurse)
Duncan Sandsb8cee002012-03-13 11:42:19 +00003174 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003175 return V;
3176
3177 // Otherwise the upper bits of LHS are all equal, while RHS has varying
3178 // bits there. Use this to work out the result of the comparison.
3179 if (RExt != CI) {
3180 switch (Pred) {
Craig Toppera2886c22012-02-07 05:05:23 +00003181 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands8fb2c382011-01-20 13:21:55 +00003182 case ICmpInst::ICMP_EQ:
3183 return ConstantInt::getFalse(CI->getContext());
3184 case ICmpInst::ICMP_NE:
3185 return ConstantInt::getTrue(CI->getContext());
3186
3187 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
3188 // LHS >s RHS.
3189 case ICmpInst::ICMP_SGT:
3190 case ICmpInst::ICMP_SGE:
3191 return CI->getValue().isNegative() ?
3192 ConstantInt::getTrue(CI->getContext()) :
3193 ConstantInt::getFalse(CI->getContext());
3194 case ICmpInst::ICMP_SLT:
3195 case ICmpInst::ICMP_SLE:
3196 return CI->getValue().isNegative() ?
3197 ConstantInt::getFalse(CI->getContext()) :
3198 ConstantInt::getTrue(CI->getContext());
3199
3200 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
3201 // LHS >u RHS.
3202 case ICmpInst::ICMP_UGT:
3203 case ICmpInst::ICMP_UGE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003204 // Comparison is true iff the LHS <s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003205 if (MaxRecurse)
3206 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
3207 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003208 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003209 return V;
3210 break;
3211 case ICmpInst::ICMP_ULT:
3212 case ICmpInst::ICMP_ULE:
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00003213 // Comparison is true iff the LHS >=s 0.
Duncan Sands8fb2c382011-01-20 13:21:55 +00003214 if (MaxRecurse)
3215 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
3216 Constant::getNullValue(SrcTy),
Duncan Sandsb8cee002012-03-13 11:42:19 +00003217 Q, MaxRecurse-1))
Duncan Sands8fb2c382011-01-20 13:21:55 +00003218 return V;
3219 break;
3220 }
3221 }
3222 }
3223 }
3224 }
3225
James Molloy1d88d6f2015-10-22 13:18:42 +00003226 // icmp eq|ne X, Y -> false|true if X != Y
3227 if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003228 isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT)) {
James Molloy1d88d6f2015-10-22 13:18:42 +00003229 LLVMContext &Ctx = LHS->getType()->getContext();
3230 return Pred == ICmpInst::ICMP_NE ?
3231 ConstantInt::getTrue(Ctx) : ConstantInt::getFalse(Ctx);
3232 }
Junmo Park53470fc2016-04-05 21:14:31 +00003233
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003234 if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
3235 return V;
Duncan Sandsd114ab32011-02-13 17:15:40 +00003236
Sanjay Patel35289c62016-12-10 17:40:47 +00003237 if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
Sanjay Patel9d5b5e32016-12-03 18:03:53 +00003238 return V;
Duncan Sandsa2287852011-05-04 16:05:05 +00003239
Chandler Carruth8059c842012-03-25 21:28:14 +00003240 // Simplify comparisons of related pointers using a powerful, recursive
3241 // GEP-walk when we have target data available..
Dan Gohman18c77a12013-01-31 02:50:36 +00003242 if (LHS->getType()->isPointerTy())
Anna Thomas43d7e1c2016-05-03 14:58:21 +00003243 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI, LHS, RHS))
Chandler Carruth8059c842012-03-25 21:28:14 +00003244 return C;
David Majnemerdc8767a2016-08-07 07:58:10 +00003245 if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
3246 if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
3247 if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
3248 Q.DL.getTypeSizeInBits(CLHS->getType()) &&
3249 Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
3250 Q.DL.getTypeSizeInBits(CRHS->getType()))
3251 if (auto *C = computePointerICmp(Q.DL, Q.TLI, Q.DT, Pred, Q.CxtI,
3252 CLHS->getPointerOperand(),
3253 CRHS->getPointerOperand()))
3254 return C;
Chandler Carruth8059c842012-03-25 21:28:14 +00003255
Nick Lewycky3db143e2012-02-26 02:09:49 +00003256 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
3257 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
3258 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
3259 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
3260 (ICmpInst::isEquality(Pred) ||
3261 (GLHS->isInBounds() && GRHS->isInBounds() &&
3262 Pred == ICmpInst::getSignedPredicate(Pred)))) {
3263 // The bases are equal and the indices are constant. Build a constant
3264 // expression GEP with the same indices and a null base pointer to see
3265 // what constant folding can make out of it.
3266 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
3267 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003268 Constant *NewLHS = ConstantExpr::getGetElementPtr(
3269 GLHS->getSourceElementType(), Null, IndicesLHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003270
3271 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
David Blaikie4a2e73b2015-04-02 18:55:32 +00003272 Constant *NewRHS = ConstantExpr::getGetElementPtr(
3273 GLHS->getSourceElementType(), Null, IndicesRHS);
Nick Lewycky3db143e2012-02-26 02:09:49 +00003274 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
3275 }
3276 }
3277 }
3278
David Majnemer5854e9f2014-11-16 02:20:08 +00003279 // If a bit is known to be zero for A and known to be one for B,
3280 // then A and B cannot be equal.
3281 if (ICmpInst::isEquality(Pred)) {
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003282 const APInt *RHSVal;
3283 if (match(RHS, m_APInt(RHSVal))) {
3284 unsigned BitWidth = RHSVal->getBitWidth();
Craig Topperb45eabc2017-04-26 16:39:58 +00003285 KnownBits LHSKnown(BitWidth);
3286 computeKnownBits(LHS, LHSKnown, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
3287 if (LHSKnown.Zero.intersects(*RHSVal) ||
3288 !LHSKnown.One.isSubsetOf(*RHSVal))
Sanjay Patelbcaf6f32016-08-04 17:48:04 +00003289 return Pred == ICmpInst::ICMP_EQ ? ConstantInt::getFalse(ITy)
3290 : ConstantInt::getTrue(ITy);
David Majnemer5854e9f2014-11-16 02:20:08 +00003291 }
3292 }
3293
Duncan Sandsf532d312010-11-07 16:12:23 +00003294 // If the comparison is with the result of a select instruction, check whether
3295 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003296 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003297 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003298 return V;
3299
3300 // If the comparison is with the result of a phi instruction, check whether
3301 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003302 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003303 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003304 return V;
Duncan Sandsf532d312010-11-07 16:12:23 +00003305
Craig Topper9f008862014-04-15 04:59:12 +00003306 return nullptr;
Chris Lattner084a1b52009-11-09 22:57:59 +00003307}
3308
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003309Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003310 const SimplifyQuery &Q) {
3311 return ::SimplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
3312}
3313
Sanjay Patel472cc782016-01-11 22:14:42 +00003314/// Given operands for an FCmpInst, see if we can fold the result.
3315/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003316static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003317 FastMathFlags FMF, const SimplifyQuery &Q,
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003318 unsigned MaxRecurse) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003319 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
3320 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
3321
Chris Lattnera71e9d62009-11-10 00:55:12 +00003322 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattnerc1f19072009-11-09 23:28:39 +00003323 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Rafael Espindola37dc9e12014-02-21 00:06:31 +00003324 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
Duncan Sands7e800d62010-11-14 11:23:23 +00003325
Chris Lattnera71e9d62009-11-10 00:55:12 +00003326 // If we have a constant, make sure it is on the RHS.
3327 std::swap(LHS, RHS);
3328 Pred = CmpInst::getSwappedPredicate(Pred);
3329 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003330
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003331 // Fold trivial predicates.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003332 Type *RetTy = GetCompareTy(LHS);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003333 if (Pred == FCmpInst::FCMP_FALSE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003334 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003335 if (Pred == FCmpInst::FCMP_TRUE)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003336 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003337
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003338 // UNO/ORD predicates can be trivially folded if NaNs are ignored.
3339 if (FMF.noNaNs()) {
3340 if (Pred == FCmpInst::FCMP_UNO)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003341 return getFalse(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003342 if (Pred == FCmpInst::FCMP_ORD)
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003343 return getTrue(RetTy);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00003344 }
3345
Mehdi Aminieb242a52015-03-09 03:20:25 +00003346 // fcmp pred x, undef and fcmp pred undef, x
3347 // fold to true if unordered, false if ordered
3348 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS)) {
3349 // Choosing NaN for the undef will always make unordered comparison succeed
3350 // and ordered comparison fail.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003351 return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
Mehdi Aminieb242a52015-03-09 03:20:25 +00003352 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003353
3354 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands772749a2011-01-01 20:08:02 +00003355 if (LHS == RHS) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003356 if (CmpInst::isTrueWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003357 return getTrue(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003358 if (CmpInst::isFalseWhenEqual(Pred))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003359 return getFalse(RetTy);
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003360 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003361
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003362 // Handle fcmp with constant RHS
David Majnemer3ee5f342016-04-13 06:55:52 +00003363 const ConstantFP *CFP = nullptr;
3364 if (const auto *RHSC = dyn_cast<Constant>(RHS)) {
3365 if (RHS->getType()->isVectorTy())
3366 CFP = dyn_cast_or_null<ConstantFP>(RHSC->getSplatValue());
3367 else
3368 CFP = dyn_cast<ConstantFP>(RHSC);
3369 }
3370 if (CFP) {
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003371 // If the constant is a nan, see if we can fold the comparison based on it.
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003372 if (CFP->getValueAPF().isNaN()) {
3373 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003374 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003375 assert(FCmpInst::isUnordered(Pred) &&
3376 "Comparison must be either ordered or unordered!");
3377 // True if unordered.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003378 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003379 }
3380 // Check whether the constant is an infinity.
3381 if (CFP->getValueAPF().isInfinity()) {
3382 if (CFP->getValueAPF().isNegative()) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003383 switch (Pred) {
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003384 case FCmpInst::FCMP_OLT:
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003385 // No value is ordered and less than negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003386 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003387 case FCmpInst::FCMP_UGE:
3388 // All values are unordered with or at least negative infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003389 return getTrue(RetTy);
Elena Demikhovsky45f04482015-01-28 08:03:58 +00003390 default:
3391 break;
3392 }
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003393 } else {
3394 switch (Pred) {
3395 case FCmpInst::FCMP_OGT:
3396 // No value is ordered and greater than infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003397 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003398 case FCmpInst::FCMP_ULE:
3399 // All values are unordered with and at most infinity.
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003400 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003401 default:
3402 break;
3403 }
3404 }
3405 }
3406 if (CFP->getValueAPF().isZero()) {
3407 switch (Pred) {
3408 case FCmpInst::FCMP_UGE:
David Majnemer3ee5f342016-04-13 06:55:52 +00003409 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003410 return getTrue(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003411 break;
3412 case FCmpInst::FCMP_OLT:
3413 // X < 0
David Majnemer3ee5f342016-04-13 06:55:52 +00003414 if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
Andrea Di Biagiobff3fd62016-09-02 15:55:25 +00003415 return getFalse(RetTy);
Mehdi Amini383d7ae2015-02-13 07:38:04 +00003416 break;
3417 default:
3418 break;
3419 }
Chris Lattnerccfdceb2009-11-09 23:55:12 +00003420 }
3421 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003422
Duncan Sandsa620bd12010-11-07 16:46:25 +00003423 // If the comparison is with the result of a select instruction, check whether
3424 // comparing with either branch of the select always yields the same value.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003425 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003426 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003427 return V;
3428
3429 // If the comparison is with the result of a phi instruction, check whether
3430 // doing the compare with each incoming phi value yields a common result.
Duncan Sandsf64e6902010-12-21 09:09:15 +00003431 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sandsb8cee002012-03-13 11:42:19 +00003432 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsfc5ad3f02010-11-09 17:25:51 +00003433 return V;
Duncan Sandsa620bd12010-11-07 16:46:25 +00003434
Craig Topper9f008862014-04-15 04:59:12 +00003435 return nullptr;
Chris Lattnerc1f19072009-11-09 23:28:39 +00003436}
3437
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003438Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003439 FastMathFlags FMF, const SimplifyQuery &Q) {
3440 return ::SimplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00003441}
3442
Sanjay Patel472cc782016-01-11 22:14:42 +00003443/// See if V simplifies when its operand Op is replaced with RepOp.
David Majnemer3f0fb982015-06-06 22:40:21 +00003444static const Value *SimplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003445 const SimplifyQuery &Q,
David Majnemer3f0fb982015-06-06 22:40:21 +00003446 unsigned MaxRecurse) {
3447 // Trivial replacement.
3448 if (V == Op)
3449 return RepOp;
3450
3451 auto *I = dyn_cast<Instruction>(V);
3452 if (!I)
3453 return nullptr;
3454
3455 // If this is a binary operator, try to simplify it with the replaced op.
3456 if (auto *B = dyn_cast<BinaryOperator>(I)) {
3457 // Consider:
3458 // %cmp = icmp eq i32 %x, 2147483647
3459 // %add = add nsw i32 %x, 1
3460 // %sel = select i1 %cmp, i32 -2147483648, i32 %add
3461 //
3462 // We can't replace %sel with %add unless we strip away the flags.
3463 if (isa<OverflowingBinaryOperator>(B))
3464 if (B->hasNoSignedWrap() || B->hasNoUnsignedWrap())
3465 return nullptr;
3466 if (isa<PossiblyExactOperator>(B))
3467 if (B->isExact())
3468 return nullptr;
3469
3470 if (MaxRecurse) {
3471 if (B->getOperand(0) == Op)
3472 return SimplifyBinOp(B->getOpcode(), RepOp, B->getOperand(1), Q,
3473 MaxRecurse - 1);
3474 if (B->getOperand(1) == Op)
3475 return SimplifyBinOp(B->getOpcode(), B->getOperand(0), RepOp, Q,
3476 MaxRecurse - 1);
3477 }
3478 }
3479
3480 // Same for CmpInsts.
3481 if (CmpInst *C = dyn_cast<CmpInst>(I)) {
3482 if (MaxRecurse) {
3483 if (C->getOperand(0) == Op)
3484 return SimplifyCmpInst(C->getPredicate(), RepOp, C->getOperand(1), Q,
3485 MaxRecurse - 1);
3486 if (C->getOperand(1) == Op)
3487 return SimplifyCmpInst(C->getPredicate(), C->getOperand(0), RepOp, Q,
3488 MaxRecurse - 1);
3489 }
3490 }
3491
3492 // TODO: We could hand off more cases to instsimplify here.
3493
3494 // If all operands are constant after substituting Op for RepOp then we can
3495 // constant fold the instruction.
3496 if (Constant *CRepOp = dyn_cast<Constant>(RepOp)) {
3497 // Build a list of all constant operands.
3498 SmallVector<Constant *, 8> ConstOps;
3499 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3500 if (I->getOperand(i) == Op)
3501 ConstOps.push_back(CRepOp);
3502 else if (Constant *COp = dyn_cast<Constant>(I->getOperand(i)))
3503 ConstOps.push_back(COp);
3504 else
3505 break;
3506 }
3507
3508 // All operands were constants, fold it.
3509 if (ConstOps.size() == I->getNumOperands()) {
3510 if (CmpInst *C = dyn_cast<CmpInst>(I))
3511 return ConstantFoldCompareInstOperands(C->getPredicate(), ConstOps[0],
3512 ConstOps[1], Q.DL, Q.TLI);
3513
3514 if (LoadInst *LI = dyn_cast<LoadInst>(I))
3515 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00003516 return ConstantFoldLoadFromConstPtr(ConstOps[0], LI->getType(), Q.DL);
David Majnemer3f0fb982015-06-06 22:40:21 +00003517
Manuel Jacobe9024592016-01-21 06:33:22 +00003518 return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
David Majnemer3f0fb982015-06-06 22:40:21 +00003519 }
3520 }
3521
3522 return nullptr;
3523}
3524
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003525/// Try to simplify a select instruction when its condition operand is an
3526/// integer comparison where one operand of the compare is a constant.
3527static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
3528 const APInt *Y, bool TrueWhenUnset) {
3529 const APInt *C;
3530
3531 // (X & Y) == 0 ? X & ~Y : X --> X
3532 // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
3533 if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
3534 *Y == ~*C)
3535 return TrueWhenUnset ? FalseVal : TrueVal;
3536
3537 // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
3538 // (X & Y) != 0 ? X : X & ~Y --> X
3539 if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
3540 *Y == ~*C)
3541 return TrueWhenUnset ? FalseVal : TrueVal;
3542
3543 if (Y->isPowerOf2()) {
3544 // (X & Y) == 0 ? X | Y : X --> X | Y
3545 // (X & Y) != 0 ? X | Y : X --> X
3546 if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
3547 *Y == *C)
3548 return TrueWhenUnset ? TrueVal : FalseVal;
3549
3550 // (X & Y) == 0 ? X : X | Y --> X
3551 // (X & Y) != 0 ? X : X | Y --> X | Y
3552 if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
3553 *Y == *C)
3554 return TrueWhenUnset ? TrueVal : FalseVal;
3555 }
Matt Arsenault82606662017-01-11 00:57:54 +00003556
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003557 return nullptr;
3558}
3559
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003560/// An alternative way to test if a bit is set or not uses sgt/slt instead of
3561/// eq/ne.
3562static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *TrueVal,
3563 Value *FalseVal,
3564 bool TrueWhenUnset) {
3565 unsigned BitWidth = TrueVal->getType()->getScalarSizeInBits();
Sanjay Patele9fc79b2016-07-21 21:56:00 +00003566 if (!BitWidth)
3567 return nullptr;
Matt Arsenault82606662017-01-11 00:57:54 +00003568
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003569 APInt MinSignedValue;
3570 Value *X;
3571 if (match(CmpLHS, m_Trunc(m_Value(X))) && (X == TrueVal || X == FalseVal)) {
3572 // icmp slt (trunc X), 0 <--> icmp ne (and X, C), 0
3573 // icmp sgt (trunc X), -1 <--> icmp eq (and X, C), 0
3574 unsigned DestSize = CmpLHS->getType()->getScalarSizeInBits();
3575 MinSignedValue = APInt::getSignedMinValue(DestSize).zext(BitWidth);
3576 } else {
3577 // icmp slt X, 0 <--> icmp ne (and X, C), 0
3578 // icmp sgt X, -1 <--> icmp eq (and X, C), 0
3579 X = CmpLHS;
3580 MinSignedValue = APInt::getSignedMinValue(BitWidth);
3581 }
3582
3583 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, &MinSignedValue,
3584 TrueWhenUnset))
3585 return V;
3586
3587 return nullptr;
3588}
3589
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003590/// Try to simplify a select instruction when its condition operand is an
3591/// integer comparison.
3592static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003593 Value *FalseVal, const SimplifyQuery &Q,
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003594 unsigned MaxRecurse) {
3595 ICmpInst::Predicate Pred;
3596 Value *CmpLHS, *CmpRHS;
3597 if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
3598 return nullptr;
3599
Sanjay Patel5f3c7032016-07-20 23:40:01 +00003600 // FIXME: This code is nearly duplicated in InstCombine. Using/refactoring
3601 // decomposeBitTestICmp() might help.
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003602 if (ICmpInst::isEquality(Pred) && match(CmpRHS, m_Zero())) {
3603 Value *X;
3604 const APInt *Y;
3605 if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
3606 if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
3607 Pred == ICmpInst::ICMP_EQ))
3608 return V;
3609 } else if (Pred == ICmpInst::ICMP_SLT && match(CmpRHS, m_Zero())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003610 // Comparing signed-less-than 0 checks if the sign bit is set.
3611 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3612 false))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003613 return V;
3614 } else if (Pred == ICmpInst::ICMP_SGT && match(CmpRHS, m_AllOnes())) {
Sanjay Patela3bfb4e2016-07-21 21:26:45 +00003615 // Comparing signed-greater-than -1 checks if the sign bit is not set.
3616 if (Value *V = simplifySelectWithFakeICmpEq(CmpLHS, TrueVal, FalseVal,
3617 true))
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003618 return V;
3619 }
3620
3621 if (CondVal->hasOneUse()) {
3622 const APInt *C;
3623 if (match(CmpRHS, m_APInt(C))) {
3624 // X < MIN ? T : F --> F
3625 if (Pred == ICmpInst::ICMP_SLT && C->isMinSignedValue())
3626 return FalseVal;
3627 // X < MIN ? T : F --> F
3628 if (Pred == ICmpInst::ICMP_ULT && C->isMinValue())
3629 return FalseVal;
3630 // X > MAX ? T : F --> F
3631 if (Pred == ICmpInst::ICMP_SGT && C->isMaxSignedValue())
3632 return FalseVal;
3633 // X > MAX ? T : F --> F
3634 if (Pred == ICmpInst::ICMP_UGT && C->isMaxValue())
3635 return FalseVal;
3636 }
3637 }
3638
3639 // If we have an equality comparison, then we know the value in one of the
3640 // arms of the select. See if substituting this value into the arm and
3641 // simplifying the result yields the same value as the other arm.
3642 if (Pred == ICmpInst::ICMP_EQ) {
3643 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3644 TrueVal ||
3645 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3646 TrueVal)
3647 return FalseVal;
3648 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3649 FalseVal ||
3650 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3651 FalseVal)
3652 return FalseVal;
3653 } else if (Pred == ICmpInst::ICMP_NE) {
3654 if (SimplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3655 FalseVal ||
3656 SimplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3657 FalseVal)
3658 return TrueVal;
3659 if (SimplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q, MaxRecurse) ==
3660 TrueVal ||
3661 SimplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q, MaxRecurse) ==
3662 TrueVal)
3663 return TrueVal;
3664 }
3665
3666 return nullptr;
3667}
3668
Sanjay Patel472cc782016-01-11 22:14:42 +00003669/// Given operands for a SelectInst, see if we can fold the result.
3670/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003671static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003672 Value *FalseVal, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003673 unsigned MaxRecurse) {
Chris Lattnerc707fa92010-04-20 05:32:14 +00003674 // select true, X, Y -> X
3675 // select false, X, Y -> Y
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003676 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
3677 if (CB->isAllOnesValue())
3678 return TrueVal;
3679 if (CB->isNullValue())
3680 return FalseVal;
3681 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003682
Chris Lattnerc707fa92010-04-20 05:32:14 +00003683 // select C, X, X -> X
Duncan Sands772749a2011-01-01 20:08:02 +00003684 if (TrueVal == FalseVal)
Chris Lattnerc707fa92010-04-20 05:32:14 +00003685 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003686
Chris Lattnerc707fa92010-04-20 05:32:14 +00003687 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3688 if (isa<Constant>(TrueVal))
3689 return TrueVal;
3690 return FalseVal;
3691 }
Dan Gohman54664ed2011-07-01 01:03:43 +00003692 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3693 return FalseVal;
3694 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3695 return TrueVal;
Duncan Sands7e800d62010-11-14 11:23:23 +00003696
Sanjay Patel5f5eb582016-07-18 20:56:53 +00003697 if (Value *V =
3698 simplifySelectWithICmpCond(CondVal, TrueVal, FalseVal, Q, MaxRecurse))
3699 return V;
David Majnemerc6a5e1d2014-11-27 06:32:46 +00003700
Craig Topper9f008862014-04-15 04:59:12 +00003701 return nullptr;
Chris Lattnerc707fa92010-04-20 05:32:14 +00003702}
3703
Duncan Sandsb8cee002012-03-13 11:42:19 +00003704Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003705 const SimplifyQuery &Q) {
3706 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003707}
3708
Sanjay Patel472cc782016-01-11 22:14:42 +00003709/// Given operands for an GetElementPtrInst, see if we can fold the result.
3710/// If not, this returns null.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003711static Value *SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003712 const SimplifyQuery &Q, unsigned) {
Duncan Sands8a0f4862010-11-22 13:42:49 +00003713 // The type of the GEP pointer operand.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003714 unsigned AS =
3715 cast<PointerType>(Ops[0]->getType()->getScalarType())->getAddressSpace();
Duncan Sands8a0f4862010-11-22 13:42:49 +00003716
Chris Lattner8574aba2009-11-27 00:29:05 +00003717 // getelementptr P -> P.
Jay Foadb992a632011-07-19 15:07:52 +00003718 if (Ops.size() == 1)
Chris Lattner8574aba2009-11-27 00:29:05 +00003719 return Ops[0];
3720
Nico Weber48c82402014-08-27 20:06:19 +00003721 // Compute the (pointer) type returned by the GEP instruction.
David Blaikie4a2e73b2015-04-02 18:55:32 +00003722 Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Ops.slice(1));
Nico Weber48c82402014-08-27 20:06:19 +00003723 Type *GEPTy = PointerType::get(LastType, AS);
3724 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
3725 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Davide Italianoa9f047a2017-04-19 14:23:42 +00003726 else if (VectorType *VT = dyn_cast<VectorType>(Ops[1]->getType()))
3727 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
Nico Weber48c82402014-08-27 20:06:19 +00003728
3729 if (isa<UndefValue>(Ops[0]))
Duncan Sands8a0f4862010-11-22 13:42:49 +00003730 return UndefValue::get(GEPTy);
Chris Lattner8574aba2009-11-27 00:29:05 +00003731
Jay Foadb992a632011-07-19 15:07:52 +00003732 if (Ops.size() == 2) {
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003733 // getelementptr P, 0 -> P.
Benjamin Kramer5e1794e2014-01-24 17:09:53 +00003734 if (match(Ops[1], m_Zero()))
3735 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003736
David Blaikie4a2e73b2015-04-02 18:55:32 +00003737 Type *Ty = SrcTy;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003738 if (Ty->isSized()) {
Nico Weber48c82402014-08-27 20:06:19 +00003739 Value *P;
3740 uint64_t C;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003741 uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
Nico Weber48c82402014-08-27 20:06:19 +00003742 // getelementptr P, N -> P if P points to a type of zero size.
3743 if (TyAllocSize == 0)
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003744 return Ops[0];
Nico Weber48c82402014-08-27 20:06:19 +00003745
3746 // The following transforms are only safe if the ptrtoint cast
3747 // doesn't truncate the pointers.
3748 if (Ops[1]->getType()->getScalarSizeInBits() ==
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003749 Q.DL.getPointerSizeInBits(AS)) {
Nico Weber48c82402014-08-27 20:06:19 +00003750 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
3751 if (match(P, m_Zero()))
3752 return Constant::getNullValue(GEPTy);
3753 Value *Temp;
3754 if (match(P, m_PtrToInt(m_Value(Temp))))
David Majnemer11ca2972014-08-27 20:08:34 +00003755 if (Temp->getType() == GEPTy)
3756 return Temp;
Nico Weber48c82402014-08-27 20:06:19 +00003757 return nullptr;
3758 };
3759
3760 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
3761 if (TyAllocSize == 1 &&
3762 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
3763 if (Value *R = PtrToIntOrZero(P))
3764 return R;
3765
3766 // getelementptr V, (ashr (sub P, V), C) -> Q
3767 // if P points to a type of size 1 << C.
3768 if (match(Ops[1],
3769 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3770 m_ConstantInt(C))) &&
3771 TyAllocSize == 1ULL << C)
3772 if (Value *R = PtrToIntOrZero(P))
3773 return R;
3774
3775 // getelementptr V, (sdiv (sub P, V), C) -> Q
3776 // if P points to a type of size C.
3777 if (match(Ops[1],
3778 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
3779 m_SpecificInt(TyAllocSize))))
3780 if (Value *R = PtrToIntOrZero(P))
3781 return R;
3782 }
Duncan Sandscf4bceb2010-11-21 13:53:09 +00003783 }
3784 }
Duncan Sands7e800d62010-11-14 11:23:23 +00003785
David Majnemerd1501372016-08-07 07:58:12 +00003786 if (Q.DL.getTypeAllocSize(LastType) == 1 &&
3787 all_of(Ops.slice(1).drop_back(1),
3788 [](Value *Idx) { return match(Idx, m_Zero()); })) {
3789 unsigned PtrWidth =
3790 Q.DL.getPointerSizeInBits(Ops[0]->getType()->getPointerAddressSpace());
3791 if (Q.DL.getTypeSizeInBits(Ops.back()->getType()) == PtrWidth) {
3792 APInt BasePtrOffset(PtrWidth, 0);
3793 Value *StrippedBasePtr =
3794 Ops[0]->stripAndAccumulateInBoundsConstantOffsets(Q.DL,
3795 BasePtrOffset);
3796
David Majnemer5c5df622016-08-16 06:13:46 +00003797 // gep (gep V, C), (sub 0, V) -> C
David Majnemerd1501372016-08-07 07:58:12 +00003798 if (match(Ops.back(),
3799 m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr))))) {
3800 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
3801 return ConstantExpr::getIntToPtr(CI, GEPTy);
3802 }
David Majnemer5c5df622016-08-16 06:13:46 +00003803 // gep (gep V, C), (xor V, -1) -> C-1
3804 if (match(Ops.back(),
3805 m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes()))) {
3806 auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
3807 return ConstantExpr::getIntToPtr(CI, GEPTy);
3808 }
David Majnemerd1501372016-08-07 07:58:12 +00003809 }
3810 }
3811
Chris Lattner8574aba2009-11-27 00:29:05 +00003812 // Check to see if this is constant foldable.
Jay Foadb992a632011-07-19 15:07:52 +00003813 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattner8574aba2009-11-27 00:29:05 +00003814 if (!isa<Constant>(Ops[i]))
Craig Topper9f008862014-04-15 04:59:12 +00003815 return nullptr;
Duncan Sands7e800d62010-11-14 11:23:23 +00003816
David Blaikie4a2e73b2015-04-02 18:55:32 +00003817 return ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ops[0]),
3818 Ops.slice(1));
Chris Lattner8574aba2009-11-27 00:29:05 +00003819}
3820
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00003821Value *llvm::SimplifyGEPInst(Type *SrcTy, ArrayRef<Value *> Ops,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003822 const SimplifyQuery &Q) {
3823 return ::SimplifyGEPInst(SrcTy, Ops, Q, RecursionLimit);
Duncan Sandsb8cee002012-03-13 11:42:19 +00003824}
3825
Sanjay Patel472cc782016-01-11 22:14:42 +00003826/// Given operands for an InsertValueInst, see if we can fold the result.
3827/// If not, this returns null.
Duncan Sandsb8cee002012-03-13 11:42:19 +00003828static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003829 ArrayRef<unsigned> Idxs, const SimplifyQuery &Q,
Duncan Sandsb8cee002012-03-13 11:42:19 +00003830 unsigned) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003831 if (Constant *CAgg = dyn_cast<Constant>(Agg))
3832 if (Constant *CVal = dyn_cast<Constant>(Val))
3833 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
3834
3835 // insertvalue x, undef, n -> x
3836 if (match(Val, m_Undef()))
3837 return Agg;
3838
3839 // insertvalue x, (extractvalue y, n), n
3840 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramer4b79c212011-09-05 18:16:19 +00003841 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3842 EV->getIndices() == Idxs) {
Duncan Sandsfd26a952011-09-05 06:52:48 +00003843 // insertvalue undef, (extractvalue y, n), n -> y
3844 if (match(Agg, m_Undef()))
3845 return EV->getAggregateOperand();
3846
3847 // insertvalue y, (extractvalue y, n), n -> y
3848 if (Agg == EV->getAggregateOperand())
3849 return Agg;
3850 }
3851
Craig Topper9f008862014-04-15 04:59:12 +00003852 return nullptr;
Duncan Sandsfd26a952011-09-05 06:52:48 +00003853}
3854
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003855Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3856 ArrayRef<unsigned> Idxs,
3857 const SimplifyQuery &Q) {
3858 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
3859}
3860
Sanjay Patel472cc782016-01-11 22:14:42 +00003861/// Given operands for an ExtractValueInst, see if we can fold the result.
3862/// If not, this returns null.
David Majnemer25a796e2015-07-13 01:15:46 +00003863static Value *SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003864 const SimplifyQuery &, unsigned) {
David Majnemer25a796e2015-07-13 01:15:46 +00003865 if (auto *CAgg = dyn_cast<Constant>(Agg))
3866 return ConstantFoldExtractValueInstruction(CAgg, Idxs);
3867
3868 // extractvalue x, (insertvalue y, elt, n), n -> elt
3869 unsigned NumIdxs = Idxs.size();
3870 for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
3871 IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
3872 ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
3873 unsigned NumInsertValueIdxs = InsertValueIdxs.size();
3874 unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
3875 if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
3876 Idxs.slice(0, NumCommonIdxs)) {
3877 if (NumIdxs == NumInsertValueIdxs)
3878 return IVI->getInsertedValueOperand();
3879 break;
3880 }
3881 }
3882
3883 return nullptr;
3884}
3885
3886Value *llvm::SimplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003887 const SimplifyQuery &Q) {
3888 return ::SimplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
3889}
3890
Sanjay Patel472cc782016-01-11 22:14:42 +00003891/// Given operands for an ExtractElementInst, see if we can fold the result.
3892/// If not, this returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003893static Value *SimplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &,
David Majnemer599ca442015-07-13 01:15:53 +00003894 unsigned) {
3895 if (auto *CVec = dyn_cast<Constant>(Vec)) {
3896 if (auto *CIdx = dyn_cast<Constant>(Idx))
3897 return ConstantFoldExtractElementInstruction(CVec, CIdx);
3898
3899 // The index is not relevant if our vector is a splat.
3900 if (auto *Splat = CVec->getSplatValue())
3901 return Splat;
3902
3903 if (isa<UndefValue>(Vec))
3904 return UndefValue::get(Vec->getType()->getVectorElementType());
3905 }
3906
3907 // If extracting a specified index from the vector, see if we can recursively
3908 // find a previously computed scalar that was inserted into the vector.
David Majnemer8e335ca2015-08-18 22:18:22 +00003909 if (auto *IdxC = dyn_cast<ConstantInt>(Idx))
3910 if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
David Majnemer599ca442015-07-13 01:15:53 +00003911 return Elt;
David Majnemer599ca442015-07-13 01:15:53 +00003912
3913 return nullptr;
3914}
3915
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003916Value *llvm::SimplifyExtractElementInst(Value *Vec, Value *Idx,
3917 const SimplifyQuery &Q) {
3918 return ::SimplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
3919}
3920
Sanjay Patel472cc782016-01-11 22:14:42 +00003921/// See if we can fold the given phi. If not, returns null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003922static Value *SimplifyPHINode(PHINode *PN, const SimplifyQuery &Q) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003923 // If all of the PHI's incoming values are the same then replace the PHI node
3924 // with the common value.
Craig Topper9f008862014-04-15 04:59:12 +00003925 Value *CommonValue = nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003926 bool HasUndefInput = false;
Pete Cooper833f34d2015-05-12 20:05:31 +00003927 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands7412f6e2010-11-17 04:30:22 +00003928 // If the incoming value is the phi node itself, it can safely be skipped.
3929 if (Incoming == PN) continue;
3930 if (isa<UndefValue>(Incoming)) {
3931 // Remember that we saw an undef value, but otherwise ignore them.
3932 HasUndefInput = true;
3933 continue;
3934 }
3935 if (CommonValue && Incoming != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00003936 return nullptr; // Not the same, bail out.
Duncan Sands7412f6e2010-11-17 04:30:22 +00003937 CommonValue = Incoming;
3938 }
3939
3940 // If CommonValue is null then all of the incoming values were either undef or
3941 // equal to the phi node itself.
3942 if (!CommonValue)
3943 return UndefValue::get(PN->getType());
3944
3945 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3946 // instruction, we cannot return X as the result of the PHI node unless it
3947 // dominates the PHI block.
3948 if (HasUndefInput)
Craig Topper9f008862014-04-15 04:59:12 +00003949 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
Duncan Sands7412f6e2010-11-17 04:30:22 +00003950
3951 return CommonValue;
3952}
3953
David Majnemer6774d612016-07-26 17:58:05 +00003954static Value *SimplifyCastInst(unsigned CastOpc, Value *Op,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003955 Type *Ty, const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemer126de5d2016-07-25 03:39:21 +00003956 if (auto *C = dyn_cast<Constant>(Op))
David Majnemer6774d612016-07-26 17:58:05 +00003957 return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
Duncan Sands395ac42d2012-03-13 14:07:05 +00003958
David Majnemer6774d612016-07-26 17:58:05 +00003959 if (auto *CI = dyn_cast<CastInst>(Op)) {
3960 auto *Src = CI->getOperand(0);
3961 Type *SrcTy = Src->getType();
3962 Type *MidTy = CI->getType();
3963 Type *DstTy = Ty;
3964 if (Src->getType() == Ty) {
3965 auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
3966 auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
3967 Type *SrcIntPtrTy =
3968 SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
3969 Type *MidIntPtrTy =
3970 MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
3971 Type *DstIntPtrTy =
3972 DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
3973 if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
3974 SrcIntPtrTy, MidIntPtrTy,
3975 DstIntPtrTy) == Instruction::BitCast)
3976 return Src;
3977 }
3978 }
David Majnemera90a6212016-07-26 05:52:29 +00003979
3980 // bitcast x -> x
David Majnemer6774d612016-07-26 17:58:05 +00003981 if (CastOpc == Instruction::BitCast)
3982 if (Op->getType() == Ty)
3983 return Op;
David Majnemera90a6212016-07-26 05:52:29 +00003984
3985 return nullptr;
3986}
3987
David Majnemer6774d612016-07-26 17:58:05 +00003988Value *llvm::SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00003989 const SimplifyQuery &Q) {
3990 return ::SimplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
3991}
3992
Sanjay Patela3c297d2017-04-19 16:48:22 +00003993/// For the given destination element of a shuffle, peek through shuffles to
3994/// match a root vector source operand that contains that element in the same
3995/// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
3996static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
3997 Constant *Mask, Value *RootVec, int RootElt,
3998 unsigned MaxRecurse) {
3999 if (!MaxRecurse--)
4000 return nullptr;
4001
4002 // Bail out if any mask value is undefined. That kind of shuffle may be
4003 // simplified further based on demanded bits or other folds.
4004 int MaskVal = ShuffleVectorInst::getMaskValue(Mask, RootElt);
4005 if (MaskVal == -1)
4006 return nullptr;
4007
4008 // The mask value chooses which source operand we need to look at next.
4009 Value *SourceOp;
4010 int InVecNumElts = Op0->getType()->getVectorNumElements();
4011 if (MaskVal < InVecNumElts) {
4012 RootElt = MaskVal;
4013 SourceOp = Op0;
4014 } else {
4015 RootElt = MaskVal - InVecNumElts;
4016 SourceOp = Op1;
4017 }
4018
4019 // If the source operand is a shuffle itself, look through it to find the
4020 // matching root vector.
4021 if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
4022 return foldIdentityShuffles(
4023 DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
4024 SourceShuf->getMask(), RootVec, RootElt, MaxRecurse);
4025 }
4026
4027 // TODO: Look through bitcasts? What if the bitcast changes the vector element
4028 // size?
4029
4030 // The source operand is not a shuffle. Initialize the root vector value for
4031 // this shuffle if that has not been done yet.
4032 if (!RootVec)
4033 RootVec = SourceOp;
4034
4035 // Give up as soon as a source operand does not match the existing root value.
4036 if (RootVec != SourceOp)
4037 return nullptr;
4038
4039 // The element must be coming from the same lane in the source vector
4040 // (although it may have crossed lanes in intermediate shuffles).
4041 if (RootElt != DestElt)
4042 return nullptr;
4043
4044 return RootVec;
4045}
4046
Zvi Rackover8f460652017-04-03 22:05:30 +00004047static Value *SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004048 Type *RetTy, const SimplifyQuery &Q,
Zvi Rackover8f460652017-04-03 22:05:30 +00004049 unsigned MaxRecurse) {
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004050 Type *InVecTy = Op0->getType();
Zvi Rackover8f460652017-04-03 22:05:30 +00004051 unsigned MaskNumElts = Mask->getType()->getVectorNumElements();
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004052 unsigned InVecNumElts = InVecTy->getVectorNumElements();
Zvi Rackover8f460652017-04-03 22:05:30 +00004053
4054 auto *Op0Const = dyn_cast<Constant>(Op0);
4055 auto *Op1Const = dyn_cast<Constant>(Op1);
4056
4057 // If all operands are constant, constant fold the shuffle.
4058 if (Op0Const && Op1Const)
4059 return ConstantFoldShuffleVectorInstruction(Op0Const, Op1Const, Mask);
4060
4061 // If only one of the operands is constant, constant fold the shuffle if the
4062 // mask does not select elements from the variable operand.
4063 bool MaskSelects0 = false, MaskSelects1 = false;
4064 for (unsigned i = 0; i != MaskNumElts; ++i) {
4065 int Idx = ShuffleVectorInst::getMaskValue(Mask, i);
4066 if (Idx == -1)
4067 continue;
4068 if ((unsigned)Idx < InVecNumElts)
4069 MaskSelects0 = true;
4070 else
4071 MaskSelects1 = true;
4072 }
4073 if (!MaskSelects0 && Op1Const)
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004074 return ConstantFoldShuffleVectorInstruction(UndefValue::get(InVecTy),
Zvi Rackover8f460652017-04-03 22:05:30 +00004075 Op1Const, Mask);
4076 if (!MaskSelects1 && Op0Const)
Zvi Rackover30efd24d2017-04-11 21:37:02 +00004077 return ConstantFoldShuffleVectorInstruction(Op0Const,
4078 UndefValue::get(InVecTy), Mask);
4079
4080 // A shuffle of a splat is always the splat itself. Legal if the shuffle's
4081 // value type is same as the input vectors' type.
4082 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
4083 if (!MaskSelects1 && RetTy == InVecTy &&
4084 OpShuf->getMask()->getSplatValue())
4085 return Op0;
4086 if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op1))
4087 if (!MaskSelects0 && RetTy == InVecTy &&
4088 OpShuf->getMask()->getSplatValue())
4089 return Op1;
Zvi Rackover8f460652017-04-03 22:05:30 +00004090
Sanjay Patela3c297d2017-04-19 16:48:22 +00004091 // Don't fold a shuffle with undef mask elements. This may get folded in a
4092 // better way using demanded bits or other analysis.
4093 // TODO: Should we allow this?
4094 for (unsigned i = 0; i != MaskNumElts; ++i)
4095 if (ShuffleVectorInst::getMaskValue(Mask, i) == -1)
4096 return nullptr;
4097
4098 // Check if every element of this shuffle can be mapped back to the
4099 // corresponding element of a single root vector. If so, we don't need this
4100 // shuffle. This handles simple identity shuffles as well as chains of
4101 // shuffles that may widen/narrow and/or move elements across lanes and back.
4102 Value *RootVec = nullptr;
4103 for (unsigned i = 0; i != MaskNumElts; ++i) {
4104 // Note that recursion is limited for each vector element, so if any element
4105 // exceeds the limit, this will fail to simplify.
4106 RootVec = foldIdentityShuffles(i, Op0, Op1, Mask, RootVec, i, MaxRecurse);
4107
4108 // We can't replace a widening/narrowing shuffle with one of its operands.
4109 if (!RootVec || RootVec->getType() != RetTy)
4110 return nullptr;
4111 }
4112 return RootVec;
Zvi Rackover8f460652017-04-03 22:05:30 +00004113}
4114
4115/// Given operands for a ShuffleVectorInst, fold the result or return null.
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004116Value *llvm::SimplifyShuffleVectorInst(Value *Op0, Value *Op1, Constant *Mask,
4117 Type *RetTy, const SimplifyQuery &Q) {
4118 return ::SimplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
Zvi Rackover8f460652017-04-03 22:05:30 +00004119}
4120
Chris Lattnera71e9d62009-11-10 00:55:12 +00004121//=== Helper functions for higher up the class hierarchy.
Chris Lattnerc1f19072009-11-09 23:28:39 +00004122
Sanjay Patel472cc782016-01-11 22:14:42 +00004123/// Given operands for a BinaryOperator, see if we can fold the result.
4124/// If not, this returns null.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004125static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004126 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chris Lattnera71e9d62009-11-10 00:55:12 +00004127 switch (Opcode) {
Chris Lattner9e4aa022011-02-09 17:15:04 +00004128 case Instruction::Add:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004129 return SimplifyAddInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004130 case Instruction::FAdd:
4131 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004132 case Instruction::Sub:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004133 return SimplifySubInst(LHS, RHS, false, false, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004134 case Instruction::FSub:
4135 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004136 case Instruction::Mul:
4137 return SimplifyMulInst(LHS, RHS, Q, MaxRecurse);
Michael Ilsemand2b05e52012-12-12 00:29:16 +00004138 case Instruction::FMul:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004139 return SimplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4140 case Instruction::SDiv:
4141 return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
4142 case Instruction::UDiv:
4143 return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004144 case Instruction::FDiv:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004145 return SimplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
4146 case Instruction::SRem:
4147 return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
4148 case Instruction::URem:
4149 return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004150 case Instruction::FRem:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004151 return SimplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004152 case Instruction::Shl:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004153 return SimplifyShlInst(LHS, RHS, false, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004154 case Instruction::LShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004155 return SimplifyLShrInst(LHS, RHS, false, Q, MaxRecurse);
Chris Lattner9e4aa022011-02-09 17:15:04 +00004156 case Instruction::AShr:
Sanjay Patel1fd16f02017-04-01 18:40:30 +00004157 return SimplifyAShrInst(LHS, RHS, false, Q, MaxRecurse);
4158 case Instruction::And:
4159 return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
4160 case Instruction::Or:
4161 return SimplifyOrInst(LHS, RHS, Q, MaxRecurse);
4162 case Instruction::Xor:
4163 return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnera71e9d62009-11-10 00:55:12 +00004164 default:
Craig Topper8ef20ea2017-04-06 18:59:08 +00004165 llvm_unreachable("Unexpected opcode");
Chris Lattnera71e9d62009-11-10 00:55:12 +00004166 }
4167}
Chris Lattnerc1f19072009-11-09 23:28:39 +00004168
Sanjay Patel472cc782016-01-11 22:14:42 +00004169/// Given operands for a BinaryOperator, see if we can fold the result.
4170/// If not, this returns null.
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004171/// In contrast to SimplifyBinOp, try to use FastMathFlag when folding the
4172/// result. In case we don't need FastMathFlags, simply fall to SimplifyBinOp.
4173static Value *SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004174 const FastMathFlags &FMF, const SimplifyQuery &Q,
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004175 unsigned MaxRecurse) {
4176 switch (Opcode) {
4177 case Instruction::FAdd:
4178 return SimplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
4179 case Instruction::FSub:
4180 return SimplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
4181 case Instruction::FMul:
4182 return SimplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
Zia Ansari394cef82016-12-08 23:27:40 +00004183 case Instruction::FDiv:
4184 return SimplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004185 default:
4186 return SimplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
4187 }
4188}
4189
Duncan Sands7e800d62010-11-14 11:23:23 +00004190Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004191 const SimplifyQuery &Q) {
4192 return ::SimplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
4193}
4194
Michael Zolotukhin4e8598e2015-02-06 20:02:51 +00004195Value *llvm::SimplifyFPBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Daniel Berline8d74dc2017-04-26 04:10:00 +00004196 FastMathFlags FMF, const SimplifyQuery &Q) {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004197 return ::SimplifyFPBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
4198}
4199
Sanjay Patel472cc782016-01-11 22:14:42 +00004200/// Given operands for a CmpInst, see if we can fold the result.
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004201static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004202 const SimplifyQuery &Q, unsigned MaxRecurse) {
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004203 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sandsb8cee002012-03-13 11:42:19 +00004204 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Benjamin Kramerf4ebfa32015-07-10 14:02:02 +00004205 return SimplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
Duncan Sandsf3b1bf12010-11-10 18:23:01 +00004206}
4207
4208Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004209 const SimplifyQuery &Q) {
4210 return ::SimplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
4211}
4212
Michael Ilseman54857292013-02-07 19:26:05 +00004213static bool IsIdempotent(Intrinsic::ID ID) {
4214 switch (ID) {
4215 default: return false;
4216
4217 // Unary idempotent: f(f(x)) = f(x)
4218 case Intrinsic::fabs:
4219 case Intrinsic::floor:
4220 case Intrinsic::ceil:
4221 case Intrinsic::trunc:
4222 case Intrinsic::rint:
4223 case Intrinsic::nearbyint:
Hal Finkel171817e2013-08-07 22:49:12 +00004224 case Intrinsic::round:
Michael Ilseman54857292013-02-07 19:26:05 +00004225 return true;
4226 }
4227}
4228
Peter Collingbourne7dd8dbf2016-04-22 21:18:02 +00004229static Value *SimplifyRelativeLoad(Constant *Ptr, Constant *Offset,
4230 const DataLayout &DL) {
4231 GlobalValue *PtrSym;
4232 APInt PtrOffset;
4233 if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
4234 return nullptr;
4235
4236 Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
4237 Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
4238 Type *Int32PtrTy = Int32Ty->getPointerTo();
4239 Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
4240
4241 auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
4242 if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
4243 return nullptr;
4244
4245 uint64_t OffsetInt = OffsetConstInt->getSExtValue();
4246 if (OffsetInt % 4 != 0)
4247 return nullptr;
4248
4249 Constant *C = ConstantExpr::getGetElementPtr(
4250 Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
4251 ConstantInt::get(Int64Ty, OffsetInt / 4));
4252 Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
4253 if (!Loaded)
4254 return nullptr;
4255
4256 auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
4257 if (!LoadedCE)
4258 return nullptr;
4259
4260 if (LoadedCE->getOpcode() == Instruction::Trunc) {
4261 LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4262 if (!LoadedCE)
4263 return nullptr;
4264 }
4265
4266 if (LoadedCE->getOpcode() != Instruction::Sub)
4267 return nullptr;
4268
4269 auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
4270 if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
4271 return nullptr;
4272 auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
4273
4274 Constant *LoadedRHS = LoadedCE->getOperand(1);
4275 GlobalValue *LoadedRHSSym;
4276 APInt LoadedRHSOffset;
4277 if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
4278 DL) ||
4279 PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
4280 return nullptr;
4281
4282 return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
4283}
4284
David Majnemer17a95aa2016-07-14 06:58:37 +00004285static bool maskIsAllZeroOrUndef(Value *Mask) {
4286 auto *ConstMask = dyn_cast<Constant>(Mask);
4287 if (!ConstMask)
4288 return false;
4289 if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
4290 return true;
4291 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
4292 ++I) {
4293 if (auto *MaskElt = ConstMask->getAggregateElement(I))
4294 if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
4295 continue;
4296 return false;
4297 }
4298 return true;
4299}
4300
Michael Ilseman54857292013-02-07 19:26:05 +00004301template <typename IterTy>
David Majnemer15032582015-05-22 03:56:46 +00004302static Value *SimplifyIntrinsic(Function *F, IterTy ArgBegin, IterTy ArgEnd,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004303 const SimplifyQuery &Q, unsigned MaxRecurse) {
David Majnemer15032582015-05-22 03:56:46 +00004304 Intrinsic::ID IID = F->getIntrinsicID();
4305 unsigned NumOperands = std::distance(ArgBegin, ArgEnd);
Michael Ilseman54857292013-02-07 19:26:05 +00004306
4307 // Unary Ops
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004308 if (NumOperands == 1) {
Matt Arsenault82606662017-01-11 00:57:54 +00004309 // Perform idempotent optimizations
4310 if (IsIdempotent(IID)) {
4311 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin)) {
4312 if (II->getIntrinsicID() == IID)
4313 return II;
4314 }
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004315 }
4316
4317 switch (IID) {
4318 case Intrinsic::fabs: {
4319 if (SignBitMustBeZero(*ArgBegin, Q.TLI))
4320 return *ArgBegin;
Marcello Maggioni0616b5f2017-01-14 07:28:47 +00004321 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004322 }
4323 default:
Matt Arsenault82606662017-01-11 00:57:54 +00004324 return nullptr;
Matt Arsenault1e0edbf2017-01-11 00:33:24 +00004325 }
4326 }
Michael Ilseman54857292013-02-07 19:26:05 +00004327
Matt Arsenault82606662017-01-11 00:57:54 +00004328 // Binary Ops
4329 if (NumOperands == 2) {
4330 Value *LHS = *ArgBegin;
4331 Value *RHS = *(ArgBegin + 1);
4332 Type *ReturnType = F->getReturnType();
4333
4334 switch (IID) {
4335 case Intrinsic::usub_with_overflow:
4336 case Intrinsic::ssub_with_overflow: {
4337 // X - X -> { 0, false }
4338 if (LHS == RHS)
4339 return Constant::getNullValue(ReturnType);
4340
4341 // X - undef -> undef
4342 // undef - X -> undef
4343 if (isa<UndefValue>(LHS) || isa<UndefValue>(RHS))
4344 return UndefValue::get(ReturnType);
4345
4346 return nullptr;
4347 }
4348 case Intrinsic::uadd_with_overflow:
4349 case Intrinsic::sadd_with_overflow: {
4350 // X + undef -> undef
4351 if (isa<UndefValue>(RHS))
4352 return UndefValue::get(ReturnType);
4353
4354 return nullptr;
4355 }
4356 case Intrinsic::umul_with_overflow:
4357 case Intrinsic::smul_with_overflow: {
4358 // X * 0 -> { 0, false }
4359 if (match(RHS, m_Zero()))
4360 return Constant::getNullValue(ReturnType);
4361
4362 // X * undef -> { 0, false }
4363 if (match(RHS, m_Undef()))
4364 return Constant::getNullValue(ReturnType);
4365
4366 return nullptr;
4367 }
4368 case Intrinsic::load_relative: {
4369 Constant *C0 = dyn_cast<Constant>(LHS);
4370 Constant *C1 = dyn_cast<Constant>(RHS);
4371 if (C0 && C1)
4372 return SimplifyRelativeLoad(C0, C1, Q.DL);
4373 return nullptr;
4374 }
4375 default:
4376 return nullptr;
4377 }
4378 }
4379
4380 // Simplify calls to llvm.masked.load.*
4381 switch (IID) {
4382 case Intrinsic::masked_load: {
4383 Value *MaskArg = ArgBegin[2];
4384 Value *PassthruArg = ArgBegin[3];
4385 // If the mask is all zeros or undef, the "passthru" argument is the result.
4386 if (maskIsAllZeroOrUndef(MaskArg))
4387 return PassthruArg;
4388 return nullptr;
4389 }
4390 default:
4391 return nullptr;
4392 }
Michael Ilseman54857292013-02-07 19:26:05 +00004393}
4394
Chandler Carruth9dc35582012-12-28 11:30:55 +00004395template <typename IterTy>
Chandler Carruthf6182152012-12-28 14:23:29 +00004396static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004397 const SimplifyQuery &Q, unsigned MaxRecurse) {
Chandler Carruthf6182152012-12-28 14:23:29 +00004398 Type *Ty = V->getType();
Chandler Carruth9dc35582012-12-28 11:30:55 +00004399 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
4400 Ty = PTy->getElementType();
4401 FunctionType *FTy = cast<FunctionType>(Ty);
4402
Dan Gohman85977e62011-11-04 18:32:42 +00004403 // call undef -> undef
David Majnemerbb53d232016-06-25 07:37:30 +00004404 // call null -> undef
4405 if (isa<UndefValue>(V) || isa<ConstantPointerNull>(V))
Chandler Carruth9dc35582012-12-28 11:30:55 +00004406 return UndefValue::get(FTy->getReturnType());
Dan Gohman85977e62011-11-04 18:32:42 +00004407
Chandler Carruthf6182152012-12-28 14:23:29 +00004408 Function *F = dyn_cast<Function>(V);
4409 if (!F)
Craig Topper9f008862014-04-15 04:59:12 +00004410 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004411
David Majnemer15032582015-05-22 03:56:46 +00004412 if (F->isIntrinsic())
4413 if (Value *Ret = SimplifyIntrinsic(F, ArgBegin, ArgEnd, Q, MaxRecurse))
Michael Ilseman54857292013-02-07 19:26:05 +00004414 return Ret;
4415
Chandler Carruthf6182152012-12-28 14:23:29 +00004416 if (!canConstantFoldCallTo(F))
Craig Topper9f008862014-04-15 04:59:12 +00004417 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004418
4419 SmallVector<Constant *, 4> ConstantArgs;
4420 ConstantArgs.reserve(ArgEnd - ArgBegin);
4421 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
4422 Constant *C = dyn_cast<Constant>(*I);
4423 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00004424 return nullptr;
Chandler Carruthf6182152012-12-28 14:23:29 +00004425 ConstantArgs.push_back(C);
4426 }
4427
4428 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
Dan Gohman85977e62011-11-04 18:32:42 +00004429}
4430
Chandler Carruthf6182152012-12-28 14:23:29 +00004431Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004432 User::op_iterator ArgEnd, const SimplifyQuery &Q) {
4433 return ::SimplifyCall(V, ArgBegin, ArgEnd, Q, RecursionLimit);
4434}
4435
Chandler Carruthf6182152012-12-28 14:23:29 +00004436Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004437 const SimplifyQuery &Q) {
4438 return ::SimplifyCall(V, Args.begin(), Args.end(), Q, RecursionLimit);
Chandler Carruth9dc35582012-12-28 11:30:55 +00004439}
4440
Sanjay Patel472cc782016-01-11 22:14:42 +00004441/// See if we can compute a simplified version of this instruction.
4442/// If not, this returns null.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004443Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00004444 const TargetLibraryInfo *TLI,
Sanjay Patel54656ca2017-02-06 18:26:06 +00004445 const DominatorTree *DT, AssumptionCache *AC,
4446 OptimizationRemarkEmitter *ORE) {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004447 return SimplifyInstruction(I, {DL, TLI, DT, AC, I}, ORE);
4448}
4449
4450Value *llvm::SimplifyInstruction(Instruction *I, const SimplifyQuery &Q,
4451 OptimizationRemarkEmitter *ORE) {
Duncan Sands64e41cf2010-11-17 08:35:29 +00004452 Value *Result;
4453
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004454 switch (I->getOpcode()) {
4455 default:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004456 Result = ConstantFoldInstruction(I, Q.DL, Q.TLI);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004457 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004458 case Instruction::FAdd:
4459 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004460 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004461 break;
Chris Lattner3d9823b2009-11-27 17:42:22 +00004462 case Instruction::Add:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004463 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
4464 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004465 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004466 break;
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004467 case Instruction::FSub:
4468 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004469 I->getFastMathFlags(), Q);
Michael Ilsemanbb6f6912012-12-12 00:27:46 +00004470 break;
Duncan Sands0a2c41682010-12-15 14:07:39 +00004471 case Instruction::Sub:
4472 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
4473 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004474 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
Duncan Sands0a2c41682010-12-15 14:07:39 +00004475 break;
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004476 case Instruction::FMul:
4477 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004478 I->getFastMathFlags(), Q);
Michael Ilsemanbe9137a2012-11-27 00:46:26 +00004479 break;
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004480 case Instruction::Mul:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004481 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsd0eb6d32010-12-21 14:00:22 +00004482 break;
Duncan Sands771e82a2011-01-28 16:51:11 +00004483 case Instruction::SDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004484 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00004485 break;
4486 case Instruction::UDiv:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004487 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands771e82a2011-01-28 16:51:11 +00004488 break;
Frits van Bommelc2549662011-01-29 15:26:31 +00004489 case Instruction::FDiv:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004490 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004491 I->getFastMathFlags(), Q);
Frits van Bommelc2549662011-01-29 15:26:31 +00004492 break;
Duncan Sandsa3e36992011-05-02 16:27:02 +00004493 case Instruction::SRem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004494 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004495 break;
4496 case Instruction::URem:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004497 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004498 break;
4499 case Instruction::FRem:
Mehdi Aminicd3ca6f2015-02-23 18:30:25 +00004500 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004501 I->getFastMathFlags(), Q);
Duncan Sandsa3e36992011-05-02 16:27:02 +00004502 break;
Duncan Sands7f60dc12011-01-14 00:37:45 +00004503 case Instruction::Shl:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004504 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
4505 cast<BinaryOperator>(I)->hasNoSignedWrap(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004506 cast<BinaryOperator>(I)->hasNoUnsignedWrap(), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004507 break;
4508 case Instruction::LShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004509 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004510 cast<BinaryOperator>(I)->isExact(), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004511 break;
4512 case Instruction::AShr:
Chris Lattner9e4aa022011-02-09 17:15:04 +00004513 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004514 cast<BinaryOperator>(I)->isExact(), Q);
Duncan Sands7f60dc12011-01-14 00:37:45 +00004515 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004516 case Instruction::And:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004517 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004518 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004519 case Instruction::Or:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004520 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004521 break;
Duncan Sandsc89ac072010-11-17 18:52:15 +00004522 case Instruction::Xor:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004523 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), Q);
Duncan Sandsc89ac072010-11-17 18:52:15 +00004524 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004525 case Instruction::ICmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004526 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
4527 I->getOperand(0), I->getOperand(1), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004528 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004529 case Instruction::FCmp:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004530 Result =
4531 SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), I->getOperand(0),
4532 I->getOperand(1), I->getFastMathFlags(), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004533 break;
Chris Lattnerc707fa92010-04-20 05:32:14 +00004534 case Instruction::Select:
Duncan Sands64e41cf2010-11-17 08:35:29 +00004535 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004536 I->getOperand(2), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004537 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004538 case Instruction::GetElementPtr: {
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004539 SmallVector<Value *, 8> Ops(I->op_begin(), I->op_end());
Manuel Jacob20c6d5b2016-01-17 22:46:43 +00004540 Result = SimplifyGEPInst(cast<GetElementPtrInst>(I)->getSourceElementType(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004541 Ops, Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004542 break;
Chris Lattner8574aba2009-11-27 00:29:05 +00004543 }
Duncan Sandsfd26a952011-09-05 06:52:48 +00004544 case Instruction::InsertValue: {
4545 InsertValueInst *IV = cast<InsertValueInst>(I);
4546 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
4547 IV->getInsertedValueOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004548 IV->getIndices(), Q);
Duncan Sandsfd26a952011-09-05 06:52:48 +00004549 break;
4550 }
David Majnemer25a796e2015-07-13 01:15:46 +00004551 case Instruction::ExtractValue: {
4552 auto *EVI = cast<ExtractValueInst>(I);
4553 Result = SimplifyExtractValueInst(EVI->getAggregateOperand(),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004554 EVI->getIndices(), Q);
David Majnemer25a796e2015-07-13 01:15:46 +00004555 break;
4556 }
David Majnemer599ca442015-07-13 01:15:53 +00004557 case Instruction::ExtractElement: {
4558 auto *EEI = cast<ExtractElementInst>(I);
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004559 Result = SimplifyExtractElementInst(EEI->getVectorOperand(),
4560 EEI->getIndexOperand(), Q);
David Majnemer599ca442015-07-13 01:15:53 +00004561 break;
4562 }
Zvi Rackover8f460652017-04-03 22:05:30 +00004563 case Instruction::ShuffleVector: {
4564 auto *SVI = cast<ShuffleVectorInst>(I);
4565 Result = SimplifyShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004566 SVI->getMask(), SVI->getType(), Q);
Zvi Rackover8f460652017-04-03 22:05:30 +00004567 break;
4568 }
Duncan Sands4581ddc2010-11-14 13:30:18 +00004569 case Instruction::PHI:
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004570 Result = SimplifyPHINode(cast<PHINode>(I), Q);
Duncan Sands64e41cf2010-11-17 08:35:29 +00004571 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004572 case Instruction::Call: {
4573 CallSite CS(cast<CallInst>(I));
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004574 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(), Q);
Dan Gohman85977e62011-11-04 18:32:42 +00004575 break;
Chandler Carruth9dc35582012-12-28 11:30:55 +00004576 }
David Majnemer6774d612016-07-26 17:58:05 +00004577#define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
4578#include "llvm/IR/Instruction.def"
4579#undef HANDLE_CAST_INST
Daniel Berlin5e3fcb12017-04-26 04:09:56 +00004580 Result =
4581 SimplifyCastInst(I->getOpcode(), I->getOperand(0), I->getType(), Q);
David Majnemera90a6212016-07-26 05:52:29 +00004582 break;
Craig Topper81c03a72017-04-12 22:54:24 +00004583 case Instruction::Alloca:
4584 // No simplifications for Alloca and it can't be constant folded.
4585 Result = nullptr;
4586 break;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004587 }
Duncan Sands64e41cf2010-11-17 08:35:29 +00004588
Hal Finkelf2199b22015-10-23 20:37:08 +00004589 // In general, it is possible for computeKnownBits to determine all bits in a
4590 // value even when the operands are not all constants.
Sanjay Patel8ca30ab2016-11-27 21:07:28 +00004591 if (!Result && I->getType()->isIntOrIntVectorTy()) {
Hal Finkelf2199b22015-10-23 20:37:08 +00004592 unsigned BitWidth = I->getType()->getScalarSizeInBits();
Craig Topperb45eabc2017-04-26 16:39:58 +00004593 KnownBits Known(BitWidth);
4594 computeKnownBits(I, Known, Q.DL, /*Depth*/ 0, Q.AC, I, Q.DT, ORE);
4595 if ((Known.Zero | Known.One).isAllOnesValue())
4596 Result = ConstantInt::get(I->getType(), Known.One);
Hal Finkelf2199b22015-10-23 20:37:08 +00004597 }
4598
Duncan Sands64e41cf2010-11-17 08:35:29 +00004599 /// If called on unreachable code, the above logic may report that the
4600 /// instruction simplified to itself. Make life easier for users by
Duncan Sands019a4182010-12-15 11:02:22 +00004601 /// detecting that case here, returning a safe value instead.
4602 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnerfb7f87d2009-11-10 01:08:51 +00004603}
4604
Sanjay Patelf44bd382016-01-20 18:59:48 +00004605/// \brief Implementation of recursive simplification through an instruction's
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004606/// uses.
Chris Lattner852d6d62009-11-10 22:26:15 +00004607///
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004608/// This is the common implementation of the recursive simplification routines.
4609/// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
4610/// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
4611/// instructions to process and attempt to simplify it using
4612/// InstructionSimplify.
4613///
4614/// This routine returns 'true' only when *it* simplifies something. The passed
4615/// in simplified value does not count toward this.
4616static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004617 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004618 const DominatorTree *DT,
4619 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004620 bool Simplified = false;
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004621 SmallSetVector<Instruction *, 8> Worklist;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004622 const DataLayout &DL = I->getModule()->getDataLayout();
Duncan Sands7e800d62010-11-14 11:23:23 +00004623
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004624 // If we have an explicit value to collapse to, do that round of the
4625 // simplification loop by hand initially.
4626 if (SimpleV) {
Chandler Carruthcdf47882014-03-09 03:16:01 +00004627 for (User *U : I->users())
4628 if (U != I)
4629 Worklist.insert(cast<Instruction>(U));
Duncan Sands7e800d62010-11-14 11:23:23 +00004630
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004631 // Replace the instruction with its simplified value.
4632 I->replaceAllUsesWith(SimpleV);
Chris Lattner19eff2a2010-07-15 06:36:08 +00004633
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004634 // Gracefully handle edge cases where the instruction is not wired into any
4635 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004636 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4637 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004638 I->eraseFromParent();
4639 } else {
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004640 Worklist.insert(I);
Chris Lattner852d6d62009-11-10 22:26:15 +00004641 }
Duncan Sands7e800d62010-11-14 11:23:23 +00004642
Chandler Carruth77e8bfb2012-03-24 22:34:26 +00004643 // Note that we must test the size on each iteration, the worklist can grow.
4644 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
4645 I = Worklist[Idx];
Duncan Sands7e800d62010-11-14 11:23:23 +00004646
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004647 // See if this instruction simplifies.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004648 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004649 if (!SimpleV)
4650 continue;
4651
4652 Simplified = true;
4653
4654 // Stash away all the uses of the old instruction so we can check them for
4655 // recursive simplifications after a RAUW. This is cheaper than checking all
4656 // uses of To on the recursive step in most cases.
Chandler Carruthcdf47882014-03-09 03:16:01 +00004657 for (User *U : I->users())
4658 Worklist.insert(cast<Instruction>(U));
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004659
4660 // Replace the instruction with its simplified value.
4661 I->replaceAllUsesWith(SimpleV);
4662
4663 // Gracefully handle edge cases where the instruction is not wired into any
4664 // parent block.
David Majnemer909793f2016-08-04 04:24:02 +00004665 if (I->getParent() && !I->isEHPad() && !isa<TerminatorInst>(I) &&
4666 !I->mayHaveSideEffects())
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004667 I->eraseFromParent();
4668 }
4669 return Simplified;
4670}
4671
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004672bool llvm::recursivelySimplifyInstruction(Instruction *I,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004673 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004674 const DominatorTree *DT,
4675 AssumptionCache *AC) {
4676 return replaceAndRecursivelySimplifyImpl(I, nullptr, TLI, DT, AC);
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004677}
4678
4679bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004680 const TargetLibraryInfo *TLI,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004681 const DominatorTree *DT,
4682 AssumptionCache *AC) {
Chandler Carruthcf1b5852012-03-24 21:11:24 +00004683 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
4684 assert(SimpleV && "Must provide a simplified value.");
Daniel Jasperaec2fa32016-12-19 08:22:17 +00004685 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC);
Chris Lattner852d6d62009-11-10 22:26:15 +00004686}