blob: 6366e3621ae84ff2b4367ac01c05e85bc5810c9a [file] [log] [blame]
Nick Lewycky97756402014-09-01 05:17:15 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
Misha Brukman01808ca2005-04-21 21:13:18 +00002//
Chris Lattnerd934c702004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman01808ca2005-04-21 21:13:18 +00007//
Chris Lattnerd934c702004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
Dan Gohmanef2ae2c2009-07-25 16:18:07 +000017// can handle. We only create one SCEV of a particular shape, so
18// pointer-comparisons for equality are legal.
Chris Lattnerd934c702004-04-02 20:23:17 +000019//
20// One important aspect of the SCEV objects is that they are never cyclic, even
21// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
22// the PHI node is one of the idioms that we can represent (e.g., a polynomial
23// recurrence) then we represent it directly as a recurrence node, otherwise we
24// represent it as a SCEVUnknown node.
25//
26// In addition to being able to represent expressions of various types, we also
27// have folders that are used to build the *canonical* representation for a
28// particular expression. These folders are capable of using a variety of
29// rewrite rules to simplify the expressions.
Misha Brukman01808ca2005-04-21 21:13:18 +000030//
Chris Lattnerd934c702004-04-02 20:23:17 +000031// Once the folders are defined, we can implement the more interesting
32// higher-level code, such as the code that recognizes PHI nodes of various
33// types, computes the execution count of a loop, etc.
34//
Chris Lattnerd934c702004-04-02 20:23:17 +000035// TODO: We should use these routines and value representations to implement
36// dependence analysis!
37//
38//===----------------------------------------------------------------------===//
39//
40// There are several good references for the techniques used in this analysis.
41//
42// Chains of recurrences -- a method to expedite the evaluation
43// of closed-form functions
44// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
45//
46// On computational properties of chains of recurrences
47// Eugene V. Zima
48//
49// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
50// Robert A. van Engelen
51//
52// Efficient Symbolic Analysis for Optimizing Compilers
53// Robert A. van Engelen
54//
55// Using the chains of recurrences algebra for data dependence testing and
56// induction variable substitution
57// MS Thesis, Johnie Birch
58//
59//===----------------------------------------------------------------------===//
60
Chandler Carruthed0881b2012-12-03 16:50:05 +000061#include "llvm/Analysis/ScalarEvolution.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000062#include "llvm/ADT/Optional.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000063#include "llvm/ADT/STLExtras.h"
64#include "llvm/ADT/SmallPtrSet.h"
65#include "llvm/ADT/Statistic.h"
Chandler Carruth66b31302015-01-04 12:03:27 +000066#include "llvm/Analysis/AssumptionCache.h"
John Criswellfe5f33b2005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Duncan Sandsd06f50e2010-11-17 04:18:45 +000068#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattnerd934c702004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000070#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000071#include "llvm/Analysis/TargetLibraryInfo.h"
Dan Gohman1ee696d2009-06-16 19:52:01 +000072#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000073#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000074#include "llvm/IR/Constants.h"
75#include "llvm/IR/DataLayout.h"
76#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000077#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000078#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000079#include "llvm/IR/GlobalAlias.h"
80#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000081#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000082#include "llvm/IR/Instructions.h"
83#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000084#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000085#include "llvm/IR/Operator.h"
Sanjoy Dasc88f5d32015-10-28 21:27:14 +000086#include "llvm/IR/PatternMatch.h"
Chris Lattner996795b2006-06-28 23:17:24 +000087#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000088#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000089#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000090#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000091#include "llvm/Support/raw_ostream.h"
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +000092#include "llvm/Support/SaveAndRestore.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000093#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000094using namespace llvm;
95
Chandler Carruthf1221bd2014-04-22 02:48:03 +000096#define DEBUG_TYPE "scalar-evolution"
97
Chris Lattner57ef9422006-12-19 22:30:33 +000098STATISTIC(NumArrayLenItCounts,
99 "Number of trip counts computed with array length");
100STATISTIC(NumTripCountsComputed,
101 "Number of loops with predictable loop counts");
102STATISTIC(NumTripCountsNotComputed,
103 "Number of loops without predictable loop counts");
104STATISTIC(NumBruteForceTripCountsComputed,
105 "Number of loops with trip counts computed by force");
106
Dan Gohmand78c4002008-05-13 00:00:25 +0000107static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000108MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
109 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000110 "symbolically execute a constant "
111 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000112 cl::init(100));
113
Benjamin Kramer214935e2012-10-26 17:31:32 +0000114// FIXME: Enable this with XDEBUG when the test suite is clean.
115static cl::opt<bool>
116VerifySCEV("verify-scev",
117 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
Wei Mia49559b2016-02-04 01:27:38 +0000118static cl::opt<bool>
119 VerifySCEVMap("verify-scev-maps",
120 cl::desc("Verify no dangling value in ScalarEvolution's"
121 "ExprValueMap (slow)"));
Benjamin Kramer214935e2012-10-26 17:31:32 +0000122
Chris Lattnerd934c702004-04-02 20:23:17 +0000123//===----------------------------------------------------------------------===//
124// SCEV class definitions
125//===----------------------------------------------------------------------===//
126
127//===----------------------------------------------------------------------===//
128// Implementation of the SCEV class.
129//
Dan Gohman3423e722009-06-30 20:13:32 +0000130
Davide Italiano2071f4c2015-10-25 19:55:24 +0000131LLVM_DUMP_METHOD
132void SCEV::dump() const {
133 print(dbgs());
134 dbgs() << '\n';
135}
136
Dan Gohman534749b2010-11-17 22:27:42 +0000137void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000138 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000139 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000140 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000141 return;
142 case scTruncate: {
143 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
144 const SCEV *Op = Trunc->getOperand();
145 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
146 << *Trunc->getType() << ")";
147 return;
148 }
149 case scZeroExtend: {
150 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
151 const SCEV *Op = ZExt->getOperand();
152 OS << "(zext " << *Op->getType() << " " << *Op << " to "
153 << *ZExt->getType() << ")";
154 return;
155 }
156 case scSignExtend: {
157 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
158 const SCEV *Op = SExt->getOperand();
159 OS << "(sext " << *Op->getType() << " " << *Op << " to "
160 << *SExt->getType() << ")";
161 return;
162 }
163 case scAddRecExpr: {
164 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
165 OS << "{" << *AR->getOperand(0);
166 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
167 OS << ",+," << *AR->getOperand(i);
168 OS << "}<";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000169 if (AR->hasNoUnsignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000170 OS << "nuw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000171 if (AR->hasNoSignedWrap())
Chris Lattnera337f5e2011-01-09 02:16:18 +0000172 OS << "nsw><";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000173 if (AR->hasNoSelfWrap() &&
Andrew Trick8b55b732011-03-14 16:50:06 +0000174 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
175 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000176 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000177 OS << ">";
178 return;
179 }
180 case scAddExpr:
181 case scMulExpr:
182 case scUMaxExpr:
183 case scSMaxExpr: {
184 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000185 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000186 switch (NAry->getSCEVType()) {
187 case scAddExpr: OpStr = " + "; break;
188 case scMulExpr: OpStr = " * "; break;
189 case scUMaxExpr: OpStr = " umax "; break;
190 case scSMaxExpr: OpStr = " smax "; break;
191 }
192 OS << "(";
193 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
194 I != E; ++I) {
195 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000196 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000197 OS << OpStr;
198 }
199 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000200 switch (NAry->getSCEVType()) {
201 case scAddExpr:
202 case scMulExpr:
Sanjoy Das76c48e02016-02-04 18:21:54 +0000203 if (NAry->hasNoUnsignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000204 OS << "<nuw>";
Sanjoy Das76c48e02016-02-04 18:21:54 +0000205 if (NAry->hasNoSignedWrap())
Andrew Trickd912a5b2011-11-29 02:06:35 +0000206 OS << "<nsw>";
207 }
Dan Gohman534749b2010-11-17 22:27:42 +0000208 return;
209 }
210 case scUDivExpr: {
211 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
212 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
213 return;
214 }
215 case scUnknown: {
216 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000217 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000218 if (U->isSizeOf(AllocTy)) {
219 OS << "sizeof(" << *AllocTy << ")";
220 return;
221 }
222 if (U->isAlignOf(AllocTy)) {
223 OS << "alignof(" << *AllocTy << ")";
224 return;
225 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000226
Chris Lattner229907c2011-07-18 04:54:35 +0000227 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000228 Constant *FieldNo;
229 if (U->isOffsetOf(CTy, FieldNo)) {
230 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000231 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000232 OS << ")";
233 return;
234 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000235
Dan Gohman534749b2010-11-17 22:27:42 +0000236 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000237 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000238 return;
239 }
240 case scCouldNotCompute:
241 OS << "***COULDNOTCOMPUTE***";
242 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000243 }
244 llvm_unreachable("Unknown SCEV kind!");
245}
246
Chris Lattner229907c2011-07-18 04:54:35 +0000247Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000248 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000249 case scConstant:
250 return cast<SCEVConstant>(this)->getType();
251 case scTruncate:
252 case scZeroExtend:
253 case scSignExtend:
254 return cast<SCEVCastExpr>(this)->getType();
255 case scAddRecExpr:
256 case scMulExpr:
257 case scUMaxExpr:
258 case scSMaxExpr:
259 return cast<SCEVNAryExpr>(this)->getType();
260 case scAddExpr:
261 return cast<SCEVAddExpr>(this)->getType();
262 case scUDivExpr:
263 return cast<SCEVUDivExpr>(this)->getType();
264 case scUnknown:
265 return cast<SCEVUnknown>(this)->getType();
266 case scCouldNotCompute:
267 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000268 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000269 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000270}
271
Dan Gohmanbe928e32008-06-18 16:23:07 +0000272bool SCEV::isZero() const {
273 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
274 return SC->getValue()->isZero();
275 return false;
276}
277
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000278bool SCEV::isOne() const {
279 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
280 return SC->getValue()->isOne();
281 return false;
282}
Chris Lattnerd934c702004-04-02 20:23:17 +0000283
Dan Gohman18a96bb2009-06-24 00:30:26 +0000284bool SCEV::isAllOnesValue() const {
285 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
286 return SC->getValue()->isAllOnesValue();
287 return false;
288}
289
Andrew Trick881a7762012-01-07 00:27:31 +0000290/// isNonConstantNegative - Return true if the specified scev is negated, but
291/// not a constant.
292bool SCEV::isNonConstantNegative() const {
293 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
294 if (!Mul) return false;
295
296 // If there is a constant factor, it will be first.
297 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
298 if (!SC) return false;
299
300 // Return true if the value is negative, this matches things like (-42 * V).
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000301 return SC->getAPInt().isNegative();
Andrew Trick881a7762012-01-07 00:27:31 +0000302}
303
Owen Anderson04052ec2009-06-22 21:57:23 +0000304SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000305 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000306
Chris Lattnerd934c702004-04-02 20:23:17 +0000307bool SCEVCouldNotCompute::classof(const SCEV *S) {
308 return S->getSCEVType() == scCouldNotCompute;
309}
310
Dan Gohmanaf752342009-07-07 17:06:11 +0000311const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000312 FoldingSetNodeID ID;
313 ID.AddInteger(scConstant);
314 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000315 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000316 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000317 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000318 UniqueSCEVs.InsertNode(S, IP);
319 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000320}
Chris Lattnerd934c702004-04-02 20:23:17 +0000321
Nick Lewycky31eaca52014-01-27 10:04:03 +0000322const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000323 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000324}
325
Dan Gohmanaf752342009-07-07 17:06:11 +0000326const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000327ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
328 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000329 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000330}
331
Dan Gohman24ceda82010-06-18 19:54:20 +0000332SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000333 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000334 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000335
Dan Gohman24ceda82010-06-18 19:54:20 +0000336SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000337 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000338 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000339 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
340 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000341 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000342}
Chris Lattnerd934c702004-04-02 20:23:17 +0000343
Dan Gohman24ceda82010-06-18 19:54:20 +0000344SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000345 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000346 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
348 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000349 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000350}
351
Dan Gohman24ceda82010-06-18 19:54:20 +0000352SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000353 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000354 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000355 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
356 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000357 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000358}
359
Dan Gohman7cac9572010-08-02 23:49:30 +0000360void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000361 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000362 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000363
364 // Remove this SCEVUnknown from the uniquing map.
365 SE->UniqueSCEVs.RemoveNode(this);
366
367 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000368 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000369}
370
371void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000372 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000373 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000374
375 // Remove this SCEVUnknown from the uniquing map.
376 SE->UniqueSCEVs.RemoveNode(this);
377
378 // Update this SCEVUnknown to point to the new value. This is needed
379 // because there may still be outstanding SCEVs which still point to
380 // this SCEVUnknown.
381 setValPtr(New);
382}
383
Chris Lattner229907c2011-07-18 04:54:35 +0000384bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000385 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000386 if (VCE->getOpcode() == Instruction::PtrToInt)
387 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000388 if (CE->getOpcode() == Instruction::GetElementPtr &&
389 CE->getOperand(0)->isNullValue() &&
390 CE->getNumOperands() == 2)
391 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
392 if (CI->isOne()) {
393 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
394 ->getElementType();
395 return true;
396 }
Dan Gohmancf913832010-01-28 02:15:55 +0000397
398 return false;
399}
400
Chris Lattner229907c2011-07-18 04:54:35 +0000401bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000402 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000403 if (VCE->getOpcode() == Instruction::PtrToInt)
404 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000405 if (CE->getOpcode() == Instruction::GetElementPtr &&
406 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000407 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000408 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000409 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000410 if (!STy->isPacked() &&
411 CE->getNumOperands() == 3 &&
412 CE->getOperand(1)->isNullValue()) {
413 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
414 if (CI->isOne() &&
415 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000416 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000417 AllocTy = STy->getElementType(1);
418 return true;
419 }
420 }
421 }
Dan Gohmancf913832010-01-28 02:15:55 +0000422
423 return false;
424}
425
Chris Lattner229907c2011-07-18 04:54:35 +0000426bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000427 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000428 if (VCE->getOpcode() == Instruction::PtrToInt)
429 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
430 if (CE->getOpcode() == Instruction::GetElementPtr &&
431 CE->getNumOperands() == 3 &&
432 CE->getOperand(0)->isNullValue() &&
433 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000434 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000435 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
436 // Ignore vector types here so that ScalarEvolutionExpander doesn't
437 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000438 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000439 CTy = Ty;
440 FieldNo = CE->getOperand(2);
441 return true;
442 }
443 }
444
445 return false;
446}
447
Chris Lattnereb3e8402004-06-20 06:23:15 +0000448//===----------------------------------------------------------------------===//
449// SCEV Utilities
450//===----------------------------------------------------------------------===//
451
452namespace {
Sanjoy Das7881abd2015-12-08 04:32:51 +0000453/// SCEVComplexityCompare - Return true if the complexity of the LHS is less
454/// than the complexity of the RHS. This comparator is used to canonicalize
455/// expressions.
456class SCEVComplexityCompare {
457 const LoopInfo *const LI;
458public:
459 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000460
Sanjoy Das7881abd2015-12-08 04:32:51 +0000461 // Return true or false if LHS is less than, or at least RHS, respectively.
462 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
463 return compare(LHS, RHS) < 0;
464 }
Dan Gohman27065672010-08-27 15:26:01 +0000465
Sanjoy Das7881abd2015-12-08 04:32:51 +0000466 // Return negative, zero, or positive, if LHS is less than, equal to, or
467 // greater than RHS, respectively. A three-way result allows recursive
468 // comparisons to be more efficient.
469 int compare(const SCEV *LHS, const SCEV *RHS) const {
470 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
471 if (LHS == RHS)
472 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000473
Sanjoy Das7881abd2015-12-08 04:32:51 +0000474 // Primarily, sort the SCEVs by their getSCEVType().
475 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
476 if (LType != RType)
477 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000478
Sanjoy Das7881abd2015-12-08 04:32:51 +0000479 // Aside from the getSCEVType() ordering, the particular ordering
480 // isn't very important except that it's beneficial to be consistent,
481 // so that (a + b) and (b + a) don't end up as different expressions.
482 switch (static_cast<SCEVTypes>(LType)) {
483 case scUnknown: {
484 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
485 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000486
Sanjoy Das7881abd2015-12-08 04:32:51 +0000487 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
488 // not as complete as it could be.
489 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000490
Sanjoy Das7881abd2015-12-08 04:32:51 +0000491 // Order pointer values after integer values. This helps SCEVExpander
492 // form GEPs.
493 bool LIsPointer = LV->getType()->isPointerTy(),
494 RIsPointer = RV->getType()->isPointerTy();
495 if (LIsPointer != RIsPointer)
496 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000497
Sanjoy Das7881abd2015-12-08 04:32:51 +0000498 // Compare getValueID values.
499 unsigned LID = LV->getValueID(),
500 RID = RV->getValueID();
501 if (LID != RID)
502 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000503
Sanjoy Das7881abd2015-12-08 04:32:51 +0000504 // Sort arguments by their position.
505 if (const Argument *LA = dyn_cast<Argument>(LV)) {
506 const Argument *RA = cast<Argument>(RV);
507 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
508 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000509 }
510
Sanjoy Das7881abd2015-12-08 04:32:51 +0000511 // For instructions, compare their loop depth, and their operand
512 // count. This is pretty loose.
513 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
514 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000515
Sanjoy Das7881abd2015-12-08 04:32:51 +0000516 // Compare loop depths.
517 const BasicBlock *LParent = LInst->getParent(),
518 *RParent = RInst->getParent();
519 if (LParent != RParent) {
520 unsigned LDepth = LI->getLoopDepth(LParent),
521 RDepth = LI->getLoopDepth(RParent);
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000523 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000524 }
Dan Gohman27065672010-08-27 15:26:01 +0000525
Sanjoy Das7881abd2015-12-08 04:32:51 +0000526 // Compare the number of operands.
527 unsigned LNumOps = LInst->getNumOperands(),
528 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000529 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000530 }
531
Sanjoy Das7881abd2015-12-08 04:32:51 +0000532 return 0;
533 }
Dan Gohman27065672010-08-27 15:26:01 +0000534
Sanjoy Das7881abd2015-12-08 04:32:51 +0000535 case scConstant: {
536 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
537 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
538
539 // Compare constant values.
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000540 const APInt &LA = LC->getAPInt();
541 const APInt &RA = RC->getAPInt();
Sanjoy Das7881abd2015-12-08 04:32:51 +0000542 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
543 if (LBitWidth != RBitWidth)
544 return (int)LBitWidth - (int)RBitWidth;
545 return LA.ult(RA) ? -1 : 1;
546 }
547
548 case scAddRecExpr: {
549 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
550 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
551
552 // Compare addrec loop depths.
553 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
554 if (LLoop != RLoop) {
555 unsigned LDepth = LLoop->getLoopDepth(),
556 RDepth = RLoop->getLoopDepth();
557 if (LDepth != RDepth)
558 return (int)LDepth - (int)RDepth;
559 }
560
561 // Addrec complexity grows with operand count.
562 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
563 if (LNumOps != RNumOps)
564 return (int)LNumOps - (int)RNumOps;
565
566 // Lexicographically compare.
567 for (unsigned i = 0; i != LNumOps; ++i) {
568 long X = compare(LA->getOperand(i), RA->getOperand(i));
Dan Gohman27065672010-08-27 15:26:01 +0000569 if (X != 0)
570 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000571 }
572
Sanjoy Das7881abd2015-12-08 04:32:51 +0000573 return 0;
Chris Lattnereb3e8402004-06-20 06:23:15 +0000574 }
Sanjoy Das7881abd2015-12-08 04:32:51 +0000575
576 case scAddExpr:
577 case scMulExpr:
578 case scSMaxExpr:
579 case scUMaxExpr: {
580 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
581 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
582
583 // Lexicographically compare n-ary expressions.
584 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
585 if (LNumOps != RNumOps)
586 return (int)LNumOps - (int)RNumOps;
587
588 for (unsigned i = 0; i != LNumOps; ++i) {
589 if (i >= RNumOps)
590 return 1;
591 long X = compare(LC->getOperand(i), RC->getOperand(i));
592 if (X != 0)
593 return X;
594 }
595 return (int)LNumOps - (int)RNumOps;
596 }
597
598 case scUDivExpr: {
599 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
600 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
601
602 // Lexicographically compare udiv expressions.
603 long X = compare(LC->getLHS(), RC->getLHS());
604 if (X != 0)
605 return X;
606 return compare(LC->getRHS(), RC->getRHS());
607 }
608
609 case scTruncate:
610 case scZeroExtend:
611 case scSignExtend: {
612 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
613 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
614
615 // Compare cast expressions by operand.
616 return compare(LC->getOperand(), RC->getOperand());
617 }
618
619 case scCouldNotCompute:
620 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
621 }
622 llvm_unreachable("Unknown SCEV kind!");
623 }
624};
625} // end anonymous namespace
Chris Lattnereb3e8402004-06-20 06:23:15 +0000626
627/// GroupByComplexity - Given a list of SCEV objects, order them by their
628/// complexity, and group objects of the same complexity together by value.
629/// When this routine is finished, we know that any duplicates in the vector are
630/// consecutive and that complexity is monotonically increasing.
631///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000632/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000633/// results from this routine. In other words, we don't want the results of
634/// this to depend on where the addresses of various SCEV objects happened to
635/// land in memory.
636///
Dan Gohmanaf752342009-07-07 17:06:11 +0000637static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000638 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000639 if (Ops.size() < 2) return; // Noop
640 if (Ops.size() == 2) {
641 // This is the common case, which also happens to be trivially simple.
642 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000643 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
644 if (SCEVComplexityCompare(LI)(RHS, LHS))
645 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000646 return;
647 }
648
Dan Gohman24ceda82010-06-18 19:54:20 +0000649 // Do the rough sort by complexity.
650 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
651
652 // Now that we are sorted by complexity, group elements of the same
653 // complexity. Note that this is, at worst, N^2, but the vector is likely to
654 // be extremely short in practice. Note that we take this approach because we
655 // do not want to depend on the addresses of the objects we are grouping.
656 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
657 const SCEV *S = Ops[i];
658 unsigned Complexity = S->getSCEVType();
659
660 // If there are any objects of the same complexity and same value as this
661 // one, group them.
662 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
663 if (Ops[j] == S) { // Found a duplicate.
664 // Move it to immediately after i'th element.
665 std::swap(Ops[i+1], Ops[j]);
666 ++i; // no need to rescan it.
667 if (i == e-2) return; // Done!
668 }
669 }
670 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000671}
672
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000673// Returns the size of the SCEV S.
674static inline int sizeOfSCEV(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +0000675 struct FindSCEVSize {
676 int Size;
677 FindSCEVSize() : Size(0) {}
678
679 bool follow(const SCEV *S) {
680 ++Size;
681 // Keep looking at all operands of S.
682 return true;
683 }
684 bool isDone() const {
685 return false;
686 }
687 };
688
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000689 FindSCEVSize F;
690 SCEVTraversal<FindSCEVSize> ST(F);
691 ST.visitAll(S);
692 return F.Size;
693}
694
695namespace {
696
David Majnemer4e879362014-12-14 09:12:33 +0000697struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000698public:
699 // Computes the Quotient and Remainder of the division of Numerator by
700 // Denominator.
701 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
702 const SCEV *Denominator, const SCEV **Quotient,
703 const SCEV **Remainder) {
704 assert(Numerator && Denominator && "Uninitialized SCEV");
705
David Majnemer4e879362014-12-14 09:12:33 +0000706 SCEVDivision D(SE, Numerator, Denominator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000707
708 // Check for the trivial case here to avoid having to check for it in the
709 // rest of the code.
710 if (Numerator == Denominator) {
711 *Quotient = D.One;
712 *Remainder = D.Zero;
713 return;
714 }
715
716 if (Numerator->isZero()) {
717 *Quotient = D.Zero;
718 *Remainder = D.Zero;
719 return;
720 }
721
Brendon Cahoona57cc8b2015-04-20 16:03:28 +0000722 // A simple case when N/1. The quotient is N.
723 if (Denominator->isOne()) {
724 *Quotient = Numerator;
725 *Remainder = D.Zero;
726 return;
727 }
728
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000729 // Split the Denominator when it is a product.
730 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
731 const SCEV *Q, *R;
732 *Quotient = Numerator;
733 for (const SCEV *Op : T->operands()) {
734 divide(SE, *Quotient, Op, &Q, &R);
735 *Quotient = Q;
736
737 // Bail out when the Numerator is not divisible by one of the terms of
738 // the Denominator.
739 if (!R->isZero()) {
740 *Quotient = D.Zero;
741 *Remainder = Numerator;
742 return;
743 }
744 }
745 *Remainder = D.Zero;
746 return;
747 }
748
749 D.visit(Numerator);
750 *Quotient = D.Quotient;
751 *Remainder = D.Remainder;
752 }
753
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000754 // Except in the trivial case described above, we do not know how to divide
755 // Expr by Denominator for the following functions with empty implementation.
756 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
757 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
758 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
759 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
760 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
761 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
762 void visitUnknown(const SCEVUnknown *Numerator) {}
763 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
764
David Majnemer4e879362014-12-14 09:12:33 +0000765 void visitConstant(const SCEVConstant *Numerator) {
766 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +0000767 APInt NumeratorVal = Numerator->getAPInt();
768 APInt DenominatorVal = D->getAPInt();
David Majnemer4e879362014-12-14 09:12:33 +0000769 uint32_t NumeratorBW = NumeratorVal.getBitWidth();
770 uint32_t DenominatorBW = DenominatorVal.getBitWidth();
771
772 if (NumeratorBW > DenominatorBW)
773 DenominatorVal = DenominatorVal.sext(NumeratorBW);
774 else if (NumeratorBW < DenominatorBW)
775 NumeratorVal = NumeratorVal.sext(DenominatorBW);
776
777 APInt QuotientVal(NumeratorVal.getBitWidth(), 0);
778 APInt RemainderVal(NumeratorVal.getBitWidth(), 0);
779 APInt::sdivrem(NumeratorVal, DenominatorVal, QuotientVal, RemainderVal);
780 Quotient = SE.getConstant(QuotientVal);
781 Remainder = SE.getConstant(RemainderVal);
782 return;
783 }
784 }
785
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000786 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
787 const SCEV *StartQ, *StartR, *StepQ, *StepR;
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000788 if (!Numerator->isAffine())
789 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000790 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
791 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
Brendon Cahoonf9751ad2015-04-22 15:06:40 +0000792 // Bail out if the types do not match.
793 Type *Ty = Denominator->getType();
794 if (Ty != StartQ->getType() || Ty != StartR->getType() ||
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000795 Ty != StepQ->getType() || Ty != StepR->getType())
796 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000797 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
798 Numerator->getNoWrapFlags());
799 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
800 Numerator->getNoWrapFlags());
801 }
802
803 void visitAddExpr(const SCEVAddExpr *Numerator) {
804 SmallVector<const SCEV *, 2> Qs, Rs;
805 Type *Ty = Denominator->getType();
806
807 for (const SCEV *Op : Numerator->operands()) {
808 const SCEV *Q, *R;
809 divide(SE, Op, Denominator, &Q, &R);
810
811 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000812 if (Ty != Q->getType() || Ty != R->getType())
813 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000814
815 Qs.push_back(Q);
816 Rs.push_back(R);
817 }
818
819 if (Qs.size() == 1) {
820 Quotient = Qs[0];
821 Remainder = Rs[0];
822 return;
823 }
824
825 Quotient = SE.getAddExpr(Qs);
826 Remainder = SE.getAddExpr(Rs);
827 }
828
829 void visitMulExpr(const SCEVMulExpr *Numerator) {
830 SmallVector<const SCEV *, 2> Qs;
831 Type *Ty = Denominator->getType();
832
833 bool FoundDenominatorTerm = false;
834 for (const SCEV *Op : Numerator->operands()) {
835 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000836 if (Ty != Op->getType())
837 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000838
839 if (FoundDenominatorTerm) {
840 Qs.push_back(Op);
841 continue;
842 }
843
844 // Check whether Denominator divides one of the product operands.
845 const SCEV *Q, *R;
846 divide(SE, Op, Denominator, &Q, &R);
847 if (!R->isZero()) {
848 Qs.push_back(Op);
849 continue;
850 }
851
852 // Bail out if types do not match.
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000853 if (Ty != Q->getType())
854 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000855
856 FoundDenominatorTerm = true;
857 Qs.push_back(Q);
858 }
859
860 if (FoundDenominatorTerm) {
861 Remainder = Zero;
862 if (Qs.size() == 1)
863 Quotient = Qs[0];
864 else
865 Quotient = SE.getMulExpr(Qs);
866 return;
867 }
868
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000869 if (!isa<SCEVUnknown>(Denominator))
870 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000871
872 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
873 ValueToValueMap RewriteMap;
874 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
875 cast<SCEVConstant>(Zero)->getValue();
876 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
877
878 if (Remainder->isZero()) {
879 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
880 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
881 cast<SCEVConstant>(One)->getValue();
882 Quotient =
883 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
884 return;
885 }
886
887 // Quotient is (Numerator - Remainder) divided by Denominator.
888 const SCEV *Q, *R;
889 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000890 // This SCEV does not seem to simplify: fail the division here.
891 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator))
892 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000893 divide(SE, Diff, Denominator, &Q, &R);
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000894 if (R != Zero)
895 return cannotDivide(Numerator);
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000896 Quotient = Q;
897 }
898
899private:
David Majnemer5d2670c2014-11-17 11:27:45 +0000900 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator,
901 const SCEV *Denominator)
902 : SE(S), Denominator(Denominator) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +0000903 Zero = SE.getZero(Denominator->getType());
904 One = SE.getOne(Denominator->getType());
David Majnemer5d2670c2014-11-17 11:27:45 +0000905
Matthew Simpsonddb4d972015-09-10 18:12:47 +0000906 // We generally do not know how to divide Expr by Denominator. We
907 // initialize the division to a "cannot divide" state to simplify the rest
908 // of the code.
909 cannotDivide(Numerator);
910 }
911
912 // Convenience function for giving up on the division. We set the quotient to
913 // be equal to zero and the remainder to be equal to the numerator.
914 void cannotDivide(const SCEV *Numerator) {
David Majnemer5d2670c2014-11-17 11:27:45 +0000915 Quotient = Zero;
916 Remainder = Numerator;
917 }
918
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000919 ScalarEvolution &SE;
920 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
David Majnemer32b8ccf2014-11-16 20:35:19 +0000921};
922
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000923}
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000924
Chris Lattnerd934c702004-04-02 20:23:17 +0000925//===----------------------------------------------------------------------===//
926// Simple SCEV method implementations
927//===----------------------------------------------------------------------===//
928
Eli Friedman61f67622008-08-04 23:49:06 +0000929/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000930/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000931static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000932 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000933 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000934 // Handle the simplest case efficiently.
935 if (K == 1)
936 return SE.getTruncateOrZeroExtend(It, ResultTy);
937
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000938 // We are using the following formula for BC(It, K):
939 //
940 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
941 //
Eli Friedman61f67622008-08-04 23:49:06 +0000942 // Suppose, W is the bitwidth of the return value. We must be prepared for
943 // overflow. Hence, we must assure that the result of our computation is
944 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
945 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000946 //
Eli Friedman61f67622008-08-04 23:49:06 +0000947 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000948 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000949 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
950 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000951 //
Eli Friedman61f67622008-08-04 23:49:06 +0000952 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000953 //
Eli Friedman61f67622008-08-04 23:49:06 +0000954 // This formula is trivially equivalent to the previous formula. However,
955 // this formula can be implemented much more efficiently. The trick is that
956 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
957 // arithmetic. To do exact division in modular arithmetic, all we have
958 // to do is multiply by the inverse. Therefore, this step can be done at
959 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000960 //
Eli Friedman61f67622008-08-04 23:49:06 +0000961 // The next issue is how to safely do the division by 2^T. The way this
962 // is done is by doing the multiplication step at a width of at least W + T
963 // bits. This way, the bottom W+T bits of the product are accurate. Then,
964 // when we perform the division by 2^T (which is equivalent to a right shift
965 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
966 // truncated out after the division by 2^T.
967 //
968 // In comparison to just directly using the first formula, this technique
969 // is much more efficient; using the first formula requires W * K bits,
970 // but this formula less than W + K bits. Also, the first formula requires
971 // a division step, whereas this formula only requires multiplies and shifts.
972 //
973 // It doesn't matter whether the subtraction step is done in the calculation
974 // width or the input iteration count's width; if the subtraction overflows,
975 // the result must be zero anyway. We prefer here to do it in the width of
976 // the induction variable because it helps a lot for certain cases; CodeGen
977 // isn't smart enough to ignore the overflow, which leads to much less
978 // efficient code if the width of the subtraction is wider than the native
979 // register width.
980 //
981 // (It's possible to not widen at all by pulling out factors of 2 before
982 // the multiplication; for example, K=2 can be calculated as
983 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
984 // extra arithmetic, so it's not an obvious win, and it gets
985 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000986
Eli Friedman61f67622008-08-04 23:49:06 +0000987 // Protection from insane SCEVs; this bound is conservative,
988 // but it probably doesn't matter.
989 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +0000990 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000991
Dan Gohmanb397e1a2009-04-21 01:07:12 +0000992 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000993
Eli Friedman61f67622008-08-04 23:49:06 +0000994 // Calculate K! / 2^T and T; we divide out the factors of two before
995 // multiplying for calculating K! / 2^T to avoid overflow.
996 // Other overflow doesn't matter because we only care about the bottom
997 // W bits of the result.
998 APInt OddFactorial(W, 1);
999 unsigned T = 1;
1000 for (unsigned i = 3; i <= K; ++i) {
1001 APInt Mult(W, i);
1002 unsigned TwoFactors = Mult.countTrailingZeros();
1003 T += TwoFactors;
1004 Mult = Mult.lshr(TwoFactors);
1005 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001006 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001007
Eli Friedman61f67622008-08-04 23:49:06 +00001008 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001009 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001010
Dan Gohman8b0a4192010-03-01 17:49:51 +00001011 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001012 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001013
1014 // Calculate the multiplicative inverse of K! / 2^T;
1015 // this multiplication factor will perform the exact division by
1016 // K! / 2^T.
1017 APInt Mod = APInt::getSignedMinValue(W+1);
1018 APInt MultiplyFactor = OddFactorial.zext(W+1);
1019 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1020 MultiplyFactor = MultiplyFactor.trunc(W);
1021
1022 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001023 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001024 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001025 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001026 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001027 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001028 Dividend = SE.getMulExpr(Dividend,
1029 SE.getTruncateOrZeroExtend(S, CalculationTy));
1030 }
1031
1032 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001033 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001034
1035 // Truncate the result, and divide by K! / 2^T.
1036
1037 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1038 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001039}
1040
Chris Lattnerd934c702004-04-02 20:23:17 +00001041/// evaluateAtIteration - Return the value of this chain of recurrences at
1042/// the specified iteration number. We can evaluate this recurrence by
1043/// multiplying each element in the chain by the binomial coefficient
1044/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1045///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001046/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001047///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001048/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001049///
Dan Gohmanaf752342009-07-07 17:06:11 +00001050const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001051 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001052 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001053 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001054 // The computation is correct in the face of overflow provided that the
1055 // multiplication is performed _after_ the evaluation of the binomial
1056 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001057 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001058 if (isa<SCEVCouldNotCompute>(Coeff))
1059 return Coeff;
1060
1061 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001062 }
1063 return Result;
1064}
1065
Chris Lattnerd934c702004-04-02 20:23:17 +00001066//===----------------------------------------------------------------------===//
1067// SCEV Expression folder implementations
1068//===----------------------------------------------------------------------===//
1069
Dan Gohmanaf752342009-07-07 17:06:11 +00001070const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001071 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001072 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001073 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001074 assert(isSCEVable(Ty) &&
1075 "This is not a conversion to a SCEVable type!");
1076 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001077
Dan Gohman3a302cb2009-07-13 20:50:19 +00001078 FoldingSetNodeID ID;
1079 ID.AddInteger(scTruncate);
1080 ID.AddPointer(Op);
1081 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001082 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001083 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1084
Dan Gohman3423e722009-06-30 20:13:32 +00001085 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001086 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001087 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001088 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001089
Dan Gohman79af8542009-04-22 16:20:48 +00001090 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001091 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001092 return getTruncateExpr(ST->getOperand(), Ty);
1093
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001094 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001095 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001096 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1097
1098 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001099 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001100 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1101
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001102 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
Nick Lewycky2ce28322015-03-20 02:52:23 +00001103 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001104 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1105 SmallVector<const SCEV *, 4> Operands;
1106 bool hasTrunc = false;
1107 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1108 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001109 if (!isa<SCEVCastExpr>(SA->getOperand(i)))
1110 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001111 Operands.push_back(S);
1112 }
1113 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001114 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001115 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001116 }
1117
Nick Lewycky5c901f32011-01-19 18:56:00 +00001118 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
Nick Lewyckybe8af482015-03-20 02:25:00 +00001119 // eliminate all the truncates, or we replace other casts with truncates.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001120 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1121 SmallVector<const SCEV *, 4> Operands;
1122 bool hasTrunc = false;
1123 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1124 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
Nick Lewyckybe8af482015-03-20 02:25:00 +00001125 if (!isa<SCEVCastExpr>(SM->getOperand(i)))
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
Nick Lewycky5c901f32011-01-19 18:56:00 +00001127 Operands.push_back(S);
1128 }
1129 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001130 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001132 }
1133
Dan Gohman5a728c92009-06-18 16:24:47 +00001134 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001135 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001136 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00001137 for (const SCEV *Op : AddRec->operands())
1138 Operands.push_back(getTruncateExpr(Op, Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001139 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001140 }
1141
Dan Gohman89dd42a2010-06-25 18:47:08 +00001142 // The cast wasn't folded; create an explicit cast node. We can reuse
1143 // the existing insert position since if we get here, we won't have
1144 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001145 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1146 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001147 UniqueSCEVs.InsertNode(S, IP);
1148 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001149}
1150
Sanjoy Das4153f472015-02-18 01:47:07 +00001151// Get the limit of a recurrence such that incrementing by Step cannot cause
1152// signed overflow as long as the value of the recurrence within the
1153// loop does not exceed this limit before incrementing.
1154static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
1155 ICmpInst::Predicate *Pred,
1156 ScalarEvolution *SE) {
1157 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1158 if (SE->isKnownPositive(Step)) {
1159 *Pred = ICmpInst::ICMP_SLT;
1160 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1161 SE->getSignedRange(Step).getSignedMax());
1162 }
1163 if (SE->isKnownNegative(Step)) {
1164 *Pred = ICmpInst::ICMP_SGT;
1165 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1166 SE->getSignedRange(Step).getSignedMin());
1167 }
1168 return nullptr;
1169}
1170
1171// Get the limit of a recurrence such that incrementing by Step cannot cause
1172// unsigned overflow as long as the value of the recurrence within the loop does
1173// not exceed this limit before incrementing.
1174static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
1175 ICmpInst::Predicate *Pred,
1176 ScalarEvolution *SE) {
1177 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1178 *Pred = ICmpInst::ICMP_ULT;
1179
1180 return SE->getConstant(APInt::getMinValue(BitWidth) -
1181 SE->getUnsignedRange(Step).getUnsignedMax());
1182}
1183
1184namespace {
1185
1186struct ExtendOpTraitsBase {
1187 typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *);
1188};
1189
1190// Used to make code generic over signed and unsigned overflow.
1191template <typename ExtendOp> struct ExtendOpTraits {
1192 // Members present:
1193 //
1194 // static const SCEV::NoWrapFlags WrapType;
1195 //
1196 // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
1197 //
1198 // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1199 // ICmpInst::Predicate *Pred,
1200 // ScalarEvolution *SE);
1201};
1202
1203template <>
1204struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
1205 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
1206
1207 static const GetExtendExprTy GetExtendExpr;
1208
1209 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1210 ICmpInst::Predicate *Pred,
1211 ScalarEvolution *SE) {
1212 return getSignedOverflowLimitForStep(Step, Pred, SE);
1213 }
1214};
1215
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001216const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001217 SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
1218
1219template <>
1220struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
1221 static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
1222
1223 static const GetExtendExprTy GetExtendExpr;
1224
1225 static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1226 ICmpInst::Predicate *Pred,
1227 ScalarEvolution *SE) {
1228 return getUnsignedOverflowLimitForStep(Step, Pred, SE);
1229 }
1230};
1231
Sanjoy Dasc1065b92015-02-18 08:03:22 +00001232const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
Sanjoy Das4153f472015-02-18 01:47:07 +00001233 SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
Alexander Kornienkof00654e2015-06-23 09:49:53 +00001234}
Sanjoy Das4153f472015-02-18 01:47:07 +00001235
1236// The recurrence AR has been shown to have no signed/unsigned wrap or something
1237// close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
1238// easily prove NSW/NUW for its preincrement or postincrement sibling. This
1239// allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
1240// Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
1241// expression "Step + sext/zext(PreIncAR)" is congruent with
1242// "sext/zext(PostIncAR)"
1243template <typename ExtendOpTy>
1244static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
1245 ScalarEvolution *SE) {
1246 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1247 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1248
1249 const Loop *L = AR->getLoop();
1250 const SCEV *Start = AR->getStart();
1251 const SCEV *Step = AR->getStepRecurrence(*SE);
1252
1253 // Check for a simple looking step prior to loop entry.
1254 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
1255 if (!SA)
1256 return nullptr;
1257
1258 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1259 // subtraction is expensive. For this purpose, perform a quick and dirty
1260 // difference, by checking for Step in the operand list.
1261 SmallVector<const SCEV *, 4> DiffOps;
1262 for (const SCEV *Op : SA->operands())
1263 if (Op != Step)
1264 DiffOps.push_back(Op);
1265
1266 if (DiffOps.size() == SA->getNumOperands())
1267 return nullptr;
1268
1269 // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
1270 // `Step`:
1271
1272 // 1. NSW/NUW flags on the step increment.
Sanjoy Das0714e3e2015-10-23 06:33:47 +00001273 auto PreStartFlags =
1274 ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
1275 const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
Sanjoy Das4153f472015-02-18 01:47:07 +00001276 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1277 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1278
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001279 // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
1280 // "S+X does not sign/unsign-overflow".
Sanjoy Das4153f472015-02-18 01:47:07 +00001281 //
1282
Sanjoy Dasb14010d2015-02-24 01:02:42 +00001283 const SCEV *BECount = SE->getBackedgeTakenCount(L);
1284 if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
1285 !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
Sanjoy Das4153f472015-02-18 01:47:07 +00001286 return PreStart;
1287
1288 // 2. Direct overflow check on the step operation's expression.
1289 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
1290 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
1291 const SCEV *OperandExtendedStart =
1292 SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy),
1293 (SE->*GetExtendExpr)(Step, WideTy));
1294 if ((SE->*GetExtendExpr)(Start, WideTy) == OperandExtendedStart) {
1295 if (PreAR && AR->getNoWrapFlags(WrapType)) {
1296 // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
1297 // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
1298 // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
1299 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(WrapType);
1300 }
1301 return PreStart;
1302 }
1303
1304 // 3. Loop precondition.
1305 ICmpInst::Predicate Pred;
1306 const SCEV *OverflowLimit =
1307 ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
1308
1309 if (OverflowLimit &&
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001310 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
Sanjoy Das4153f472015-02-18 01:47:07 +00001311 return PreStart;
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00001312
Sanjoy Das4153f472015-02-18 01:47:07 +00001313 return nullptr;
1314}
1315
1316// Get the normalized zero or sign extended expression for this AddRec's Start.
1317template <typename ExtendOpTy>
1318static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
1319 ScalarEvolution *SE) {
1320 auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
1321
1322 const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE);
1323 if (!PreStart)
1324 return (SE->*GetExtendExpr)(AR->getStart(), Ty);
1325
1326 return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty),
1327 (SE->*GetExtendExpr)(PreStart, Ty));
1328}
1329
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001330// Try to prove away overflow by looking at "nearby" add recurrences. A
1331// motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
1332// does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
1333//
1334// Formally:
1335//
1336// {S,+,X} == {S-T,+,X} + T
1337// => Ext({S,+,X}) == Ext({S-T,+,X} + T)
1338//
1339// If ({S-T,+,X} + T) does not overflow ... (1)
1340//
1341// RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
1342//
1343// If {S-T,+,X} does not overflow ... (2)
1344//
1345// RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
1346// == {Ext(S-T)+Ext(T),+,Ext(X)}
1347//
1348// If (S-T)+T does not overflow ... (3)
1349//
1350// RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
1351// == {Ext(S),+,Ext(X)} == LHS
1352//
1353// Thus, if (1), (2) and (3) are true for some T, then
1354// Ext({S,+,X}) == {Ext(S),+,Ext(X)}
1355//
1356// (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
1357// does not overflow" restricted to the 0th iteration. Therefore we only need
1358// to check for (1) and (2).
1359//
1360// In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
1361// is `Delta` (defined below).
1362//
1363template <typename ExtendOpTy>
1364bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
1365 const SCEV *Step,
1366 const Loop *L) {
1367 auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
1368
1369 // We restrict `Start` to a constant to prevent SCEV from spending too much
1370 // time here. It is correct (but more expensive) to continue with a
1371 // non-constant `Start` and do a general SCEV subtraction to compute
1372 // `PreStart` below.
1373 //
1374 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
1375 if (!StartC)
1376 return false;
1377
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001378 APInt StartAI = StartC->getAPInt();
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001379
1380 for (unsigned Delta : {-2, -1, 1, 2}) {
1381 const SCEV *PreStart = getConstant(StartAI - Delta);
1382
Sanjoy Das42801102015-10-23 06:57:21 +00001383 FoldingSetNodeID ID;
1384 ID.AddInteger(scAddRecExpr);
1385 ID.AddPointer(PreStart);
1386 ID.AddPointer(Step);
1387 ID.AddPointer(L);
1388 void *IP = nullptr;
1389 const auto *PreAR =
1390 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
1391
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001392 // Give up if we don't already have the add recurrence we need because
1393 // actually constructing an add recurrence is relatively expensive.
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001394 if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
1395 const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
1396 ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1397 const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
1398 DeltaS, &Pred, this);
1399 if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
1400 return true;
1401 }
1402 }
1403
1404 return false;
1405}
1406
Dan Gohmanaf752342009-07-07 17:06:11 +00001407const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001408 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001409 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001410 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001411 assert(isSCEVable(Ty) &&
1412 "This is not a conversion to a SCEVable type!");
1413 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001414
Dan Gohman3423e722009-06-30 20:13:32 +00001415 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001416 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1417 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001418 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001419
Dan Gohman79af8542009-04-22 16:20:48 +00001420 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001421 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001422 return getZeroExtendExpr(SZ->getOperand(), Ty);
1423
Dan Gohman74a0ba12009-07-13 20:55:53 +00001424 // Before doing any expensive analysis, check to see if we've already
1425 // computed a SCEV for this Op and Ty.
1426 FoldingSetNodeID ID;
1427 ID.AddInteger(scZeroExtend);
1428 ID.AddPointer(Op);
1429 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001430 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001431 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1432
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001433 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1434 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1435 // It's possible the bits taken off by the truncate were all zero bits. If
1436 // so, we should be able to simplify this further.
1437 const SCEV *X = ST->getOperand();
1438 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001439 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1440 unsigned NewBits = getTypeSizeInBits(Ty);
1441 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001442 CR.zextOrTrunc(NewBits)))
1443 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001444 }
1445
Dan Gohman76466372009-04-27 20:16:15 +00001446 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001447 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001448 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001449 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001450 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001451 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001452 const SCEV *Start = AR->getStart();
1453 const SCEV *Step = AR->getStepRecurrence(*this);
1454 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1455 const Loop *L = AR->getLoop();
1456
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001457 if (!AR->hasNoUnsignedWrap()) {
1458 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1459 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1460 }
1461
Dan Gohman62ef6a72009-07-25 01:22:26 +00001462 // If we have special knowledge that this addrec won't overflow,
1463 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001464 if (AR->hasNoUnsignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001465 return getAddRecExpr(
1466 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1467 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001468
Dan Gohman76466372009-04-27 20:16:15 +00001469 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1470 // Note that this serves two purposes: It filters out loops that are
1471 // simply not analyzable, and it covers the case where this code is
1472 // being called from within backedge-taken count analysis, such that
1473 // attempting to ask for the backedge-taken count would likely result
1474 // in infinite recursion. In the later case, the analysis code will
1475 // cope with a conservative value, and it will take care to purge
1476 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001477 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001478 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001479 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001480 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001481
1482 // Check whether the backedge-taken count can be losslessly casted to
1483 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001484 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001485 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001486 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001487 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1488 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001489 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001490 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001491 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001492 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1493 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1494 const SCEV *WideMaxBECount =
1495 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001496 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001497 getAddExpr(WideStart,
1498 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001499 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001500 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001501 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1502 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001503 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001504 return getAddRecExpr(
1505 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1506 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001507 }
Dan Gohman76466372009-04-27 20:16:15 +00001508 // Similar to above, only this time treat the step value as signed.
1509 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001510 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001511 getAddExpr(WideStart,
1512 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001513 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001514 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001515 // Cache knowledge of AR NW, which is propagated to this AddRec.
1516 // Negative step causes unsigned wrap, but it still can't self-wrap.
1517 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001518 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001519 return getAddRecExpr(
1520 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1521 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001522 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001523 }
1524
1525 // If the backedge is guarded by a comparison with the pre-inc value
1526 // the addrec is safe. Also, if the entry is guarded by a comparison
1527 // with the start value and the backedge is guarded by a comparison
1528 // with the post-inc value, the addrec is safe.
1529 if (isKnownPositive(Step)) {
1530 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1531 getUnsignedRange(Step).getUnsignedMax());
1532 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001533 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001534 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001535 AR->getPostIncExpr(*this), N))) {
1536 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1537 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001538 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001539 return getAddRecExpr(
1540 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1541 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001542 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001543 } else if (isKnownNegative(Step)) {
1544 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1545 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001546 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1547 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001548 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001549 AR->getPostIncExpr(*this), N))) {
1550 // Cache knowledge of AR NW, which is propagated to this AddRec.
1551 // Negative step causes unsigned wrap, but it still can't self-wrap.
1552 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1553 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001554 return getAddRecExpr(
1555 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1556 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001557 }
Dan Gohman76466372009-04-27 20:16:15 +00001558 }
1559 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001560
1561 if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
1562 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
1563 return getAddRecExpr(
1564 getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this),
1565 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1566 }
Dan Gohman76466372009-04-27 20:16:15 +00001567 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001568
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001569 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
1570 // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001571 if (SA->hasNoUnsignedWrap()) {
Sanjoy Daseeca9f62015-10-22 19:57:38 +00001572 // If the addition does not unsign overflow then we can, by definition,
1573 // commute the zero extension with the addition operation.
1574 SmallVector<const SCEV *, 4> Ops;
1575 for (const auto *Op : SA->operands())
1576 Ops.push_back(getZeroExtendExpr(Op, Ty));
1577 return getAddExpr(Ops, SCEV::FlagNUW);
1578 }
1579 }
1580
Dan Gohman74a0ba12009-07-13 20:55:53 +00001581 // The cast wasn't folded; create an explicit cast node.
1582 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001583 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001584 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1585 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001586 UniqueSCEVs.InsertNode(S, IP);
1587 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001588}
1589
Dan Gohmanaf752342009-07-07 17:06:11 +00001590const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001591 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001592 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001593 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001594 assert(isSCEVable(Ty) &&
1595 "This is not a conversion to a SCEVable type!");
1596 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001597
Dan Gohman3423e722009-06-30 20:13:32 +00001598 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001599 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1600 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001601 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001602
Dan Gohman79af8542009-04-22 16:20:48 +00001603 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001604 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001605 return getSignExtendExpr(SS->getOperand(), Ty);
1606
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001607 // sext(zext(x)) --> zext(x)
1608 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1609 return getZeroExtendExpr(SZ->getOperand(), Ty);
1610
Dan Gohman74a0ba12009-07-13 20:55:53 +00001611 // Before doing any expensive analysis, check to see if we've already
1612 // computed a SCEV for this Op and Ty.
1613 FoldingSetNodeID ID;
1614 ID.AddInteger(scSignExtend);
1615 ID.AddPointer(Op);
1616 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001617 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001618 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1619
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001620 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1621 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1622 // It's possible the bits taken off by the truncate were all sign bits. If
1623 // so, we should be able to simplify this further.
1624 const SCEV *X = ST->getOperand();
1625 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001626 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1627 unsigned NewBits = getTypeSizeInBits(Ty);
1628 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001629 CR.sextOrTrunc(NewBits)))
1630 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001631 }
1632
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001633 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001634 if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001635 if (SA->getNumOperands() == 2) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001636 auto *SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1637 auto *SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001638 if (SMul && SC1) {
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001639 if (auto *SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001640 const APInt &C1 = SC1->getAPInt();
1641 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001642 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001643 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001644 return getAddExpr(getSignExtendExpr(SC1, Ty),
1645 getSignExtendExpr(SMul, Ty));
1646 }
1647 }
1648 }
Sanjoy Dasa060e602015-10-22 19:57:25 +00001649
1650 // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
Sanjoy Das76c48e02016-02-04 18:21:54 +00001651 if (SA->hasNoSignedWrap()) {
Sanjoy Dasa060e602015-10-22 19:57:25 +00001652 // If the addition does not sign overflow then we can, by definition,
1653 // commute the sign extension with the addition operation.
1654 SmallVector<const SCEV *, 4> Ops;
1655 for (const auto *Op : SA->operands())
1656 Ops.push_back(getSignExtendExpr(Op, Ty));
1657 return getAddExpr(Ops, SCEV::FlagNSW);
1658 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001659 }
Dan Gohman76466372009-04-27 20:16:15 +00001660 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001661 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001662 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001663 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001664 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001665 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001666 const SCEV *Start = AR->getStart();
1667 const SCEV *Step = AR->getStepRecurrence(*this);
1668 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1669 const Loop *L = AR->getLoop();
1670
Sanjoy Das724f5cf2016-03-03 18:31:29 +00001671 if (!AR->hasNoSignedWrap()) {
1672 auto NewFlags = proveNoWrapViaConstantRanges(AR);
1673 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(NewFlags);
1674 }
1675
Dan Gohman62ef6a72009-07-25 01:22:26 +00001676 // If we have special knowledge that this addrec won't overflow,
1677 // we don't need to do any further analysis.
Sanjoy Das76c48e02016-02-04 18:21:54 +00001678 if (AR->hasNoSignedWrap())
Sanjoy Das4153f472015-02-18 01:47:07 +00001679 return getAddRecExpr(
1680 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1681 getSignExtendExpr(Step, Ty), L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001682
Dan Gohman76466372009-04-27 20:16:15 +00001683 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1684 // Note that this serves two purposes: It filters out loops that are
1685 // simply not analyzable, and it covers the case where this code is
1686 // being called from within backedge-taken count analysis, such that
1687 // attempting to ask for the backedge-taken count would likely result
1688 // in infinite recursion. In the later case, the analysis code will
1689 // cope with a conservative value, and it will take care to purge
1690 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001691 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001692 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001693 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001694 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001695
1696 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001697 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001698 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001699 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001700 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001701 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1702 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001703 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001704 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001705 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001706 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1707 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1708 const SCEV *WideMaxBECount =
1709 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001710 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001711 getAddExpr(WideStart,
1712 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001713 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001714 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001715 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1716 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001717 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001718 return getAddRecExpr(
1719 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1720 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001721 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001722 // Similar to above, only this time treat the step value as unsigned.
1723 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001724 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001725 getAddExpr(WideStart,
1726 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001727 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001728 if (SAdd == OperandExtendedAdd) {
Sanjoy Dasbf5d8702015-02-09 18:34:55 +00001729 // If AR wraps around then
1730 //
1731 // abs(Step) * MaxBECount > unsigned-max(AR->getType())
1732 // => SAdd != OperandExtendedAdd
1733 //
1734 // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
1735 // (SAdd == OperandExtendedAdd => AR is NW)
1736
1737 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1738
Dan Gohman8c129d72009-07-16 17:34:36 +00001739 // Return the expression with the addrec on the outside.
Sanjoy Das4153f472015-02-18 01:47:07 +00001740 return getAddRecExpr(
1741 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1742 getZeroExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001743 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001744 }
1745
1746 // If the backedge is guarded by a comparison with the pre-inc value
1747 // the addrec is safe. Also, if the entry is guarded by a comparison
1748 // with the start value and the backedge is guarded by a comparison
1749 // with the post-inc value, the addrec is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001750 ICmpInst::Predicate Pred;
Sanjoy Das4153f472015-02-18 01:47:07 +00001751 const SCEV *OverflowLimit =
1752 getSignedOverflowLimitForStep(Step, &Pred, this);
Andrew Trick812276e2011-05-31 21:17:47 +00001753 if (OverflowLimit &&
1754 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1755 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1756 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1757 OverflowLimit)))) {
1758 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1759 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Sanjoy Das4153f472015-02-18 01:47:07 +00001760 return getAddRecExpr(
1761 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1762 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001763 }
1764 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001765 // If Start and Step are constants, check if we can apply this
1766 // transformation:
1767 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
Sanjoy Das1195dbe2015-10-08 03:45:58 +00001768 auto *SC1 = dyn_cast<SCEVConstant>(Start);
1769 auto *SC2 = dyn_cast<SCEVConstant>(Step);
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001770 if (SC1 && SC2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001771 const APInt &C1 = SC1->getAPInt();
1772 const APInt &C2 = SC2->getAPInt();
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001773 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1774 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001775 Start = getSignExtendExpr(Start, Ty);
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00001776 const SCEV *NewAR = getAddRecExpr(getZero(AR->getType()), Step, L,
1777 AR->getNoWrapFlags());
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001778 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1779 }
1780 }
Sanjoy Das9e2c5012015-03-04 22:24:17 +00001781
1782 if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
1783 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1784 return getAddRecExpr(
1785 getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this),
1786 getSignExtendExpr(Step, Ty), L, AR->getNoWrapFlags());
1787 }
Dan Gohman76466372009-04-27 20:16:15 +00001788 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001789
Sanjoy Das11ef6062016-03-03 18:31:23 +00001790 // If the input value is provably positive and we could not simplify
1791 // away the sext build a zext instead.
1792 if (isKnownNonNegative(Op))
1793 return getZeroExtendExpr(Op, Ty);
1794
Dan Gohman74a0ba12009-07-13 20:55:53 +00001795 // The cast wasn't folded; create an explicit cast node.
1796 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001797 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001798 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1799 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001800 UniqueSCEVs.InsertNode(S, IP);
1801 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001802}
1803
Dan Gohman8db2edc2009-06-13 15:56:47 +00001804/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1805/// unspecified bits out to the given type.
1806///
Dan Gohmanaf752342009-07-07 17:06:11 +00001807const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001808 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001809 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1810 "This is not an extending conversion!");
1811 assert(isSCEVable(Ty) &&
1812 "This is not a conversion to a SCEVable type!");
1813 Ty = getEffectiveSCEVType(Ty);
1814
1815 // Sign-extend negative constants.
1816 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001817 if (SC->getAPInt().isNegative())
Dan Gohman8db2edc2009-06-13 15:56:47 +00001818 return getSignExtendExpr(Op, Ty);
1819
1820 // Peel off a truncate cast.
1821 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001822 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001823 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1824 return getAnyExtendExpr(NewOp, Ty);
1825 return getTruncateOrNoop(NewOp, Ty);
1826 }
1827
1828 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001829 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001830 if (!isa<SCEVZeroExtendExpr>(ZExt))
1831 return ZExt;
1832
1833 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001834 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001835 if (!isa<SCEVSignExtendExpr>(SExt))
1836 return SExt;
1837
Dan Gohman51ad99d2010-01-21 02:09:26 +00001838 // Force the cast to be folded into the operands of an addrec.
1839 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1840 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001841 for (const SCEV *Op : AR->operands())
1842 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001843 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001844 }
1845
Dan Gohman8db2edc2009-06-13 15:56:47 +00001846 // If the expression is obviously signed, use the sext cast value.
1847 if (isa<SCEVSMaxExpr>(Op))
1848 return SExt;
1849
1850 // Absent any other information, use the zext cast value.
1851 return ZExt;
1852}
1853
Dan Gohman038d02e2009-06-14 22:58:51 +00001854/// CollectAddOperandsWithScales - Process the given Ops list, which is
1855/// a list of operands to be added under the given scale, update the given
1856/// map. This is a helper function for getAddRecExpr. As an example of
1857/// what it does, given a sequence of operands that would form an add
1858/// expression like this:
1859///
Tobias Grosserba49e422014-03-05 10:37:17 +00001860/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001861///
1862/// where A and B are constants, update the map with these values:
1863///
1864/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1865///
1866/// and add 13 + A*B*29 to AccumulatedConstant.
1867/// This will allow getAddRecExpr to produce this:
1868///
1869/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1870///
1871/// This form often exposes folding opportunities that are hidden in
1872/// the original operand list.
1873///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001874/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001875/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1876/// the common case where no interesting opportunities are present, and
1877/// is also used as a check to avoid infinite recursion.
1878///
1879static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001880CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001881 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001882 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001883 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001884 const APInt &Scale,
1885 ScalarEvolution &SE) {
1886 bool Interesting = false;
1887
Dan Gohman45073042010-06-18 19:12:32 +00001888 // Iterate over the add operands. They are sorted, with constants first.
1889 unsigned i = 0;
1890 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1891 ++i;
1892 // Pull a buried constant out to the outside.
1893 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1894 Interesting = true;
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001895 AccumulatedConstant += Scale * C->getAPInt();
Dan Gohman45073042010-06-18 19:12:32 +00001896 }
1897
1898 // Next comes everything else. We're especially interested in multiplies
1899 // here, but they're in the middle, so just visit the rest with one loop.
1900 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001901 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1902 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1903 APInt NewScale =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001904 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
Dan Gohman038d02e2009-06-14 22:58:51 +00001905 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1906 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001907 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001908 Interesting |=
1909 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001910 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001911 NewScale, SE);
1912 } else {
1913 // A multiplication of a constant with some other value. Update
1914 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001915 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1916 const SCEV *Key = SE.getMulExpr(MulOps);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001917 auto Pair = M.insert({Key, NewScale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001918 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001919 NewOps.push_back(Pair.first->first);
1920 } else {
1921 Pair.first->second += NewScale;
1922 // The map already had an entry for this value, which may indicate
1923 // a folding opportunity.
1924 Interesting = true;
1925 }
1926 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001927 } else {
1928 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001929 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00001930 M.insert({Ops[i], Scale});
Dan Gohman038d02e2009-06-14 22:58:51 +00001931 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001932 NewOps.push_back(Pair.first->first);
1933 } else {
1934 Pair.first->second += Scale;
1935 // The map already had an entry for this value, which may indicate
1936 // a folding opportunity.
1937 Interesting = true;
1938 }
1939 }
1940 }
1941
1942 return Interesting;
1943}
1944
Sanjoy Das81401d42015-01-10 23:41:24 +00001945// We're trying to construct a SCEV of type `Type' with `Ops' as operands and
1946// `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
1947// can't-overflow flags for the operation if possible.
1948static SCEV::NoWrapFlags
1949StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
1950 const SmallVectorImpl<const SCEV *> &Ops,
Sanjoy Das8f274152015-10-22 19:57:19 +00001951 SCEV::NoWrapFlags Flags) {
Sanjoy Das81401d42015-01-10 23:41:24 +00001952 using namespace std::placeholders;
Sanjoy Das8f274152015-10-22 19:57:19 +00001953 typedef OverflowingBinaryOperator OBO;
Sanjoy Das81401d42015-01-10 23:41:24 +00001954
1955 bool CanAnalyze =
1956 Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
1957 (void)CanAnalyze;
1958 assert(CanAnalyze && "don't call from other places!");
1959
1960 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1961 SCEV::NoWrapFlags SignOrUnsignWrap =
Sanjoy Das8f274152015-10-22 19:57:19 +00001962 ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001963
1964 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Sanjoy Das9b0015f2015-11-29 23:40:57 +00001965 auto IsKnownNonNegative = [&](const SCEV *S) {
1966 return SE->isKnownNonNegative(S);
1967 };
Sanjoy Das81401d42015-01-10 23:41:24 +00001968
Sanjoy Das3b827c72015-11-29 23:40:53 +00001969 if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
Sanjoy Das8f274152015-10-22 19:57:19 +00001970 Flags =
1971 ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Sanjoy Das81401d42015-01-10 23:41:24 +00001972
Sanjoy Das8f274152015-10-22 19:57:19 +00001973 SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
1974
1975 if (SignOrUnsignWrap != SignOrUnsignMask && Type == scAddExpr &&
1976 Ops.size() == 2 && isa<SCEVConstant>(Ops[0])) {
1977
1978 // (A + C) --> (A + C)<nsw> if the addition does not sign overflow
1979 // (A + C) --> (A + C)<nuw> if the addition does not unsign overflow
1980
Sanjoy Das0de2fec2015-12-17 20:28:46 +00001981 const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
Sanjoy Das8f274152015-10-22 19:57:19 +00001982 if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00001983 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1984 Instruction::Add, C, OBO::NoSignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00001985 if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
1986 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
1987 }
1988 if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
Sanjoy Das5079f622016-02-22 16:13:02 +00001989 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
1990 Instruction::Add, C, OBO::NoUnsignedWrap);
Sanjoy Das8f274152015-10-22 19:57:19 +00001991 if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
1992 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
1993 }
1994 }
1995
1996 return Flags;
Sanjoy Das81401d42015-01-10 23:41:24 +00001997}
1998
Dan Gohman4d5435d2009-05-24 23:45:28 +00001999/// getAddExpr - Get a canonical add expression, or something simpler if
2000/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002001const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002002 SCEV::NoWrapFlags Flags) {
2003 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
2004 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002005 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00002006 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002007#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002008 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002009 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00002010 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002011 "SCEVAddExpr operand types don't match!");
2012#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002013
2014 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002015 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002016
Sanjoy Das64895612015-10-09 02:44:45 +00002017 Flags = StrengthenNoWrapFlags(this, scAddExpr, Ops, Flags);
2018
Chris Lattnerd934c702004-04-02 20:23:17 +00002019 // If there are any constants, fold them together.
2020 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002021 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002022 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00002023 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002024 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002025 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002026 Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
Dan Gohman011cf682009-06-14 22:53:57 +00002027 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002028 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002029 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002030 }
2031
2032 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002033 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002034 Ops.erase(Ops.begin());
2035 --Idx;
2036 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002037
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002038 if (Ops.size() == 1) return Ops[0];
2039 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002040
Dan Gohman15871f22010-08-27 21:39:59 +00002041 // Okay, check to see if the same value occurs in the operand list more than
2042 // once. If so, merge them together into an multiply expression. Since we
2043 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00002044 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00002045 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00002046 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00002047 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00002048 // Scan ahead to count how many equal operands there are.
2049 unsigned Count = 2;
2050 while (i+Count != e && Ops[i+Count] == Ops[i])
2051 ++Count;
2052 // Merge the values into a multiply.
2053 const SCEV *Scale = getConstant(Ty, Count);
2054 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
2055 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00002056 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00002057 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00002058 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00002059 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00002060 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00002061 }
Dan Gohmane67b2872010-08-12 14:46:54 +00002062 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00002063 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002064
Dan Gohman2e55cc52009-05-08 21:03:19 +00002065 // Check for truncates. If all the operands are truncated from the same
2066 // type, see if factoring out the truncate would permit the result to be
2067 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
2068 // if the contents of the resulting outer trunc fold to something simple.
2069 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
2070 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00002071 Type *DstType = Trunc->getType();
2072 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00002073 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002074 bool Ok = true;
2075 // Check all the operands to see if they can be represented in the
2076 // source type of the truncate.
2077 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
2078 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
2079 if (T->getOperand()->getType() != SrcType) {
2080 Ok = false;
2081 break;
2082 }
2083 LargeOps.push_back(T->getOperand());
2084 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002085 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002086 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002087 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00002088 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
2089 if (const SCEVTruncateExpr *T =
2090 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
2091 if (T->getOperand()->getType() != SrcType) {
2092 Ok = false;
2093 break;
2094 }
2095 LargeMulOps.push_back(T->getOperand());
Sanjoy Das63914592015-10-18 00:29:20 +00002096 } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00002097 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00002098 } else {
2099 Ok = false;
2100 break;
2101 }
2102 }
2103 if (Ok)
2104 LargeOps.push_back(getMulExpr(LargeMulOps));
2105 } else {
2106 Ok = false;
2107 break;
2108 }
2109 }
2110 if (Ok) {
2111 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00002112 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00002113 // If it folds to something simple, use it. Otherwise, don't.
2114 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
2115 return getTruncateExpr(Fold, DstType);
2116 }
2117 }
2118
2119 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00002120 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
2121 ++Idx;
2122
2123 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00002124 if (Idx < Ops.size()) {
2125 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002126 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002127 // If we have an add, expand the add operands onto the end of the operands
2128 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002129 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002130 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002131 DeletedAdd = true;
2132 }
2133
2134 // If we deleted at least one add, we added operands to the end of the list,
2135 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002136 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002137 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002138 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002139 }
2140
2141 // Skip over the add expression until we get to a multiply.
2142 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2143 ++Idx;
2144
Dan Gohman038d02e2009-06-14 22:58:51 +00002145 // Check to see if there are any folding opportunities present with
2146 // operands multiplied by constant values.
2147 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
2148 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00002149 DenseMap<const SCEV *, APInt> M;
2150 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00002151 APInt AccumulatedConstant(BitWidth, 0);
2152 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00002153 Ops.data(), Ops.size(),
2154 APInt(BitWidth, 1), *this)) {
Sanjoy Das7d752672015-12-08 04:32:54 +00002155 struct APIntCompare {
2156 bool operator()(const APInt &LHS, const APInt &RHS) const {
2157 return LHS.ult(RHS);
2158 }
2159 };
2160
Dan Gohman038d02e2009-06-14 22:58:51 +00002161 // Some interesting folding opportunity is present, so its worthwhile to
2162 // re-generate the operands list. Group the operands by constant scale,
2163 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00002164 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002165 for (const SCEV *NewOp : NewOps)
2166 MulOpLists[M.find(NewOp)->second].push_back(NewOp);
Dan Gohman038d02e2009-06-14 22:58:51 +00002167 // Re-generate the operands list.
2168 Ops.clear();
2169 if (AccumulatedConstant != 0)
2170 Ops.push_back(getConstant(AccumulatedConstant));
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002171 for (auto &MulOp : MulOpLists)
2172 if (MulOp.first != 0)
2173 Ops.push_back(getMulExpr(getConstant(MulOp.first),
2174 getAddExpr(MulOp.second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00002175 if (Ops.empty())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002176 return getZero(Ty);
Dan Gohman038d02e2009-06-14 22:58:51 +00002177 if (Ops.size() == 1)
2178 return Ops[0];
2179 return getAddExpr(Ops);
2180 }
2181 }
2182
Chris Lattnerd934c702004-04-02 20:23:17 +00002183 // If we are adding something to a multiply expression, make sure the
2184 // something is not already an operand of the multiply. If so, merge it into
2185 // the multiply.
2186 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002187 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002188 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00002189 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00002190 if (isa<SCEVConstant>(MulOpSCEV))
2191 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00002192 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00002193 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002194 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00002195 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002196 if (Mul->getNumOperands() != 2) {
2197 // If the multiply has more than two operands, we must get the
2198 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00002199 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
2200 Mul->op_begin()+MulOp);
2201 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002202 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002203 }
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002204 const SCEV *One = getOne(Ty);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00002205 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00002206 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00002207 if (Ops.size() == 2) return OuterMul;
2208 if (AddOp < Idx) {
2209 Ops.erase(Ops.begin()+AddOp);
2210 Ops.erase(Ops.begin()+Idx-1);
2211 } else {
2212 Ops.erase(Ops.begin()+Idx);
2213 Ops.erase(Ops.begin()+AddOp-1);
2214 }
2215 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00002216 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002217 }
Misha Brukman01808ca2005-04-21 21:13:18 +00002218
Chris Lattnerd934c702004-04-02 20:23:17 +00002219 // Check this multiply against other multiplies being added together.
2220 for (unsigned OtherMulIdx = Idx+1;
2221 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
2222 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00002223 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002224 // If MulOp occurs in OtherMul, we can fold the two multiplies
2225 // together.
2226 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
2227 OMulOp != e; ++OMulOp)
2228 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
2229 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00002230 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002231 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002232 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002233 Mul->op_begin()+MulOp);
2234 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002235 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002236 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002237 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002238 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002239 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002240 OtherMul->op_begin()+OMulOp);
2241 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002242 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002243 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002244 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2245 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002246 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002247 Ops.erase(Ops.begin()+Idx);
2248 Ops.erase(Ops.begin()+OtherMulIdx-1);
2249 Ops.push_back(OuterMul);
2250 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002251 }
2252 }
2253 }
2254 }
2255
2256 // If there are any add recurrences in the operands list, see if any other
2257 // added values are loop invariant. If so, we can fold them into the
2258 // recurrence.
2259 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2260 ++Idx;
2261
2262 // Scan over all recurrences, trying to fold loop invariants into them.
2263 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2264 // Scan all of the other operands to this add and add them to the vector if
2265 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002266 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002267 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002268 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002269 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002270 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002271 LIOps.push_back(Ops[i]);
2272 Ops.erase(Ops.begin()+i);
2273 --i; --e;
2274 }
2275
2276 // If we found some loop invariants, fold them into the recurrence.
2277 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002278 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002279 LIOps.push_back(AddRec->getStart());
2280
Dan Gohmanaf752342009-07-07 17:06:11 +00002281 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002282 AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002283 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002284
Dan Gohman16206132010-06-30 07:16:37 +00002285 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002286 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002287 // Always propagate NW.
2288 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002289 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002290
Chris Lattnerd934c702004-04-02 20:23:17 +00002291 // If all of the other operands were loop invariant, we are done.
2292 if (Ops.size() == 1) return NewRec;
2293
Nick Lewyckydb66b822011-09-06 05:08:09 +00002294 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002295 for (unsigned i = 0;; ++i)
2296 if (Ops[i] == AddRec) {
2297 Ops[i] = NewRec;
2298 break;
2299 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002300 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002301 }
2302
2303 // Okay, if there weren't any loop invariants to be folded, check to see if
2304 // there are multiple AddRec's with the same loop induction variable being
2305 // added together. If so, we can fold them.
2306 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002307 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2308 ++OtherIdx)
2309 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2310 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2311 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2312 AddRec->op_end());
2313 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2314 ++OtherIdx)
Sanjoy Dasf25d25a2015-10-31 23:21:32 +00002315 if (const auto *OtherAddRec = dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002316 if (OtherAddRec->getLoop() == AddRecLoop) {
2317 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2318 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002319 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002320 AddRecOps.append(OtherAddRec->op_begin()+i,
2321 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002322 break;
2323 }
Dan Gohman028c1812010-08-29 14:53:34 +00002324 AddRecOps[i] = getAddExpr(AddRecOps[i],
2325 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002326 }
2327 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002328 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002329 // Step size has changed, so we cannot guarantee no self-wraparound.
2330 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002331 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002332 }
2333
2334 // Otherwise couldn't fold anything into this recurrence. Move onto the
2335 // next one.
2336 }
2337
2338 // Okay, it looks like we really DO need an add expr. Check to see if we
2339 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002340 FoldingSetNodeID ID;
2341 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002342 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2343 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002344 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002345 SCEVAddExpr *S =
2346 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2347 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002348 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2349 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002350 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2351 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002352 UniqueSCEVs.InsertNode(S, IP);
2353 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002354 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002355 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002356}
2357
Nick Lewycky287682e2011-10-04 06:51:26 +00002358static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2359 uint64_t k = i*j;
2360 if (j > 1 && k / j != i) Overflow = true;
2361 return k;
2362}
2363
2364/// Compute the result of "n choose k", the binomial coefficient. If an
2365/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002366/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002367static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2368 // We use the multiplicative formula:
2369 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2370 // At each iteration, we take the n-th term of the numeral and divide by the
2371 // (k-n)th term of the denominator. This division will always produce an
2372 // integral result, and helps reduce the chance of overflow in the
2373 // intermediate computations. However, we can still overflow even when the
2374 // final result would fit.
2375
2376 if (n == 0 || n == k) return 1;
2377 if (k > n) return 0;
2378
2379 if (k > n/2)
2380 k = n-k;
2381
2382 uint64_t r = 1;
2383 for (uint64_t i = 1; i <= k; ++i) {
2384 r = umul_ov(r, n-(i-1), Overflow);
2385 r /= i;
2386 }
2387 return r;
2388}
2389
Nick Lewycky05044c22014-12-06 00:45:50 +00002390/// Determine if any of the operands in this SCEV are a constant or if
2391/// any of the add or multiply expressions in this SCEV contain a constant.
2392static bool containsConstantSomewhere(const SCEV *StartExpr) {
2393 SmallVector<const SCEV *, 4> Ops;
2394 Ops.push_back(StartExpr);
2395 while (!Ops.empty()) {
2396 const SCEV *CurrentExpr = Ops.pop_back_val();
2397 if (isa<SCEVConstant>(*CurrentExpr))
2398 return true;
2399
2400 if (isa<SCEVAddExpr>(*CurrentExpr) || isa<SCEVMulExpr>(*CurrentExpr)) {
2401 const auto *CurrentNAry = cast<SCEVNAryExpr>(CurrentExpr);
Benjamin Kramer6cd780f2015-02-17 15:29:18 +00002402 Ops.append(CurrentNAry->op_begin(), CurrentNAry->op_end());
Nick Lewycky05044c22014-12-06 00:45:50 +00002403 }
2404 }
2405 return false;
2406}
2407
Dan Gohman4d5435d2009-05-24 23:45:28 +00002408/// getMulExpr - Get a canonical multiply expression, or something simpler if
2409/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002410const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002411 SCEV::NoWrapFlags Flags) {
2412 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2413 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002414 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002415 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002416#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002417 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002418 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002419 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002420 "SCEVMulExpr operand types don't match!");
2421#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002422
2423 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002424 GroupByComplexity(Ops, &LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002425
Sanjoy Das64895612015-10-09 02:44:45 +00002426 Flags = StrengthenNoWrapFlags(this, scMulExpr, Ops, Flags);
2427
Chris Lattnerd934c702004-04-02 20:23:17 +00002428 // If there are any constants, fold them together.
2429 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002430 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002431
2432 // C1*(C2+V) -> C1*C2 + C1*V
2433 if (Ops.size() == 2)
Nick Lewycky05044c22014-12-06 00:45:50 +00002434 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
2435 // If any of Add's ops are Adds or Muls with a constant,
2436 // apply this transformation as well.
2437 if (Add->getNumOperands() == 2)
2438 if (containsConstantSomewhere(Add))
2439 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2440 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002441
Chris Lattnerd934c702004-04-02 20:23:17 +00002442 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002443 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002444 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002445 ConstantInt *Fold =
2446 ConstantInt::get(getContext(), LHSC->getAPInt() * RHSC->getAPInt());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002447 Ops[0] = getConstant(Fold);
2448 Ops.erase(Ops.begin()+1); // Erase the folded element
2449 if (Ops.size() == 1) return Ops[0];
2450 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002451 }
2452
2453 // If we are left with a constant one being multiplied, strip it off.
2454 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2455 Ops.erase(Ops.begin());
2456 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002457 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002458 // If we have a multiply of zero, it will always be zero.
2459 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002460 } else if (Ops[0]->isAllOnesValue()) {
2461 // If we have a mul by -1 of an add, try distributing the -1 among the
2462 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002463 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002464 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2465 SmallVector<const SCEV *, 4> NewOps;
2466 bool AnyFolded = false;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002467 for (const SCEV *AddOp : Add->operands()) {
2468 const SCEV *Mul = getMulExpr(Ops[0], AddOp);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002469 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2470 NewOps.push_back(Mul);
2471 }
2472 if (AnyFolded)
2473 return getAddExpr(NewOps);
Sanjoy Das63914592015-10-18 00:29:20 +00002474 } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
Andrew Tricke92dcce2011-03-14 17:38:54 +00002475 // Negation preserves a recurrence's no self-wrap property.
2476 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00002477 for (const SCEV *AddRecOp : AddRec->operands())
2478 Operands.push_back(getMulExpr(Ops[0], AddRecOp));
2479
Andrew Tricke92dcce2011-03-14 17:38:54 +00002480 return getAddRecExpr(Operands, AddRec->getLoop(),
2481 AddRec->getNoWrapFlags(SCEV::FlagNW));
2482 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002483 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002484 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002485
2486 if (Ops.size() == 1)
2487 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002488 }
2489
2490 // Skip over the add expression until we get to a multiply.
2491 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2492 ++Idx;
2493
Chris Lattnerd934c702004-04-02 20:23:17 +00002494 // If there are mul operands inline them all into this expression.
2495 if (Idx < Ops.size()) {
2496 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002497 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002498 // If we have an mul, expand the mul operands onto the end of the operands
2499 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002500 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002501 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002502 DeletedMul = true;
2503 }
2504
2505 // If we deleted at least one mul, we added operands to the end of the list,
2506 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002507 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002508 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002509 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002510 }
2511
2512 // If there are any add recurrences in the operands list, see if any other
2513 // added values are loop invariant. If so, we can fold them into the
2514 // recurrence.
2515 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2516 ++Idx;
2517
2518 // Scan over all recurrences, trying to fold loop invariants into them.
2519 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2520 // Scan all of the other operands to this mul and add them to the vector if
2521 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002522 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002523 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002524 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002525 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002526 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002527 LIOps.push_back(Ops[i]);
2528 Ops.erase(Ops.begin()+i);
2529 --i; --e;
2530 }
2531
2532 // If we found some loop invariants, fold them into the recurrence.
2533 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002534 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002535 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002536 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002537 const SCEV *Scale = getMulExpr(LIOps);
2538 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2539 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002540
Dan Gohman16206132010-06-30 07:16:37 +00002541 // Build the new addrec. Propagate the NUW and NSW flags if both the
2542 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002543 //
2544 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002545 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002546 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2547 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002548
2549 // If all of the other operands were loop invariant, we are done.
2550 if (Ops.size() == 1) return NewRec;
2551
Nick Lewyckydb66b822011-09-06 05:08:09 +00002552 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002553 for (unsigned i = 0;; ++i)
2554 if (Ops[i] == AddRec) {
2555 Ops[i] = NewRec;
2556 break;
2557 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002558 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002559 }
2560
2561 // Okay, if there weren't any loop invariants to be folded, check to see if
2562 // there are multiple AddRec's with the same loop induction variable being
2563 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002564
2565 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2566 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2567 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2568 // ]]],+,...up to x=2n}.
2569 // Note that the arguments to choose() are always integers with values
2570 // known at compile time, never SCEV objects.
2571 //
2572 // The implementation avoids pointless extra computations when the two
2573 // addrec's are of different length (mathematically, it's equivalent to
2574 // an infinite stream of zeros on the right).
2575 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002576 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002577 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002578 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002579 const SCEVAddRecExpr *OtherAddRec =
2580 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2581 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002582 continue;
2583
Nick Lewycky97756402014-09-01 05:17:15 +00002584 bool Overflow = false;
2585 Type *Ty = AddRec->getType();
2586 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2587 SmallVector<const SCEV*, 7> AddRecOps;
2588 for (int x = 0, xe = AddRec->getNumOperands() +
2589 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002590 const SCEV *Term = getZero(Ty);
Nick Lewycky97756402014-09-01 05:17:15 +00002591 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2592 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2593 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2594 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2595 z < ze && !Overflow; ++z) {
2596 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2597 uint64_t Coeff;
2598 if (LargerThan64Bits)
2599 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2600 else
2601 Coeff = Coeff1*Coeff2;
2602 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2603 const SCEV *Term1 = AddRec->getOperand(y-z);
2604 const SCEV *Term2 = OtherAddRec->getOperand(z);
2605 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002606 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002607 }
Nick Lewycky97756402014-09-01 05:17:15 +00002608 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002609 }
Nick Lewycky97756402014-09-01 05:17:15 +00002610 if (!Overflow) {
2611 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2612 SCEV::FlagAnyWrap);
2613 if (Ops.size() == 2) return NewAddRec;
2614 Ops[Idx] = NewAddRec;
2615 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2616 OpsModified = true;
2617 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2618 if (!AddRec)
2619 break;
2620 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002621 }
Nick Lewycky97756402014-09-01 05:17:15 +00002622 if (OpsModified)
2623 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002624
2625 // Otherwise couldn't fold anything into this recurrence. Move onto the
2626 // next one.
2627 }
2628
2629 // Okay, it looks like we really DO need an mul expr. Check to see if we
2630 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002631 FoldingSetNodeID ID;
2632 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002633 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2634 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002635 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002636 SCEVMulExpr *S =
2637 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2638 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002639 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2640 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002641 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2642 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002643 UniqueSCEVs.InsertNode(S, IP);
2644 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002645 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002646 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002647}
2648
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002649/// getUDivExpr - Get a canonical unsigned division expression, or something
2650/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002651const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2652 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002653 assert(getEffectiveSCEVType(LHS->getType()) ==
2654 getEffectiveSCEVType(RHS->getType()) &&
2655 "SCEVUDivExpr operand types don't match!");
2656
Dan Gohmana30370b2009-05-04 22:02:23 +00002657 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002658 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002659 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002660 // If the denominator is zero, the result of the udiv is undefined. Don't
2661 // try to analyze it, because the resolution chosen here may differ from
2662 // the resolution chosen in other parts of the compiler.
2663 if (!RHSC->getValue()->isZero()) {
2664 // Determine if the division can be folded into the operands of
2665 // its operands.
2666 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002667 Type *Ty = LHS->getType();
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002668 unsigned LZ = RHSC->getAPInt().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002669 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002670 // For non-power-of-two values, effectively round the value up to the
2671 // nearest power of two.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002672 if (!RHSC->getAPInt().isPowerOf2())
Dan Gohmanacd700a2010-04-22 01:35:11 +00002673 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002674 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002675 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002676 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2677 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002678 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2679 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002680 const APInt &StepInt = Step->getAPInt();
2681 const APInt &DivInt = RHSC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002682 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002683 getZeroExtendExpr(AR, ExtTy) ==
2684 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2685 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002686 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002687 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002688 for (const SCEV *Op : AR->operands())
2689 Operands.push_back(getUDivExpr(Op, RHS));
2690 return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002691 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002692 /// Get a canonical UDivExpr for a recurrence.
2693 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2694 // We can currently only fold X%N if X is constant.
2695 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2696 if (StartC && !DivInt.urem(StepInt) &&
2697 getZeroExtendExpr(AR, ExtTy) ==
2698 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2699 getZeroExtendExpr(Step, ExtTy),
2700 AR->getLoop(), SCEV::FlagAnyWrap)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002701 const APInt &StartInt = StartC->getAPInt();
Andrew Trick6d45a012011-08-06 07:00:37 +00002702 const APInt &StartRem = StartInt.urem(StepInt);
2703 if (StartRem != 0)
2704 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2705 AR->getLoop(), SCEV::FlagNW);
2706 }
2707 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002708 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2709 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2710 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002711 for (const SCEV *Op : M->operands())
2712 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002713 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2714 // Find an operand that's safely divisible.
2715 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2716 const SCEV *Op = M->getOperand(i);
2717 const SCEV *Div = getUDivExpr(Op, RHSC);
2718 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2719 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2720 M->op_end());
2721 Operands[i] = Div;
2722 return getMulExpr(Operands);
2723 }
2724 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002725 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002726 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Andrew Trick7d1eea82011-04-27 18:17:36 +00002727 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002728 SmallVector<const SCEV *, 4> Operands;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00002729 for (const SCEV *Op : A->operands())
2730 Operands.push_back(getZeroExtendExpr(Op, ExtTy));
Dan Gohmanacd700a2010-04-22 01:35:11 +00002731 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2732 Operands.clear();
2733 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2734 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2735 if (isa<SCEVUDivExpr>(Op) ||
2736 getMulExpr(Op, RHS) != A->getOperand(i))
2737 break;
2738 Operands.push_back(Op);
2739 }
2740 if (Operands.size() == A->getNumOperands())
2741 return getAddExpr(Operands);
2742 }
2743 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002744
Dan Gohmanacd700a2010-04-22 01:35:11 +00002745 // Fold if both operands are constant.
2746 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2747 Constant *LHSCV = LHSC->getValue();
2748 Constant *RHSCV = RHSC->getValue();
2749 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2750 RHSCV)));
2751 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002752 }
2753 }
2754
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002755 FoldingSetNodeID ID;
2756 ID.AddInteger(scUDivExpr);
2757 ID.AddPointer(LHS);
2758 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002759 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002760 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002761 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2762 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002763 UniqueSCEVs.InsertNode(S, IP);
2764 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002765}
2766
Nick Lewycky31eaca52014-01-27 10:04:03 +00002767static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002768 APInt A = C1->getAPInt().abs();
2769 APInt B = C2->getAPInt().abs();
Nick Lewycky31eaca52014-01-27 10:04:03 +00002770 uint32_t ABW = A.getBitWidth();
2771 uint32_t BBW = B.getBitWidth();
2772
2773 if (ABW > BBW)
2774 B = B.zext(ABW);
2775 else if (ABW < BBW)
2776 A = A.zext(BBW);
2777
2778 return APIntOps::GreatestCommonDivisor(A, B);
2779}
2780
2781/// getUDivExactExpr - Get a canonical unsigned division expression, or
2782/// something simpler if possible. There is no representation for an exact udiv
2783/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2784/// We can't do this when it's not exact because the udiv may be clearing bits.
2785const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2786 const SCEV *RHS) {
2787 // TODO: we could try to find factors in all sorts of things, but for now we
2788 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2789 // end of this file for inspiration.
2790
2791 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2792 if (!Mul)
2793 return getUDivExpr(LHS, RHS);
2794
2795 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2796 // If the mulexpr multiplies by a constant, then that constant must be the
2797 // first element of the mulexpr.
Sanjoy Das63914592015-10-18 00:29:20 +00002798 if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
Nick Lewycky31eaca52014-01-27 10:04:03 +00002799 if (LHSCst == RHSCst) {
2800 SmallVector<const SCEV *, 2> Operands;
2801 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2802 return getMulExpr(Operands);
2803 }
2804
2805 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2806 // that there's a factor provided by one of the other terms. We need to
2807 // check.
2808 APInt Factor = gcd(LHSCst, RHSCst);
2809 if (!Factor.isIntN(1)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00002810 LHSCst =
2811 cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
2812 RHSCst =
2813 cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
Nick Lewycky31eaca52014-01-27 10:04:03 +00002814 SmallVector<const SCEV *, 2> Operands;
2815 Operands.push_back(LHSCst);
2816 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2817 LHS = getMulExpr(Operands);
2818 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002819 Mul = dyn_cast<SCEVMulExpr>(LHS);
2820 if (!Mul)
2821 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002822 }
2823 }
2824 }
2825
2826 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2827 if (Mul->getOperand(i) == RHS) {
2828 SmallVector<const SCEV *, 2> Operands;
2829 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2830 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2831 return getMulExpr(Operands);
2832 }
2833 }
2834
2835 return getUDivExpr(LHS, RHS);
2836}
Chris Lattnerd934c702004-04-02 20:23:17 +00002837
Dan Gohman4d5435d2009-05-24 23:45:28 +00002838/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2839/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002840const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2841 const Loop *L,
2842 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002843 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002844 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002845 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002846 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002847 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002848 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002849 }
2850
2851 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002852 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002853}
2854
Dan Gohman4d5435d2009-05-24 23:45:28 +00002855/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2856/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002857const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002858ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002859 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002860 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002861#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002862 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002863 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002864 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002865 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002866 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002867 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002868 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002869#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002870
Dan Gohmanbe928e32008-06-18 16:23:07 +00002871 if (Operands.back()->isZero()) {
2872 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002873 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002874 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002875
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002876 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2877 // use that information to infer NUW and NSW flags. However, computing a
2878 // BE count requires calling getAddRecExpr, so we may not yet have a
2879 // meaningful BE count at this point (and if we don't, we'd be stuck
2880 // with a SCEVCouldNotCompute as the cached BE count).
2881
Sanjoy Das81401d42015-01-10 23:41:24 +00002882 Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002883
Dan Gohman223a5d22008-08-08 18:33:12 +00002884 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002885 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002886 const Loop *NestedLoop = NestedAR->getLoop();
Chandler Carruth2f1fd162015-08-17 02:08:17 +00002887 if (L->contains(NestedLoop)
2888 ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
2889 : (!NestedLoop->contains(L) &&
2890 DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002891 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002892 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002893 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002894 // AddRecs require their operands be loop-invariant with respect to their
2895 // loops. Don't perform this transformation if it would break this
2896 // requirement.
Sanjoy Das3b827c72015-11-29 23:40:53 +00002897 bool AllInvariant = all_of(
2898 Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002899
Dan Gohmancc030b72009-06-26 22:36:20 +00002900 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002901 // Create a recurrence for the outer loop with the same step size.
2902 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002903 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2904 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002905 SCEV::NoWrapFlags OuterFlags =
2906 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002907
2908 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Sanjoy Das3b827c72015-11-29 23:40:53 +00002909 AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
2910 return isLoopInvariant(Op, NestedLoop);
2911 });
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00002912
Andrew Trick8b55b732011-03-14 16:50:06 +00002913 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002914 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002915 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002916 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2917 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002918 SCEV::NoWrapFlags InnerFlags =
2919 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002920 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2921 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002922 }
2923 // Reset Operands to its original state.
2924 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002925 }
2926 }
2927
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002928 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2929 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002930 FoldingSetNodeID ID;
2931 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002932 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2933 ID.AddPointer(Operands[i]);
2934 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002935 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002936 SCEVAddRecExpr *S =
2937 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2938 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002939 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2940 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002941 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2942 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002943 UniqueSCEVs.InsertNode(S, IP);
2944 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002945 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002946 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002947}
2948
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002949const SCEV *
2950ScalarEvolution::getGEPExpr(Type *PointeeType, const SCEV *BaseExpr,
2951 const SmallVectorImpl<const SCEV *> &IndexExprs,
2952 bool InBounds) {
2953 // getSCEV(Base)->getType() has the same address space as Base->getType()
2954 // because SCEV::getType() preserves the address space.
2955 Type *IntPtrTy = getEffectiveSCEVType(BaseExpr->getType());
2956 // FIXME(PR23527): Don't blindly transfer the inbounds flag from the GEP
2957 // instruction to its SCEV, because the Instruction may be guarded by control
2958 // flow and the no-overflow bits may not be valid for the expression in any
Jingyue Wu42f1d672015-07-28 18:22:40 +00002959 // context. This can be fixed similarly to how these flags are handled for
2960 // adds.
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002961 SCEV::NoWrapFlags Wrap = InBounds ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
2962
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00002963 const SCEV *TotalOffset = getZero(IntPtrTy);
Jingyue Wu2982d4d2015-05-18 17:03:25 +00002964 // The address space is unimportant. The first thing we do on CurTy is getting
2965 // its element type.
2966 Type *CurTy = PointerType::getUnqual(PointeeType);
2967 for (const SCEV *IndexExpr : IndexExprs) {
2968 // Compute the (potentially symbolic) offset in bytes for this index.
2969 if (StructType *STy = dyn_cast<StructType>(CurTy)) {
2970 // For a struct, add the member offset.
2971 ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
2972 unsigned FieldNo = Index->getZExtValue();
2973 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
2974
2975 // Add the field offset to the running total offset.
2976 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
2977
2978 // Update CurTy to the type of the field at Index.
2979 CurTy = STy->getTypeAtIndex(Index);
2980 } else {
2981 // Update CurTy to its element type.
2982 CurTy = cast<SequentialType>(CurTy)->getElementType();
2983 // For an array, add the element offset, explicitly scaled.
2984 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, CurTy);
2985 // Getelementptr indices are signed.
2986 IndexExpr = getTruncateOrSignExtend(IndexExpr, IntPtrTy);
2987
2988 // Multiply the index by the element size to compute the element offset.
2989 const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, Wrap);
2990
2991 // Add the element offset to the running total offset.
2992 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2993 }
2994 }
2995
2996 // Add the total offset from all the GEP indices to the base.
2997 return getAddExpr(BaseExpr, TotalOffset, Wrap);
2998}
2999
Dan Gohmanabd17092009-06-24 14:49:00 +00003000const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
3001 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003002 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003003 Ops.push_back(LHS);
3004 Ops.push_back(RHS);
3005 return getSMaxExpr(Ops);
3006}
3007
Dan Gohmanaf752342009-07-07 17:06:11 +00003008const SCEV *
3009ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003010 assert(!Ops.empty() && "Cannot get empty smax!");
3011 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003012#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003013 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003014 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003015 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003016 "SCEVSMaxExpr operand types don't match!");
3017#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003018
3019 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003020 GroupByComplexity(Ops, &LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003021
3022 // If there are any constants, fold them together.
3023 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003024 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003025 ++Idx;
3026 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003027 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003028 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003029 ConstantInt *Fold = ConstantInt::get(
3030 getContext(), APIntOps::smax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003031 Ops[0] = getConstant(Fold);
3032 Ops.erase(Ops.begin()+1); // Erase the folded element
3033 if (Ops.size() == 1) return Ops[0];
3034 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003035 }
3036
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003037 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003038 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
3039 Ops.erase(Ops.begin());
3040 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003041 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
3042 // If we have an smax with a constant maximum-int, it will always be
3043 // maximum-int.
3044 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003045 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003046
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003047 if (Ops.size() == 1) return Ops[0];
3048 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003049
3050 // Find the first SMax
3051 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
3052 ++Idx;
3053
3054 // Check to see if one of the operands is an SMax. If so, expand its operands
3055 // onto our operand list, and recurse to simplify.
3056 if (Idx < Ops.size()) {
3057 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003058 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003059 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003060 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003061 DeletedSMax = true;
3062 }
3063
3064 if (DeletedSMax)
3065 return getSMaxExpr(Ops);
3066 }
3067
3068 // Okay, check to see if the same value occurs in the operand list twice. If
3069 // so, delete one. Since we sorted the list, these values are required to
3070 // be adjacent.
3071 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003072 // X smax Y smax Y --> X smax Y
3073 // X smax Y --> X, if X is always greater than Y
3074 if (Ops[i] == Ops[i+1] ||
3075 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
3076 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3077 --i; --e;
3078 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003079 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3080 --i; --e;
3081 }
3082
3083 if (Ops.size() == 1) return Ops[0];
3084
3085 assert(!Ops.empty() && "Reduced smax down to nothing!");
3086
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003087 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003088 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003089 FoldingSetNodeID ID;
3090 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003091 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3092 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003093 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003094 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003095 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3096 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003097 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
3098 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003099 UniqueSCEVs.InsertNode(S, IP);
3100 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003101}
3102
Dan Gohmanabd17092009-06-24 14:49:00 +00003103const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
3104 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003105 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003106 Ops.push_back(LHS);
3107 Ops.push_back(RHS);
3108 return getUMaxExpr(Ops);
3109}
3110
Dan Gohmanaf752342009-07-07 17:06:11 +00003111const SCEV *
3112ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003113 assert(!Ops.empty() && "Cannot get empty umax!");
3114 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00003115#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00003116 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00003117 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00003118 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00003119 "SCEVUMaxExpr operand types don't match!");
3120#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003121
3122 // Sort by complexity, this groups all similar expression types together.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003123 GroupByComplexity(Ops, &LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003124
3125 // If there are any constants, fold them together.
3126 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00003127 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003128 ++Idx;
3129 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00003130 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003131 // We found two constants, fold them together!
Sanjoy Das0de2fec2015-12-17 20:28:46 +00003132 ConstantInt *Fold = ConstantInt::get(
3133 getContext(), APIntOps::umax(LHSC->getAPInt(), RHSC->getAPInt()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003134 Ops[0] = getConstant(Fold);
3135 Ops.erase(Ops.begin()+1); // Erase the folded element
3136 if (Ops.size() == 1) return Ops[0];
3137 LHSC = cast<SCEVConstant>(Ops[0]);
3138 }
3139
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003140 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003141 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
3142 Ops.erase(Ops.begin());
3143 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00003144 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
3145 // If we have an umax with a constant maximum-int, it will always be
3146 // maximum-int.
3147 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003148 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003149
Dan Gohmanfe4b2912010-04-13 16:49:23 +00003150 if (Ops.size() == 1) return Ops[0];
3151 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003152
3153 // Find the first UMax
3154 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
3155 ++Idx;
3156
3157 // Check to see if one of the operands is a UMax. If so, expand its operands
3158 // onto our operand list, and recurse to simplify.
3159 if (Idx < Ops.size()) {
3160 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00003161 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003162 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00003163 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003164 DeletedUMax = true;
3165 }
3166
3167 if (DeletedUMax)
3168 return getUMaxExpr(Ops);
3169 }
3170
3171 // Okay, check to see if the same value occurs in the operand list twice. If
3172 // so, delete one. Since we sorted the list, these values are required to
3173 // be adjacent.
3174 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00003175 // X umax Y umax Y --> X umax Y
3176 // X umax Y --> X, if X is always greater than Y
3177 if (Ops[i] == Ops[i+1] ||
3178 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
3179 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
3180 --i; --e;
3181 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003182 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
3183 --i; --e;
3184 }
3185
3186 if (Ops.size() == 1) return Ops[0];
3187
3188 assert(!Ops.empty() && "Reduced umax down to nothing!");
3189
3190 // Okay, it looks like we really DO need a umax expr. Check to see if we
3191 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003192 FoldingSetNodeID ID;
3193 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003194 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
3195 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00003196 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003197 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00003198 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
3199 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00003200 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
3201 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003202 UniqueSCEVs.InsertNode(S, IP);
3203 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003204}
3205
Dan Gohmanabd17092009-06-24 14:49:00 +00003206const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
3207 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003208 // ~smax(~x, ~y) == smin(x, y).
3209 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3210}
3211
Dan Gohmanabd17092009-06-24 14:49:00 +00003212const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
3213 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00003214 // ~umax(~x, ~y) == umin(x, y)
3215 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
3216}
3217
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003218const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003219 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003220 // constant expression and then folding it back into a ConstantInt.
3221 // This is just a compile-time optimization.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003222 return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003223}
3224
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003225const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
3226 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00003227 unsigned FieldNo) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003228 // We can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00003229 // constant expression and then folding it back into a ConstantInt.
3230 // This is just a compile-time optimization.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003231 return getConstant(
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003232 IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003233}
3234
Dan Gohmanaf752342009-07-07 17:06:11 +00003235const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00003236 // Don't attempt to do anything other than create a SCEVUnknown object
3237 // here. createSCEV only calls getUnknown after checking for all other
3238 // interesting possibilities, and any other code that calls getUnknown
3239 // is doing so in order to hide a value from SCEV canonicalization.
3240
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003241 FoldingSetNodeID ID;
3242 ID.AddInteger(scUnknown);
3243 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003244 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003245 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3246 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3247 "Stale SCEVUnknown in uniquing map!");
3248 return S;
3249 }
3250 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3251 FirstUnknown);
3252 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003253 UniqueSCEVs.InsertNode(S, IP);
3254 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003255}
3256
Chris Lattnerd934c702004-04-02 20:23:17 +00003257//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003258// Basic SCEV Analysis and PHI Idiom Recognition Code
3259//
3260
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003261/// isSCEVable - Test if values of the given type are analyzable within
3262/// the SCEV framework. This primarily includes integer types, and it
3263/// can optionally include pointer types if the ScalarEvolution class
3264/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003265bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003266 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003267 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003268}
3269
3270/// getTypeSizeInBits - Return the size in bits of the specified type,
3271/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003272uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003273 assert(isSCEVable(Ty) && "Type is not SCEVable!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003274 return getDataLayout().getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003275}
3276
3277/// getEffectiveSCEVType - Return a type with the same bitwidth as
3278/// the given type and which represents how SCEV will treat the given
3279/// type, for which isSCEVable must return true. For pointer types,
3280/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003281Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003282 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3283
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003284 if (Ty->isIntegerTy())
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003285 return Ty;
3286
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003287 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003288 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Sanjoy Das49edd3b2015-10-27 00:52:09 +00003289 return getDataLayout().getIntPtrType(Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003290}
Chris Lattnerd934c702004-04-02 20:23:17 +00003291
Dan Gohmanaf752342009-07-07 17:06:11 +00003292const SCEV *ScalarEvolution::getCouldNotCompute() {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00003293 return CouldNotCompute.get();
Dan Gohman31efa302009-04-18 17:58:19 +00003294}
3295
Sanjoy Das7d752672015-12-08 04:32:54 +00003296
3297bool ScalarEvolution::checkValidity(const SCEV *S) const {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003298 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3299 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3300 // is set iff if find such SCEVUnknown.
3301 //
3302 struct FindInvalidSCEVUnknown {
3303 bool FindOne;
3304 FindInvalidSCEVUnknown() { FindOne = false; }
3305 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003306 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003307 case scConstant:
3308 return false;
3309 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003310 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003311 FindOne = true;
3312 return false;
3313 default:
3314 return true;
3315 }
3316 }
3317 bool isDone() const { return FindOne; }
3318 };
Shuxin Yangefc4c012013-07-08 17:33:13 +00003319
Shuxin Yangefc4c012013-07-08 17:33:13 +00003320 FindInvalidSCEVUnknown F;
3321 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3322 ST.visitAll(S);
3323
3324 return !F.FindOne;
3325}
3326
Wei Mia49559b2016-02-04 01:27:38 +00003327namespace {
3328// Helper class working with SCEVTraversal to figure out if a SCEV contains
3329// a sub SCEV of scAddRecExpr type. FindInvalidSCEVUnknown::FoundOne is set
3330// iff if such sub scAddRecExpr type SCEV is found.
3331struct FindAddRecurrence {
3332 bool FoundOne;
3333 FindAddRecurrence() : FoundOne(false) {}
3334
3335 bool follow(const SCEV *S) {
3336 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
3337 case scAddRecExpr:
3338 FoundOne = true;
3339 case scConstant:
3340 case scUnknown:
3341 case scCouldNotCompute:
3342 return false;
3343 default:
3344 return true;
3345 }
3346 }
3347 bool isDone() const { return FoundOne; }
3348};
3349}
3350
3351bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
3352 HasRecMapType::iterator I = HasRecMap.find_as(S);
3353 if (I != HasRecMap.end())
3354 return I->second;
3355
3356 FindAddRecurrence F;
3357 SCEVTraversal<FindAddRecurrence> ST(F);
3358 ST.visitAll(S);
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003359 HasRecMap.insert({S, F.FoundOne});
Wei Mia49559b2016-02-04 01:27:38 +00003360 return F.FoundOne;
3361}
3362
3363/// getSCEVValues - Return the Value set from S.
3364SetVector<Value *> *ScalarEvolution::getSCEVValues(const SCEV *S) {
3365 ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
3366 if (SI == ExprValueMap.end())
3367 return nullptr;
3368#ifndef NDEBUG
3369 if (VerifySCEVMap) {
3370 // Check there is no dangling Value in the set returned.
3371 for (const auto &VE : SI->second)
3372 assert(ValueExprMap.count(VE));
3373 }
3374#endif
3375 return &SI->second;
3376}
3377
3378/// eraseValueFromMap - Erase Value from ValueExprMap and ExprValueMap.
3379/// If ValueExprMap.erase(V) is not used together with forgetMemoizedResults(S),
3380/// eraseValueFromMap should be used instead to ensure whenever V->S is removed
3381/// from ValueExprMap, V is also removed from the set of ExprValueMap[S].
3382void ScalarEvolution::eraseValueFromMap(Value *V) {
3383 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3384 if (I != ValueExprMap.end()) {
3385 const SCEV *S = I->second;
3386 SetVector<Value *> *SV = getSCEVValues(S);
3387 // Remove V from the set of ExprValueMap[S]
3388 if (SV)
3389 SV->remove(V);
3390 ValueExprMap.erase(V);
3391 }
3392}
3393
Chris Lattnerd934c702004-04-02 20:23:17 +00003394/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3395/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003396const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003397 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003398
Jingyue Wu42f1d672015-07-28 18:22:40 +00003399 const SCEV *S = getExistingSCEV(V);
3400 if (S == nullptr) {
3401 S = createSCEV(V);
Wei Mia49559b2016-02-04 01:27:38 +00003402 // During PHI resolution, it is possible to create two SCEVs for the same
3403 // V, so it is needed to double check whether V->S is inserted into
3404 // ValueExprMap before insert S->V into ExprValueMap.
3405 std::pair<ValueExprMapType::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003406 ValueExprMap.insert({SCEVCallbackVH(V, this), S});
Wei Mia49559b2016-02-04 01:27:38 +00003407 if (Pair.second)
3408 ExprValueMap[S].insert(V);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003409 }
3410 return S;
3411}
3412
3413const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
3414 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
3415
Shuxin Yangefc4c012013-07-08 17:33:13 +00003416 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3417 if (I != ValueExprMap.end()) {
3418 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003419 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003420 return S;
Wei Mia49559b2016-02-04 01:27:38 +00003421 forgetMemoizedResults(S);
Jingyue Wu42f1d672015-07-28 18:22:40 +00003422 ValueExprMap.erase(I);
Shuxin Yangefc4c012013-07-08 17:33:13 +00003423 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00003424 return nullptr;
Chris Lattnerd934c702004-04-02 20:23:17 +00003425}
3426
Dan Gohman0a40ad92009-04-16 03:18:22 +00003427/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3428///
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003429const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
3430 SCEV::NoWrapFlags Flags) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003431 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003432 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003433 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003434
Chris Lattner229907c2011-07-18 04:54:35 +00003435 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003436 Ty = getEffectiveSCEVType(Ty);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003437 return getMulExpr(
3438 V, getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003439}
3440
3441/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003442const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003443 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003444 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003445 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003446
Chris Lattner229907c2011-07-18 04:54:35 +00003447 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003448 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003449 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003450 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003451 return getMinusSCEV(AllOnes, V);
3452}
3453
Andrew Trick8b55b732011-03-14 16:50:06 +00003454/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003455const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003456 SCEV::NoWrapFlags Flags) {
Dan Gohman46f00a22010-07-20 16:53:00 +00003457 // Fast path: X - X --> 0.
3458 if (LHS == RHS)
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00003459 return getZero(LHS->getType());
Dan Gohman46f00a22010-07-20 16:53:00 +00003460
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00003461 // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
3462 // makes it so that we cannot make much use of NUW.
3463 auto AddFlags = SCEV::FlagAnyWrap;
3464 const bool RHSIsNotMinSigned =
3465 !getSignedRange(RHS).getSignedMin().isMinSignedValue();
3466 if (maskFlags(Flags, SCEV::FlagNSW) == SCEV::FlagNSW) {
3467 // Let M be the minimum representable signed value. Then (-1)*RHS
3468 // signed-wraps if and only if RHS is M. That can happen even for
3469 // a NSW subtraction because e.g. (-1)*M signed-wraps even though
3470 // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
3471 // (-1)*RHS, we need to prove that RHS != M.
3472 //
3473 // If LHS is non-negative and we know that LHS - RHS does not
3474 // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
3475 // either by proving that RHS > M or that LHS >= 0.
3476 if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
3477 AddFlags = SCEV::FlagNSW;
3478 }
3479 }
3480
3481 // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
3482 // RHS is NSW and LHS >= 0.
3483 //
3484 // The difficulty here is that the NSW flag may have been proven
3485 // relative to a loop that is to be found in a recurrence in LHS and
3486 // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
3487 // larger scope than intended.
3488 auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3489
3490 return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003491}
3492
3493/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3494/// input value to the specified type. If the type must be extended, it is zero
3495/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003496const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003497ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3498 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003499 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3500 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003501 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003502 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003503 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003504 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003505 return getTruncateExpr(V, Ty);
3506 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003507}
3508
3509/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3510/// input value to the specified type. If the type must be extended, it is sign
3511/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003512const SCEV *
3513ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003514 Type *Ty) {
3515 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003516 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3517 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003518 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003519 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003520 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003521 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003522 return getTruncateExpr(V, Ty);
3523 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003524}
3525
Dan Gohmane712a2f2009-05-13 03:46:30 +00003526/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3527/// input value to the specified type. If the type must be extended, it is zero
3528/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003529const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003530ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3531 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003532 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3533 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003534 "Cannot noop or zero extend with non-integer arguments!");
3535 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3536 "getNoopOrZeroExtend cannot truncate!");
3537 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3538 return V; // No conversion
3539 return getZeroExtendExpr(V, Ty);
3540}
3541
3542/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3543/// input value to the specified type. If the type must be extended, it is sign
3544/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003545const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003546ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3547 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003548 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3549 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003550 "Cannot noop or sign extend with non-integer arguments!");
3551 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3552 "getNoopOrSignExtend cannot truncate!");
3553 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3554 return V; // No conversion
3555 return getSignExtendExpr(V, Ty);
3556}
3557
Dan Gohman8db2edc2009-06-13 15:56:47 +00003558/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3559/// the input value to the specified type. If the type must be extended,
3560/// it is extended with unspecified bits. The conversion must not be
3561/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003562const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003563ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3564 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003565 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3566 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003567 "Cannot noop or any extend with non-integer arguments!");
3568 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3569 "getNoopOrAnyExtend cannot truncate!");
3570 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3571 return V; // No conversion
3572 return getAnyExtendExpr(V, Ty);
3573}
3574
Dan Gohmane712a2f2009-05-13 03:46:30 +00003575/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3576/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003577const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003578ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3579 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003580 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3581 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003582 "Cannot truncate or noop with non-integer arguments!");
3583 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3584 "getTruncateOrNoop cannot extend!");
3585 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3586 return V; // No conversion
3587 return getTruncateExpr(V, Ty);
3588}
3589
Dan Gohman96212b62009-06-22 00:31:57 +00003590/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3591/// the types using zero-extension, and then perform a umax operation
3592/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003593const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3594 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003595 const SCEV *PromotedLHS = LHS;
3596 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003597
3598 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3599 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3600 else
3601 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3602
3603 return getUMaxExpr(PromotedLHS, PromotedRHS);
3604}
3605
Dan Gohman2bc22302009-06-22 15:03:27 +00003606/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3607/// the types using zero-extension, and then perform a umin operation
3608/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003609const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3610 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003611 const SCEV *PromotedLHS = LHS;
3612 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003613
3614 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3615 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3616 else
3617 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3618
3619 return getUMinExpr(PromotedLHS, PromotedRHS);
3620}
3621
Andrew Trick87716c92011-03-17 23:51:11 +00003622/// getPointerBase - Transitively follow the chain of pointer-type operands
3623/// until reaching a SCEV that does not have a single pointer operand. This
3624/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3625/// but corner cases do exist.
3626const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3627 // A pointer operand may evaluate to a nonpointer expression, such as null.
3628 if (!V->getType()->isPointerTy())
3629 return V;
3630
3631 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3632 return getPointerBase(Cast->getOperand());
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00003633 } else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003634 const SCEV *PtrOp = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003635 for (const SCEV *NAryOp : NAry->operands()) {
3636 if (NAryOp->getType()->isPointerTy()) {
Andrew Trick87716c92011-03-17 23:51:11 +00003637 // Cannot find the base of an expression with multiple pointer operands.
3638 if (PtrOp)
3639 return V;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00003640 PtrOp = NAryOp;
Andrew Trick87716c92011-03-17 23:51:11 +00003641 }
3642 }
3643 if (!PtrOp)
3644 return V;
3645 return getPointerBase(PtrOp);
3646 }
3647 return V;
3648}
3649
Dan Gohman0b89dff2009-07-25 01:13:03 +00003650/// PushDefUseChildren - Push users of the given Instruction
3651/// onto the given Worklist.
3652static void
3653PushDefUseChildren(Instruction *I,
3654 SmallVectorImpl<Instruction *> &Worklist) {
3655 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003656 for (User *U : I->users())
3657 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003658}
3659
3660/// ForgetSymbolicValue - This looks up computed SCEV values for all
3661/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003662/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003663/// resolution.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00003664void ScalarEvolution::forgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003665 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003666 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003667
Dan Gohman0b89dff2009-07-25 01:13:03 +00003668 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003669 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003670 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003671 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00003672 if (!Visited.insert(I).second)
3673 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003674
Sanjoy Das63914592015-10-18 00:29:20 +00003675 auto It = ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003676 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003677 const SCEV *Old = It->second;
3678
Dan Gohman0b89dff2009-07-25 01:13:03 +00003679 // Short-circuit the def-use traversal if the symbolic name
3680 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003681 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003682 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003683
Dan Gohman0b89dff2009-07-25 01:13:03 +00003684 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003685 // structure, it's a PHI that's in the progress of being computed
3686 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3687 // additional loop trip count information isn't going to change anything.
3688 // In the second case, createNodeForPHI will perform the necessary
3689 // updates on its own when it gets to that point. In the third, we do
3690 // want to forget the SCEVUnknown.
3691 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003692 !isa<SCEVUnknown>(Old) ||
3693 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003694 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003695 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003696 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003697 }
3698
3699 PushDefUseChildren(I, Worklist);
3700 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003701}
Chris Lattnerd934c702004-04-02 20:23:17 +00003702
Benjamin Kramer83709b12015-11-16 09:01:28 +00003703namespace {
Silviu Barangaf91c8072015-10-30 15:02:28 +00003704class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
3705public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003706 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003707 ScalarEvolution &SE) {
3708 SCEVInitRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003709 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003710 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3711 }
3712
3713 SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
3714 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3715
3716 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3717 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3718 Valid = false;
3719 return Expr;
3720 }
3721
3722 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3723 // Only allow AddRecExprs for this loop.
3724 if (Expr->getLoop() == L)
3725 return Expr->getStart();
3726 Valid = false;
3727 return Expr;
3728 }
3729
3730 bool isValid() { return Valid; }
3731
3732private:
3733 const Loop *L;
3734 bool Valid;
3735};
3736
3737class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
3738public:
Sanjoy Das807d33d2016-02-20 01:44:10 +00003739 static const SCEV *rewrite(const SCEV *S, const Loop *L,
Silviu Barangaf91c8072015-10-30 15:02:28 +00003740 ScalarEvolution &SE) {
3741 SCEVShiftRewriter Rewriter(L, SE);
Sanjoy Das807d33d2016-02-20 01:44:10 +00003742 const SCEV *Result = Rewriter.visit(S);
Silviu Barangaf91c8072015-10-30 15:02:28 +00003743 return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
3744 }
3745
3746 SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
3747 : SCEVRewriteVisitor(SE), L(L), Valid(true) {}
3748
3749 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
3750 // Only allow AddRecExprs for this loop.
3751 if (!(SE.getLoopDisposition(Expr, L) == ScalarEvolution::LoopInvariant))
3752 Valid = false;
3753 return Expr;
3754 }
3755
3756 const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
3757 if (Expr->getLoop() == L && Expr->isAffine())
3758 return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
3759 Valid = false;
3760 return Expr;
3761 }
3762 bool isValid() { return Valid; }
3763
3764private:
3765 const Loop *L;
3766 bool Valid;
3767};
Benjamin Kramer83709b12015-11-16 09:01:28 +00003768} // end anonymous namespace
Silviu Barangaf91c8072015-10-30 15:02:28 +00003769
Sanjoy Das724f5cf2016-03-03 18:31:29 +00003770SCEV::NoWrapFlags
3771ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
3772 if (!AR->isAffine())
3773 return SCEV::FlagAnyWrap;
3774
3775 typedef OverflowingBinaryOperator OBO;
3776 SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
3777
3778 if (!AR->hasNoSignedWrap()) {
3779 ConstantRange AddRecRange = getSignedRange(AR);
3780 ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
3781
3782 auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3783 Instruction::Add, IncRange, OBO::NoSignedWrap);
3784 if (NSWRegion.contains(AddRecRange))
3785 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
3786 }
3787
3788 if (!AR->hasNoUnsignedWrap()) {
3789 ConstantRange AddRecRange = getUnsignedRange(AR);
3790 ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
3791
3792 auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
3793 Instruction::Add, IncRange, OBO::NoUnsignedWrap);
3794 if (NUWRegion.contains(AddRecRange))
3795 Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
3796 }
3797
3798 return Result;
3799}
3800
Sanjoy Das118d9192016-03-31 05:14:22 +00003801namespace {
3802/// Represents an abstract binary operation. This may exist as a
3803/// normal instruction or constant expression, or may have been
3804/// derived from an expression tree.
3805struct BinaryOp {
3806 unsigned Opcode;
3807 Value *LHS;
3808 Value *RHS;
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003809 bool IsNSW;
3810 bool IsNUW;
Sanjoy Das118d9192016-03-31 05:14:22 +00003811
3812 /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
3813 /// constant expression.
3814 Operator *Op;
3815
3816 explicit BinaryOp(Operator *Op)
3817 : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003818 IsNSW(false), IsNUW(false), Op(Op) {
3819 if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
3820 IsNSW = OBO->hasNoSignedWrap();
3821 IsNUW = OBO->hasNoUnsignedWrap();
3822 }
3823 }
Sanjoy Das118d9192016-03-31 05:14:22 +00003824
Sanjoy Dase12c0e52016-03-31 05:14:26 +00003825 explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
3826 bool IsNUW = false)
3827 : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW),
3828 Op(nullptr) {}
Sanjoy Das118d9192016-03-31 05:14:22 +00003829};
3830}
3831
3832
3833/// Try to map \p V into a BinaryOp, and return \c None on failure.
Sanjoy Das3c529a42016-04-10 22:50:26 +00003834static Optional<BinaryOp> MatchBinaryOp(Value *V, DominatorTree &DT) {
Sanjoy Das118d9192016-03-31 05:14:22 +00003835 auto *Op = dyn_cast<Operator>(V);
3836 if (!Op)
3837 return None;
3838
3839 // Implementation detail: all the cleverness here should happen without
3840 // creating new SCEV expressions -- our caller knowns tricks to avoid creating
3841 // SCEV expressions when possible, and we should not break that.
3842
3843 switch (Op->getOpcode()) {
3844 case Instruction::Add:
3845 case Instruction::Sub:
3846 case Instruction::Mul:
3847 case Instruction::UDiv:
3848 case Instruction::And:
3849 case Instruction::Or:
3850 case Instruction::AShr:
3851 case Instruction::Shl:
3852 return BinaryOp(Op);
3853
3854 case Instruction::Xor:
3855 if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
3856 // If the RHS of the xor is a signbit, then this is just an add.
3857 // Instcombine turns add of signbit into xor as a strength reduction step.
3858 if (RHSC->getValue().isSignBit())
3859 return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
3860 return BinaryOp(Op);
3861
3862 case Instruction::LShr:
3863 // Turn logical shift right of a constant into a unsigned divide.
3864 if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
3865 uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
3866
3867 // If the shift count is not less than the bitwidth, the result of
3868 // the shift is undefined. Don't try to analyze it, because the
3869 // resolution chosen here may differ from the resolution chosen in
3870 // other parts of the compiler.
3871 if (SA->getValue().ult(BitWidth)) {
3872 Constant *X =
3873 ConstantInt::get(SA->getContext(),
3874 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
3875 return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
3876 }
3877 }
3878 return BinaryOp(Op);
3879
Sanjoy Das3c529a42016-04-10 22:50:26 +00003880 case Instruction::ExtractValue: {
3881 auto *EVI = cast<ExtractValueInst>(Op);
3882 if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
3883 break;
3884
3885 auto *CI = dyn_cast<CallInst>(EVI->getAggregateOperand());
3886 if (!CI)
3887 break;
3888
3889 if (auto *F = CI->getCalledFunction())
3890 switch (F->getIntrinsicID()) {
3891 case Intrinsic::sadd_with_overflow:
3892 case Intrinsic::uadd_with_overflow: {
3893 if (!isOverflowIntrinsicNoWrap(cast<IntrinsicInst>(CI), DT))
3894 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3895 CI->getArgOperand(1));
3896
3897 // Now that we know that all uses of the arithmetic-result component of
3898 // CI are guarded by the overflow check, we can go ahead and pretend
3899 // that the arithmetic is non-overflowing.
3900 if (F->getIntrinsicID() == Intrinsic::sadd_with_overflow)
3901 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3902 CI->getArgOperand(1), /* IsNSW = */ true,
3903 /* IsNUW = */ false);
3904 else
3905 return BinaryOp(Instruction::Add, CI->getArgOperand(0),
3906 CI->getArgOperand(1), /* IsNSW = */ false,
3907 /* IsNUW*/ true);
3908 }
3909
3910 case Intrinsic::ssub_with_overflow:
3911 case Intrinsic::usub_with_overflow:
3912 return BinaryOp(Instruction::Sub, CI->getArgOperand(0),
3913 CI->getArgOperand(1));
3914
3915 case Intrinsic::smul_with_overflow:
3916 case Intrinsic::umul_with_overflow:
3917 return BinaryOp(Instruction::Mul, CI->getArgOperand(0),
3918 CI->getArgOperand(1));
3919 default:
3920 break;
3921 }
3922 }
3923
Sanjoy Das118d9192016-03-31 05:14:22 +00003924 default:
3925 break;
3926 }
3927
3928 return None;
3929}
3930
Sanjoy Das55015d22015-10-02 23:09:44 +00003931const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
3932 const Loop *L = LI.getLoopFor(PN->getParent());
3933 if (!L || L->getHeader() != PN->getParent())
3934 return nullptr;
3935
3936 // The loop may have multiple entrances or multiple exits; we can analyze
3937 // this phi as an addrec if it has a unique entry value and a unique
3938 // backedge value.
3939 Value *BEValueV = nullptr, *StartValueV = nullptr;
3940 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3941 Value *V = PN->getIncomingValue(i);
3942 if (L->contains(PN->getIncomingBlock(i))) {
3943 if (!BEValueV) {
3944 BEValueV = V;
3945 } else if (BEValueV != V) {
3946 BEValueV = nullptr;
3947 break;
3948 }
3949 } else if (!StartValueV) {
3950 StartValueV = V;
3951 } else if (StartValueV != V) {
3952 StartValueV = nullptr;
3953 break;
3954 }
3955 }
3956 if (BEValueV && StartValueV) {
3957 // While we are analyzing this PHI node, handle its value symbolically.
3958 const SCEV *SymbolicName = getUnknown(PN);
3959 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
3960 "PHI node already processed?");
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00003961 ValueExprMap.insert({SCEVCallbackVH(PN, this), SymbolicName});
Sanjoy Das55015d22015-10-02 23:09:44 +00003962
3963 // Using this symbolic name for the PHI, analyze the value coming around
3964 // the back-edge.
3965 const SCEV *BEValue = getSCEV(BEValueV);
3966
3967 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3968 // has a special value for the first iteration of the loop.
3969
3970 // If the value coming around the backedge is an add with the symbolic
3971 // value we just inserted, then we found a simple induction variable!
3972 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
3973 // If there is a single occurrence of the symbolic value, replace it
3974 // with a recurrence.
3975 unsigned FoundIndex = Add->getNumOperands();
3976 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3977 if (Add->getOperand(i) == SymbolicName)
3978 if (FoundIndex == e) {
3979 FoundIndex = i;
Dan Gohman6635bb22010-04-12 07:49:36 +00003980 break;
3981 }
Sanjoy Das55015d22015-10-02 23:09:44 +00003982
3983 if (FoundIndex != Add->getNumOperands()) {
3984 // Create an add with everything but the specified operand.
3985 SmallVector<const SCEV *, 8> Ops;
3986 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3987 if (i != FoundIndex)
3988 Ops.push_back(Add->getOperand(i));
3989 const SCEV *Accum = getAddExpr(Ops);
3990
3991 // This is not a valid addrec if the step amount is varying each
3992 // loop iteration, but is not itself an addrec in this loop.
3993 if (isLoopInvariant(Accum, L) ||
3994 (isa<SCEVAddRecExpr>(Accum) &&
3995 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
3996 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
3997
3998 // If the increment doesn't overflow, then neither the addrec nor
3999 // the post-increment will overflow.
Sanjoy Das3c529a42016-04-10 22:50:26 +00004000 if (auto BO = MatchBinaryOp(BEValueV, DT)) {
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004001 if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
4002 if (BO->IsNUW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004003 Flags = setFlags(Flags, SCEV::FlagNUW);
Sanjoy Dase12c0e52016-03-31 05:14:26 +00004004 if (BO->IsNSW)
Sanjoy Das55015d22015-10-02 23:09:44 +00004005 Flags = setFlags(Flags, SCEV::FlagNSW);
4006 }
4007 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
4008 // If the increment is an inbounds GEP, then we know the address
4009 // space cannot be wrapped around. We cannot make any guarantee
4010 // about signed or unsigned overflow because pointers are
4011 // unsigned but we may have a negative index from the base
4012 // pointer. We can guarantee that no unsigned wrap occurs if the
4013 // indices form a positive value.
4014 if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
4015 Flags = setFlags(Flags, SCEV::FlagNW);
4016
4017 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
4018 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
4019 Flags = setFlags(Flags, SCEV::FlagNUW);
4020 }
4021
4022 // We cannot transfer nuw and nsw flags from subtraction
4023 // operations -- sub nuw X, Y is not the same as add nuw X, -Y
4024 // for instance.
4025 }
4026
4027 const SCEV *StartVal = getSCEV(StartValueV);
4028 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
4029
4030 // Since the no-wrap flags are on the increment, they apply to the
4031 // post-incremented value as well.
4032 if (isLoopInvariant(Accum, L))
4033 (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
4034
4035 // Okay, for the entire analysis of this edge we assumed the PHI
4036 // to be symbolic. We now need to go back and purge all of the
4037 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004038 forgetSymbolicName(PN, SymbolicName);
Sanjoy Das55015d22015-10-02 23:09:44 +00004039 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
4040 return PHISCEV;
Dan Gohman6635bb22010-04-12 07:49:36 +00004041 }
4042 }
Silviu Barangaf91c8072015-10-30 15:02:28 +00004043 } else {
Sanjoy Das55015d22015-10-02 23:09:44 +00004044 // Otherwise, this could be a loop like this:
4045 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
4046 // In this case, j = {1,+,1} and BEValue is j.
4047 // Because the other in-value of i (0) fits the evolution of BEValue
4048 // i really is an addrec evolution.
Silviu Barangaf91c8072015-10-30 15:02:28 +00004049 //
4050 // We can generalize this saying that i is the shifted value of BEValue
4051 // by one iteration:
4052 // PHI(f(0), f({1,+,1})) --> f({0,+,1})
4053 const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
4054 const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this);
4055 if (Shifted != getCouldNotCompute() &&
4056 Start != getCouldNotCompute()) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004057 const SCEV *StartVal = getSCEV(StartValueV);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004058 if (Start == StartVal) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004059 // Okay, for the entire analysis of this edge we assumed the PHI
4060 // to be symbolic. We now need to go back and purge all of the
4061 // entries for the scalars that use the symbolic expression.
Sanjoy Dasf1e9cae02016-03-01 19:28:01 +00004062 forgetSymbolicName(PN, SymbolicName);
Silviu Barangaf91c8072015-10-30 15:02:28 +00004063 ValueExprMap[SCEVCallbackVH(PN, this)] = Shifted;
4064 return Shifted;
Chris Lattnerd934c702004-04-02 20:23:17 +00004065 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004066 }
Dan Gohman6635bb22010-04-12 07:49:36 +00004067 }
Tobias Grosser934fcf42016-02-21 18:50:09 +00004068
4069 // Remove the temporary PHI node SCEV that has been inserted while intending
4070 // to create an AddRecExpr for this PHI node. We can not keep this temporary
4071 // as it will prevent later (possibly simpler) SCEV expressions to be added
4072 // to the ValueExprMap.
4073 ValueExprMap.erase(PN);
Sanjoy Das55015d22015-10-02 23:09:44 +00004074 }
4075
4076 return nullptr;
4077}
4078
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004079// Checks if the SCEV S is available at BB. S is considered available at BB
4080// if S can be materialized at BB without introducing a fault.
4081static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
4082 BasicBlock *BB) {
4083 struct CheckAvailable {
4084 bool TraversalDone = false;
4085 bool Available = true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004086
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004087 const Loop *L = nullptr; // The loop BB is in (can be nullptr)
4088 BasicBlock *BB = nullptr;
4089 DominatorTree &DT;
Sanjoy Das55015d22015-10-02 23:09:44 +00004090
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004091 CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
4092 : L(L), BB(BB), DT(DT) {}
Sanjoy Das55015d22015-10-02 23:09:44 +00004093
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004094 bool setUnavailable() {
4095 TraversalDone = true;
4096 Available = false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004097 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004098 }
4099
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004100 bool follow(const SCEV *S) {
4101 switch (S->getSCEVType()) {
4102 case scConstant: case scTruncate: case scZeroExtend: case scSignExtend:
4103 case scAddExpr: case scMulExpr: case scUMaxExpr: case scSMaxExpr:
Sanjoy Dasbb5ffc52015-10-24 05:37:28 +00004104 // These expressions are available if their operand(s) is/are.
4105 return true;
Sanjoy Das55015d22015-10-02 23:09:44 +00004106
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004107 case scAddRecExpr: {
4108 // We allow add recurrences that are on the loop BB is in, or some
4109 // outer loop. This guarantees availability because the value of the
4110 // add recurrence at BB is simply the "current" value of the induction
4111 // variable. We can relax this in the future; for instance an add
4112 // recurrence on a sibling dominating loop is also available at BB.
4113 const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
4114 if (L && (ARLoop == L || ARLoop->contains(L)))
Sanjoy Das55015d22015-10-02 23:09:44 +00004115 return true;
4116
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004117 return setUnavailable();
Sanjoy Das55015d22015-10-02 23:09:44 +00004118 }
4119
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004120 case scUnknown: {
4121 // For SCEVUnknown, we check for simple dominance.
4122 const auto *SU = cast<SCEVUnknown>(S);
4123 Value *V = SU->getValue();
Sanjoy Das55015d22015-10-02 23:09:44 +00004124
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004125 if (isa<Argument>(V))
4126 return false;
Sanjoy Das55015d22015-10-02 23:09:44 +00004127
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004128 if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
4129 return false;
4130
4131 return setUnavailable();
4132 }
4133
4134 case scUDivExpr:
4135 case scCouldNotCompute:
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00004136 // We do not try to smart about these at all.
4137 return setUnavailable();
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004138 }
4139 llvm_unreachable("switch should be fully covered!");
4140 }
4141
4142 bool isDone() { return TraversalDone; }
Sanjoy Das55015d22015-10-02 23:09:44 +00004143 };
4144
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004145 CheckAvailable CA(L, BB, DT);
4146 SCEVTraversal<CheckAvailable> ST(CA);
4147
4148 ST.visitAll(S);
4149 return CA.Available;
4150}
4151
4152// Try to match a control flow sequence that branches out at BI and merges back
4153// at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
4154// match.
4155static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
4156 Value *&C, Value *&LHS, Value *&RHS) {
4157 C = BI->getCondition();
4158
4159 BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
4160 BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
4161
4162 if (!LeftEdge.isSingleEdge())
4163 return false;
4164
4165 assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
4166
4167 Use &LeftUse = Merge->getOperandUse(0);
4168 Use &RightUse = Merge->getOperandUse(1);
4169
4170 if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
4171 LHS = LeftUse;
4172 RHS = RightUse;
4173 return true;
4174 }
4175
4176 if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
4177 LHS = RightUse;
4178 RHS = LeftUse;
4179 return true;
4180 }
4181
4182 return false;
4183}
4184
4185const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
Sanjoy Das55015d22015-10-02 23:09:44 +00004186 if (PN->getNumIncomingValues() == 2) {
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004187 const Loop *L = LI.getLoopFor(PN->getParent());
4188
Sanjoy Das337d4782015-10-31 23:21:40 +00004189 // We don't want to break LCSSA, even in a SCEV expression tree.
4190 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
4191 if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
4192 return nullptr;
4193
Sanjoy Das55015d22015-10-02 23:09:44 +00004194 // Try to match
4195 //
4196 // br %cond, label %left, label %right
4197 // left:
4198 // br label %merge
4199 // right:
4200 // br label %merge
4201 // merge:
4202 // V = phi [ %x, %left ], [ %y, %right ]
4203 //
4204 // as "select %cond, %x, %y"
4205
4206 BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
4207 assert(IDom && "At least the entry block should dominate PN");
4208
4209 auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
4210 Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
4211
Sanjoy Das1cd930b2015-10-03 00:34:19 +00004212 if (BI && BI->isConditional() &&
4213 BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
4214 IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
4215 IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
Sanjoy Das55015d22015-10-02 23:09:44 +00004216 return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
4217 }
4218
4219 return nullptr;
4220}
4221
4222const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
4223 if (const SCEV *S = createAddRecFromPHI(PN))
4224 return S;
4225
4226 if (const SCEV *S = createNodeFromSelectLikePHI(PN))
4227 return S;
Misha Brukman01808ca2005-04-21 21:13:18 +00004228
Dan Gohmana9c205c2010-02-25 06:57:05 +00004229 // If the PHI has a single incoming value, follow that value, unless the
4230 // PHI's incoming blocks are in a different loop, in which case doing so
4231 // risks breaking LCSSA form. Instcombine would normally zap these, but
4232 // it doesn't have DominatorTree information, so it may miss cases.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004233 if (Value *V = SimplifyInstruction(PN, getDataLayout(), &TLI, &DT, &AC))
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004234 if (LI.replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00004235 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00004236
Chris Lattnerd934c702004-04-02 20:23:17 +00004237 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00004238 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00004239}
4240
Sanjoy Das55015d22015-10-02 23:09:44 +00004241const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Instruction *I,
4242 Value *Cond,
4243 Value *TrueVal,
4244 Value *FalseVal) {
Mehdi Amini044cb342015-10-07 18:14:25 +00004245 // Handle "constant" branch or select. This can occur for instance when a
4246 // loop pass transforms an inner loop and moves on to process the outer loop.
4247 if (auto *CI = dyn_cast<ConstantInt>(Cond))
4248 return getSCEV(CI->isOne() ? TrueVal : FalseVal);
4249
Sanjoy Dasd0671342015-10-02 19:39:59 +00004250 // Try to match some simple smax or umax patterns.
4251 auto *ICI = dyn_cast<ICmpInst>(Cond);
4252 if (!ICI)
4253 return getUnknown(I);
4254
4255 Value *LHS = ICI->getOperand(0);
4256 Value *RHS = ICI->getOperand(1);
4257
4258 switch (ICI->getPredicate()) {
4259 case ICmpInst::ICMP_SLT:
4260 case ICmpInst::ICMP_SLE:
4261 std::swap(LHS, RHS);
4262 // fall through
4263 case ICmpInst::ICMP_SGT:
4264 case ICmpInst::ICMP_SGE:
4265 // a >s b ? a+x : b+x -> smax(a, b)+x
4266 // a >s b ? b+x : a+x -> smin(a, b)+x
4267 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4268 const SCEV *LS = getNoopOrSignExtend(getSCEV(LHS), I->getType());
4269 const SCEV *RS = getNoopOrSignExtend(getSCEV(RHS), I->getType());
4270 const SCEV *LA = getSCEV(TrueVal);
4271 const SCEV *RA = getSCEV(FalseVal);
4272 const SCEV *LDiff = getMinusSCEV(LA, LS);
4273 const SCEV *RDiff = getMinusSCEV(RA, RS);
4274 if (LDiff == RDiff)
4275 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4276 LDiff = getMinusSCEV(LA, RS);
4277 RDiff = getMinusSCEV(RA, LS);
4278 if (LDiff == RDiff)
4279 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4280 }
4281 break;
4282 case ICmpInst::ICMP_ULT:
4283 case ICmpInst::ICMP_ULE:
4284 std::swap(LHS, RHS);
4285 // fall through
4286 case ICmpInst::ICMP_UGT:
4287 case ICmpInst::ICMP_UGE:
4288 // a >u b ? a+x : b+x -> umax(a, b)+x
4289 // a >u b ? b+x : a+x -> umin(a, b)+x
4290 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType())) {
4291 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4292 const SCEV *RS = getNoopOrZeroExtend(getSCEV(RHS), I->getType());
4293 const SCEV *LA = getSCEV(TrueVal);
4294 const SCEV *RA = getSCEV(FalseVal);
4295 const SCEV *LDiff = getMinusSCEV(LA, LS);
4296 const SCEV *RDiff = getMinusSCEV(RA, RS);
4297 if (LDiff == RDiff)
4298 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4299 LDiff = getMinusSCEV(LA, RS);
4300 RDiff = getMinusSCEV(RA, LS);
4301 if (LDiff == RDiff)
4302 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4303 }
4304 break;
4305 case ICmpInst::ICMP_NE:
4306 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4307 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4308 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4309 const SCEV *One = getOne(I->getType());
4310 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4311 const SCEV *LA = getSCEV(TrueVal);
4312 const SCEV *RA = getSCEV(FalseVal);
4313 const SCEV *LDiff = getMinusSCEV(LA, LS);
4314 const SCEV *RDiff = getMinusSCEV(RA, One);
4315 if (LDiff == RDiff)
4316 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4317 }
4318 break;
4319 case ICmpInst::ICMP_EQ:
4320 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4321 if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(I->getType()) &&
4322 isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
4323 const SCEV *One = getOne(I->getType());
4324 const SCEV *LS = getNoopOrZeroExtend(getSCEV(LHS), I->getType());
4325 const SCEV *LA = getSCEV(TrueVal);
4326 const SCEV *RA = getSCEV(FalseVal);
4327 const SCEV *LDiff = getMinusSCEV(LA, One);
4328 const SCEV *RDiff = getMinusSCEV(RA, LS);
4329 if (LDiff == RDiff)
4330 return getAddExpr(getUMaxExpr(One, LS), LDiff);
4331 }
4332 break;
4333 default:
4334 break;
4335 }
4336
4337 return getUnknown(I);
4338}
4339
Dan Gohmanee750d12009-05-08 20:26:55 +00004340/// createNodeForGEP - Expand GEP instructions into add and multiply
4341/// operations. This allows them to be analyzed by regular SCEV code.
4342///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004343const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Dan Gohman30f24fe2009-05-09 00:14:52 +00004344 // Don't attempt to analyze GEPs over unsized objects.
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004345 if (!GEP->getSourceElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00004346 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00004347
Jingyue Wu2982d4d2015-05-18 17:03:25 +00004348 SmallVector<const SCEV *, 4> IndexExprs;
4349 for (auto Index = GEP->idx_begin(); Index != GEP->idx_end(); ++Index)
4350 IndexExprs.push_back(getSCEV(*Index));
Eduard Burtescu19eb0312016-01-19 17:28:00 +00004351 return getGEPExpr(GEP->getSourceElementType(),
4352 getSCEV(GEP->getPointerOperand()),
4353 IndexExprs, GEP->isInBounds());
Dan Gohmanee750d12009-05-08 20:26:55 +00004354}
4355
Nick Lewycky3783b462007-11-22 07:59:40 +00004356/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
4357/// guaranteed to end in (at every loop iteration). It is, at the same time,
4358/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
4359/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004360uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00004361ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00004362 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004363 return C->getAPInt().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00004364
Dan Gohmana30370b2009-05-04 22:02:23 +00004365 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00004366 return std::min(GetMinTrailingZeros(T->getOperand()),
4367 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00004368
Dan Gohmana30370b2009-05-04 22:02:23 +00004369 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004370 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4371 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4372 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004373 }
4374
Dan Gohmana30370b2009-05-04 22:02:23 +00004375 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00004376 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
4377 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
4378 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00004379 }
4380
Dan Gohmana30370b2009-05-04 22:02:23 +00004381 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004382 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004383 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004384 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004385 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004386 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004387 }
4388
Dan Gohmana30370b2009-05-04 22:02:23 +00004389 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004390 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004391 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
4392 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00004393 for (unsigned i = 1, e = M->getNumOperands();
4394 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004395 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00004396 BitWidth);
4397 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004398 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004399
Dan Gohmana30370b2009-05-04 22:02:23 +00004400 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00004401 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004402 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00004403 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004404 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00004405 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00004406 }
Nick Lewycky3783b462007-11-22 07:59:40 +00004407
Dan Gohmana30370b2009-05-04 22:02:23 +00004408 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004409 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004410 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004411 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004412 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00004413 return MinOpRes;
4414 }
4415
Dan Gohmana30370b2009-05-04 22:02:23 +00004416 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004417 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00004418 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004419 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00004420 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00004421 return MinOpRes;
4422 }
4423
Dan Gohmanc702fc02009-06-19 23:29:04 +00004424 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
4425 // For a SCEVUnknown, ask ValueTracking.
4426 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00004427 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004428 computeKnownBits(U->getValue(), Zeros, Ones, getDataLayout(), 0, &AC,
4429 nullptr, &DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004430 return Zeros.countTrailingOnes();
4431 }
4432
4433 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00004434 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00004435}
Chris Lattnerd934c702004-04-02 20:23:17 +00004436
Sanjoy Das1f05c512014-10-10 21:22:34 +00004437/// GetRangeFromMetadata - Helper method to assign a range to V from
4438/// metadata present in the IR.
4439static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
Sanjoy Dasa7e13782015-10-24 05:37:35 +00004440 if (Instruction *I = dyn_cast<Instruction>(V))
4441 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
4442 return getConstantRangeFromMetadata(*MD);
Sanjoy Das1f05c512014-10-10 21:22:34 +00004443
4444 return None;
4445}
4446
Sanjoy Das91b54772015-03-09 21:43:43 +00004447/// getRange - Determine the range for a particular SCEV. If SignHint is
4448/// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
4449/// with a "cleaner" unsigned (resp. signed) representation.
Dan Gohmane65c9172009-07-13 21:35:55 +00004450///
4451ConstantRange
Sanjoy Das91b54772015-03-09 21:43:43 +00004452ScalarEvolution::getRange(const SCEV *S,
4453 ScalarEvolution::RangeSignHint SignHint) {
4454 DenseMap<const SCEV *, ConstantRange> &Cache =
4455 SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
4456 : SignedRanges;
4457
Dan Gohman761065e2010-11-17 02:44:44 +00004458 // See if we've computed this range already.
Sanjoy Das91b54772015-03-09 21:43:43 +00004459 DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
4460 if (I != Cache.end())
Dan Gohman761065e2010-11-17 02:44:44 +00004461 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00004462
4463 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004464 return setRange(C, SignHint, ConstantRange(C->getAPInt()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00004465
Dan Gohman85be4332010-01-26 19:19:05 +00004466 unsigned BitWidth = getTypeSizeInBits(S->getType());
4467 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
4468
Sanjoy Das91b54772015-03-09 21:43:43 +00004469 // If the value has known zeros, the maximum value will have those known zeros
4470 // as well.
Dan Gohman85be4332010-01-26 19:19:05 +00004471 uint32_t TZ = GetMinTrailingZeros(S);
Sanjoy Das91b54772015-03-09 21:43:43 +00004472 if (TZ != 0) {
4473 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
4474 ConservativeResult =
4475 ConstantRange(APInt::getMinValue(BitWidth),
4476 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
4477 else
4478 ConservativeResult = ConstantRange(
4479 APInt::getSignedMinValue(BitWidth),
4480 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
4481 }
Dan Gohman85be4332010-01-26 19:19:05 +00004482
Dan Gohmane65c9172009-07-13 21:35:55 +00004483 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004484 ConstantRange X = getRange(Add->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004485 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004486 X = X.add(getRange(Add->getOperand(i), SignHint));
4487 return setRange(Add, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004488 }
4489
4490 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004491 ConstantRange X = getRange(Mul->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004492 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004493 X = X.multiply(getRange(Mul->getOperand(i), SignHint));
4494 return setRange(Mul, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004495 }
4496
4497 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004498 ConstantRange X = getRange(SMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004499 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004500 X = X.smax(getRange(SMax->getOperand(i), SignHint));
4501 return setRange(SMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004502 }
4503
4504 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004505 ConstantRange X = getRange(UMax->getOperand(0), SignHint);
Dan Gohmane65c9172009-07-13 21:35:55 +00004506 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
Sanjoy Das91b54772015-03-09 21:43:43 +00004507 X = X.umax(getRange(UMax->getOperand(i), SignHint));
4508 return setRange(UMax, SignHint, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00004509 }
4510
4511 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004512 ConstantRange X = getRange(UDiv->getLHS(), SignHint);
4513 ConstantRange Y = getRange(UDiv->getRHS(), SignHint);
4514 return setRange(UDiv, SignHint,
4515 ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004516 }
4517
4518 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004519 ConstantRange X = getRange(ZExt->getOperand(), SignHint);
4520 return setRange(ZExt, SignHint,
4521 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004522 }
4523
4524 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004525 ConstantRange X = getRange(SExt->getOperand(), SignHint);
4526 return setRange(SExt, SignHint,
4527 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004528 }
4529
4530 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
Sanjoy Das91b54772015-03-09 21:43:43 +00004531 ConstantRange X = getRange(Trunc->getOperand(), SignHint);
4532 return setRange(Trunc, SignHint,
4533 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004534 }
4535
Dan Gohmane65c9172009-07-13 21:35:55 +00004536 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004537 // If there's no unsigned wrap, the value will never be less than its
4538 // initial value.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004539 if (AddRec->hasNoUnsignedWrap())
Dan Gohman51ad99d2010-01-21 02:09:26 +00004540 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00004541 if (!C->getValue()->isZero())
Sanjoy Das0de2fec2015-12-17 20:28:46 +00004542 ConservativeResult = ConservativeResult.intersectWith(
4543 ConstantRange(C->getAPInt(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00004544
Dan Gohman51ad99d2010-01-21 02:09:26 +00004545 // If there's no signed wrap, and all the operands have the same sign or
4546 // zero, the value won't ever change sign.
Sanjoy Das76c48e02016-02-04 18:21:54 +00004547 if (AddRec->hasNoSignedWrap()) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00004548 bool AllNonNeg = true;
4549 bool AllNonPos = true;
4550 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
4551 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
4552 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
4553 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004554 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00004555 ConservativeResult = ConservativeResult.intersectWith(
4556 ConstantRange(APInt(BitWidth, 0),
4557 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004558 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00004559 ConservativeResult = ConservativeResult.intersectWith(
4560 ConstantRange(APInt::getSignedMinValue(BitWidth),
4561 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00004562 }
Dan Gohmane65c9172009-07-13 21:35:55 +00004563
4564 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00004565 if (AddRec->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00004566 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00004567 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
4568 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Sanjoy Dasb765b632016-03-02 00:57:39 +00004569 auto RangeFromAffine = getRangeForAffineAR(
4570 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4571 BitWidth);
4572 if (!RangeFromAffine.isFullSet())
4573 ConservativeResult =
4574 ConservativeResult.intersectWith(RangeFromAffine);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004575
4576 auto RangeFromFactoring = getRangeViaFactoring(
4577 AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
4578 BitWidth);
4579 if (!RangeFromFactoring.isFullSet())
4580 ConservativeResult =
4581 ConservativeResult.intersectWith(RangeFromFactoring);
Dan Gohmand261d272009-06-24 01:05:09 +00004582 }
Dan Gohmand261d272009-06-24 01:05:09 +00004583 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00004584
Sanjoy Das91b54772015-03-09 21:43:43 +00004585 return setRange(AddRec, SignHint, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00004586 }
4587
Dan Gohmanc702fc02009-06-19 23:29:04 +00004588 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00004589 // Check if the IR explicitly contains !range metadata.
4590 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
4591 if (MDRange.hasValue())
4592 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
4593
Sanjoy Das91b54772015-03-09 21:43:43 +00004594 // Split here to avoid paying the compile-time cost of calling both
4595 // computeKnownBits and ComputeNumSignBits. This restriction can be lifted
4596 // if needed.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00004597 const DataLayout &DL = getDataLayout();
Sanjoy Das91b54772015-03-09 21:43:43 +00004598 if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED) {
4599 // For a SCEVUnknown, ask ValueTracking.
4600 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004601 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, &AC, nullptr, &DT);
Sanjoy Das91b54772015-03-09 21:43:43 +00004602 if (Ones != ~Zeros + 1)
4603 ConservativeResult =
4604 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1));
4605 } else {
4606 assert(SignHint == ScalarEvolution::HINT_RANGE_SIGNED &&
4607 "generalize as needed!");
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004608 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004609 if (NS > 1)
4610 ConservativeResult = ConservativeResult.intersectWith(
4611 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
4612 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1));
Sanjoy Das91b54772015-03-09 21:43:43 +00004613 }
4614
4615 return setRange(U, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004616 }
4617
Sanjoy Das91b54772015-03-09 21:43:43 +00004618 return setRange(S, SignHint, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00004619}
4620
Sanjoy Dasb765b632016-03-02 00:57:39 +00004621ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
4622 const SCEV *Step,
4623 const SCEV *MaxBECount,
4624 unsigned BitWidth) {
4625 assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
4626 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
4627 "Precondition!");
4628
4629 ConstantRange Result(BitWidth, /* isFullSet = */ true);
4630
4631 // Check for overflow. This must be done with ConstantRange arithmetic
4632 // because we could be called from within the ScalarEvolution overflow
4633 // checking code.
4634
4635 MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
4636 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
4637 ConstantRange ZExtMaxBECountRange =
4638 MaxBECountRange.zextOrTrunc(BitWidth * 2 + 1);
4639
4640 ConstantRange StepSRange = getSignedRange(Step);
4641 ConstantRange SExtStepSRange = StepSRange.sextOrTrunc(BitWidth * 2 + 1);
4642
4643 ConstantRange StartURange = getUnsignedRange(Start);
4644 ConstantRange EndURange =
4645 StartURange.add(MaxBECountRange.multiply(StepSRange));
4646
4647 // Check for unsigned overflow.
4648 ConstantRange ZExtStartURange = StartURange.zextOrTrunc(BitWidth * 2 + 1);
4649 ConstantRange ZExtEndURange = EndURange.zextOrTrunc(BitWidth * 2 + 1);
4650 if (ZExtStartURange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4651 ZExtEndURange) {
4652 APInt Min = APIntOps::umin(StartURange.getUnsignedMin(),
4653 EndURange.getUnsignedMin());
4654 APInt Max = APIntOps::umax(StartURange.getUnsignedMax(),
4655 EndURange.getUnsignedMax());
4656 bool IsFullRange = Min.isMinValue() && Max.isMaxValue();
4657 if (!IsFullRange)
4658 Result =
4659 Result.intersectWith(ConstantRange(Min, Max + 1));
4660 }
4661
4662 ConstantRange StartSRange = getSignedRange(Start);
4663 ConstantRange EndSRange =
4664 StartSRange.add(MaxBECountRange.multiply(StepSRange));
4665
4666 // Check for signed overflow. This must be done with ConstantRange
4667 // arithmetic because we could be called from within the ScalarEvolution
4668 // overflow checking code.
4669 ConstantRange SExtStartSRange = StartSRange.sextOrTrunc(BitWidth * 2 + 1);
4670 ConstantRange SExtEndSRange = EndSRange.sextOrTrunc(BitWidth * 2 + 1);
4671 if (SExtStartSRange.add(ZExtMaxBECountRange.multiply(SExtStepSRange)) ==
4672 SExtEndSRange) {
4673 APInt Min =
4674 APIntOps::smin(StartSRange.getSignedMin(), EndSRange.getSignedMin());
4675 APInt Max =
4676 APIntOps::smax(StartSRange.getSignedMax(), EndSRange.getSignedMax());
4677 bool IsFullRange = Min.isMinSignedValue() && Max.isMaxSignedValue();
4678 if (!IsFullRange)
4679 Result =
4680 Result.intersectWith(ConstantRange(Min, Max + 1));
4681 }
4682
4683 return Result;
4684}
4685
Sanjoy Dasbf730982016-03-02 00:57:54 +00004686ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
4687 const SCEV *Step,
4688 const SCEV *MaxBECount,
4689 unsigned BitWidth) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004690 // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
4691 // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
4692
4693 struct SelectPattern {
4694 Value *Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004695 APInt TrueValue;
4696 APInt FalseValue;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004697
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004698 explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
4699 const SCEV *S) {
4700 Optional<unsigned> CastOp;
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004701 APInt Offset(BitWidth, 0);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004702
4703 assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
4704 "Should be!");
4705
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004706 // Peel off a constant offset:
4707 if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
4708 // In the future we could consider being smarter here and handle
4709 // {Start+Step,+,Step} too.
4710 if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
4711 return;
4712
4713 Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
4714 S = SA->getOperand(1);
4715 }
4716
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004717 // Peel off a cast operation
4718 if (auto *SCast = dyn_cast<SCEVCastExpr>(S)) {
4719 CastOp = SCast->getSCEVType();
4720 S = SCast->getOperand();
4721 }
4722
Sanjoy Dasbf730982016-03-02 00:57:54 +00004723 using namespace llvm::PatternMatch;
4724
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004725 auto *SU = dyn_cast<SCEVUnknown>(S);
4726 const APInt *TrueVal, *FalseVal;
4727 if (!SU ||
4728 !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
4729 m_APInt(FalseVal)))) {
Sanjoy Dasbf730982016-03-02 00:57:54 +00004730 Condition = nullptr;
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004731 return;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004732 }
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004733
4734 TrueValue = *TrueVal;
4735 FalseValue = *FalseVal;
4736
4737 // Re-apply the cast we peeled off earlier
4738 if (CastOp.hasValue())
4739 switch (*CastOp) {
4740 default:
4741 llvm_unreachable("Unknown SCEV cast type!");
4742
4743 case scTruncate:
4744 TrueValue = TrueValue.trunc(BitWidth);
4745 FalseValue = FalseValue.trunc(BitWidth);
4746 break;
4747 case scZeroExtend:
4748 TrueValue = TrueValue.zext(BitWidth);
4749 FalseValue = FalseValue.zext(BitWidth);
4750 break;
4751 case scSignExtend:
4752 TrueValue = TrueValue.sext(BitWidth);
4753 FalseValue = FalseValue.sext(BitWidth);
4754 break;
4755 }
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004756
4757 // Re-apply the constant offset we peeled off earlier
4758 TrueValue += Offset;
4759 FalseValue += Offset;
Sanjoy Dasbf730982016-03-02 00:57:54 +00004760 }
4761
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004762 bool isRecognized() { return Condition != nullptr; }
Sanjoy Dasbf730982016-03-02 00:57:54 +00004763 };
4764
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004765 SelectPattern StartPattern(*this, BitWidth, Start);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004766 if (!StartPattern.isRecognized())
4767 return ConstantRange(BitWidth, /* isFullSet = */ true);
4768
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004769 SelectPattern StepPattern(*this, BitWidth, Step);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004770 if (!StepPattern.isRecognized())
4771 return ConstantRange(BitWidth, /* isFullSet = */ true);
4772
4773 if (StartPattern.Condition != StepPattern.Condition) {
4774 // We don't handle this case today; but we could, by considering four
4775 // possibilities below instead of two. I'm not sure if there are cases where
4776 // that will help over what getRange already does, though.
4777 return ConstantRange(BitWidth, /* isFullSet = */ true);
4778 }
4779
4780 // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
4781 // construct arbitrary general SCEV expressions here. This function is called
4782 // from deep in the call stack, and calling getSCEV (on a sext instruction,
4783 // say) can end up caching a suboptimal value.
4784
Sanjoy Das6b017a12016-03-02 02:56:29 +00004785 // FIXME: without the explicit `this` receiver below, MSVC errors out with
4786 // C2352 and C2512 (otherwise it isn't needed).
4787
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004788 const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004789 const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
Sanjoy Das97d19bd2016-03-09 01:51:02 +00004790 const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
Sanjoy Dasd3488c62016-03-09 01:50:57 +00004791 const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
Sanjoy Das62a1c332016-03-02 02:15:42 +00004792
Sanjoy Das1168f932016-03-02 02:34:20 +00004793 ConstantRange TrueRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004794 this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
Sanjoy Das1168f932016-03-02 02:34:20 +00004795 ConstantRange FalseRange =
Sanjoy Daseca1b532016-03-02 02:44:08 +00004796 this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
Sanjoy Dasbf730982016-03-02 00:57:54 +00004797
4798 return TrueRange.unionWith(FalseRange);
4799}
4800
Jingyue Wu42f1d672015-07-28 18:22:40 +00004801SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00004802 if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004803 const BinaryOperator *BinOp = cast<BinaryOperator>(V);
4804
4805 // Return early if there are no flags to propagate to the SCEV.
4806 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4807 if (BinOp->hasNoUnsignedWrap())
4808 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
4809 if (BinOp->hasNoSignedWrap())
4810 Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004811 if (Flags == SCEV::FlagAnyWrap)
Jingyue Wu42f1d672015-07-28 18:22:40 +00004812 return SCEV::FlagAnyWrap;
Jingyue Wu42f1d672015-07-28 18:22:40 +00004813
4814 // Here we check that BinOp is in the header of the innermost loop
4815 // containing BinOp, since we only deal with instructions in the loop
4816 // header. The actual loop we need to check later will come from an add
4817 // recurrence, but getting that requires computing the SCEV of the operands,
4818 // which can be expensive. This check we can do cheaply to rule out some
4819 // cases early.
Sanjoy Dasdcd3a882016-03-02 04:52:22 +00004820 Loop *InnermostContainingLoop = LI.getLoopFor(BinOp->getParent());
4821 if (InnermostContainingLoop == nullptr ||
4822 InnermostContainingLoop->getHeader() != BinOp->getParent())
Jingyue Wu42f1d672015-07-28 18:22:40 +00004823 return SCEV::FlagAnyWrap;
4824
4825 // Only proceed if we can prove that BinOp does not yield poison.
4826 if (!isKnownNotFullPoison(BinOp)) return SCEV::FlagAnyWrap;
4827
4828 // At this point we know that if V is executed, then it does not wrap
4829 // according to at least one of NSW or NUW. If V is not executed, then we do
4830 // not know if the calculation that V represents would wrap. Multiple
4831 // instructions can map to the same SCEV. If we apply NSW or NUW from V to
4832 // the SCEV, we must guarantee no wrapping for that SCEV also when it is
4833 // derived from other instructions that map to the same SCEV. We cannot make
4834 // that guarantee for cases where V is not executed. So we need to find the
4835 // loop that V is considered in relation to and prove that V is executed for
4836 // every iteration of that loop. That implies that the value that V
4837 // calculates does not wrap anywhere in the loop, so then we can apply the
4838 // flags to the SCEV.
4839 //
4840 // We check isLoopInvariant to disambiguate in case we are adding two
4841 // recurrences from different loops, so that we know which loop to prove
4842 // that V is executed in.
4843 for (int OpIndex = 0; OpIndex < 2; ++OpIndex) {
4844 const SCEV *Op = getSCEV(BinOp->getOperand(OpIndex));
4845 if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
4846 const int OtherOpIndex = 1 - OpIndex;
4847 const SCEV *OtherOp = getSCEV(BinOp->getOperand(OtherOpIndex));
4848 if (isLoopInvariant(OtherOp, AddRec->getLoop()) &&
4849 isGuaranteedToExecuteForEveryIteration(BinOp, AddRec->getLoop()))
4850 return Flags;
4851 }
4852 }
4853 return SCEV::FlagAnyWrap;
4854}
4855
4856/// createSCEV - We know that there is no SCEV for the specified value. Analyze
4857/// the expression.
Chris Lattnerd934c702004-04-02 20:23:17 +00004858///
Dan Gohmanaf752342009-07-07 17:06:11 +00004859const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004860 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004861 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004862
Dan Gohman69451a02010-03-09 23:46:50 +00004863 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman69451a02010-03-09 23:46:50 +00004864 // Don't attempt to analyze instructions in blocks that aren't
4865 // reachable. Such instructions don't matter, and they aren't required
4866 // to obey basic rules for definitions dominating uses which this
4867 // analysis depends on.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00004868 if (!DT.isReachableFromEntry(I->getParent()))
Dan Gohman69451a02010-03-09 23:46:50 +00004869 return getUnknown(V);
Sanjoy Das260ad4d2016-03-29 16:40:39 +00004870 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohmanf436bac2009-06-24 00:54:57 +00004871 return getConstant(CI);
4872 else if (isa<ConstantPointerNull>(V))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00004873 return getZero(V->getType());
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004874 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
Sanjoy Das5ce32722016-04-08 00:48:30 +00004875 return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
Sanjoy Das260ad4d2016-03-29 16:40:39 +00004876 else if (!isa<ConstantExpr>(V))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004877 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004878
Dan Gohman80ca01c2009-07-17 20:47:02 +00004879 Operator *U = cast<Operator>(V);
Sanjoy Das3c529a42016-04-10 22:50:26 +00004880 if (auto BO = MatchBinaryOp(U, DT)) {
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004881 switch (BO->Opcode) {
4882 case Instruction::Add: {
4883 // The simple thing to do would be to just call getSCEV on both operands
4884 // and call getAddExpr with the result. However if we're looking at a
4885 // bunch of things all added together, this can be quite inefficient,
4886 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4887 // Instead, gather up all the operands and make a single getAddExpr call.
4888 // LLVM IR canonical form means we need only traverse the left operands.
4889 SmallVector<const SCEV *, 4> AddOps;
4890 do {
4891 if (BO->Op) {
4892 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
4893 AddOps.push_back(OpSCEV);
4894 break;
4895 }
Jingyue Wu42f1d672015-07-28 18:22:40 +00004896
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004897 // If a NUW or NSW flag can be applied to the SCEV for this
4898 // addition, then compute the SCEV for this addition by itself
4899 // with a separate call to getAddExpr. We need to do that
4900 // instead of pushing the operands of the addition onto AddOps,
4901 // since the flags are only known to apply to this particular
4902 // addition - they may not apply to other additions that can be
4903 // formed with operands from AddOps.
4904 const SCEV *RHS = getSCEV(BO->RHS);
4905 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
4906 if (Flags != SCEV::FlagAnyWrap) {
4907 const SCEV *LHS = getSCEV(BO->LHS);
4908 if (BO->Opcode == Instruction::Sub)
4909 AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
4910 else
4911 AddOps.push_back(getAddExpr(LHS, RHS, Flags));
4912 break;
4913 }
Dan Gohman36bad002009-09-17 18:05:20 +00004914 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004915
4916 if (BO->Opcode == Instruction::Sub)
4917 AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
4918 else
4919 AddOps.push_back(getSCEV(BO->RHS));
4920
Sanjoy Das3c529a42016-04-10 22:50:26 +00004921 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004922 if (!NewBO || (NewBO->Opcode != Instruction::Add &&
4923 NewBO->Opcode != Instruction::Sub)) {
4924 AddOps.push_back(getSCEV(BO->LHS));
4925 break;
4926 }
4927 BO = NewBO;
4928 } while (true);
4929
4930 return getAddExpr(AddOps);
4931 }
4932
4933 case Instruction::Mul: {
4934 SmallVector<const SCEV *, 4> MulOps;
4935 do {
4936 if (BO->Op) {
4937 if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
4938 MulOps.push_back(OpSCEV);
4939 break;
4940 }
4941
4942 SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
4943 if (Flags != SCEV::FlagAnyWrap) {
4944 MulOps.push_back(
4945 getMulExpr(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags));
4946 break;
4947 }
4948 }
4949
4950 MulOps.push_back(getSCEV(BO->RHS));
Sanjoy Das3c529a42016-04-10 22:50:26 +00004951 auto NewBO = MatchBinaryOp(BO->LHS, DT);
Sanjoy Das2381fcd2016-03-29 16:40:44 +00004952 if (!NewBO || NewBO->Opcode != Instruction::Mul) {
4953 MulOps.push_back(getSCEV(BO->LHS));
4954 break;
4955 }
4956 BO = NewBO;
4957 } while (true);
4958
4959 return getMulExpr(MulOps);
4960 }
4961 case Instruction::UDiv:
4962 return getUDivExpr(getSCEV(BO->LHS), getSCEV(BO->RHS));
4963 case Instruction::Sub: {
4964 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
4965 if (BO->Op)
4966 Flags = getNoWrapFlagsFromUB(BO->Op);
4967 return getMinusSCEV(getSCEV(BO->LHS), getSCEV(BO->RHS), Flags);
4968 }
4969 case Instruction::And:
4970 // For an expression like x&255 that merely masks off the high bits,
4971 // use zext(trunc(x)) as the SCEV expression.
4972 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
4973 if (CI->isNullValue())
4974 return getSCEV(BO->RHS);
4975 if (CI->isAllOnesValue())
4976 return getSCEV(BO->LHS);
4977 const APInt &A = CI->getValue();
4978
4979 // Instcombine's ShrinkDemandedConstant may strip bits out of
4980 // constants, obscuring what would otherwise be a low-bits mask.
4981 // Use computeKnownBits to compute what ShrinkDemandedConstant
4982 // knew about to reconstruct a low-bits mask value.
4983 unsigned LZ = A.countLeadingZeros();
4984 unsigned TZ = A.countTrailingZeros();
4985 unsigned BitWidth = A.getBitWidth();
4986 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4987 computeKnownBits(BO->LHS, KnownZero, KnownOne, getDataLayout(),
4988 0, &AC, nullptr, &DT);
4989
4990 APInt EffectiveMask =
4991 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4992 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4993 const SCEV *MulCount = getConstant(ConstantInt::get(
4994 getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4995 return getMulExpr(
4996 getZeroExtendExpr(
4997 getTruncateExpr(
4998 getUDivExactExpr(getSCEV(BO->LHS), MulCount),
4999 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
5000 BO->LHS->getType()),
5001 MulCount);
5002 }
Dan Gohman36bad002009-09-17 18:05:20 +00005003 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005004 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005005
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005006 case Instruction::Or:
5007 // If the RHS of the Or is a constant, we may have something like:
5008 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
5009 // optimizations will transparently handle this case.
5010 //
5011 // In order for this transformation to be safe, the LHS must be of the
5012 // form X*(2^n) and the Or constant must be less than 2^n.
5013 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5014 const SCEV *LHS = getSCEV(BO->LHS);
5015 const APInt &CIVal = CI->getValue();
5016 if (GetMinTrailingZeros(LHS) >=
5017 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
5018 // Build a plain add SCEV.
5019 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
5020 // If the LHS of the add was an addrec and it has no-wrap flags,
5021 // transfer the no-wrap flags, since an or won't introduce a wrap.
5022 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
5023 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
5024 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
5025 OldAR->getNoWrapFlags());
5026 }
5027 return S;
5028 }
5029 }
5030 break;
Dan Gohman6350296e2009-05-18 16:29:04 +00005031
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005032 case Instruction::Xor:
5033 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
5034 // If the RHS of xor is -1, then this is a not operation.
5035 if (CI->isAllOnesValue())
5036 return getNotSCEV(getSCEV(BO->LHS));
Dan Gohmaneddf7712009-06-18 00:00:20 +00005037
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005038 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
5039 // This is a variant of the check for xor with -1, and it handles
5040 // the case where instcombine has trimmed non-demanded bits out
5041 // of an xor with -1.
5042 if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
5043 if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
5044 if (LBO->getOpcode() == Instruction::And &&
5045 LCI->getValue() == CI->getValue())
5046 if (const SCEVZeroExtendExpr *Z =
5047 dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
5048 Type *UTy = BO->LHS->getType();
5049 const SCEV *Z0 = Z->getOperand();
5050 Type *Z0Ty = Z0->getType();
5051 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
Dan Gohmaneddf7712009-06-18 00:00:20 +00005052
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005053 // If C is a low-bits mask, the zero extend is serving to
5054 // mask off the high bits. Complement the operand and
5055 // re-apply the zext.
5056 if (APIntOps::isMask(Z0TySize, CI->getValue()))
5057 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
5058
5059 // If C is a single bit, it may be in the sign-bit position
5060 // before the zero-extend. In this case, represent the xor
5061 // using an add, which is equivalent, and re-apply the zext.
5062 APInt Trunc = CI->getValue().trunc(Z0TySize);
5063 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
5064 Trunc.isSignBit())
5065 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
5066 UTy);
5067 }
5068 }
5069 break;
Dan Gohman05e89732008-06-22 19:56:46 +00005070
5071 case Instruction::Shl:
5072 // Turn shift left of a constant amount into a multiply.
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005073 if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
5074 uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00005075
5076 // If the shift count is not less than the bitwidth, the result of
5077 // the shift is undefined. Don't try to analyze it, because the
5078 // resolution chosen here may differ from the resolution chosen in
5079 // other parts of the compiler.
5080 if (SA->getValue().uge(BitWidth))
5081 break;
5082
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005083 // It is currently not resolved how to interpret NSW for left
5084 // shift by BitWidth - 1, so we avoid applying flags in that
5085 // case. Remove this check (or this comment) once the situation
5086 // is resolved. See
5087 // http://lists.llvm.org/pipermail/llvm-dev/2015-April/084195.html
5088 // and http://reviews.llvm.org/D8890 .
5089 auto Flags = SCEV::FlagAnyWrap;
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005090 if (BO->Op && SA->getValue().ult(BitWidth - 1))
5091 Flags = getNoWrapFlagsFromUB(BO->Op);
Bjarke Hammersholt Roune9791ed42015-08-14 22:45:26 +00005092
Owen Andersonedb4a702009-07-24 23:12:02 +00005093 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00005094 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005095 return getMulExpr(getSCEV(BO->LHS), getSCEV(X), Flags);
Dan Gohman05e89732008-06-22 19:56:46 +00005096 }
5097 break;
5098
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005099 case Instruction::AShr:
5100 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
5101 if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS))
5102 if (Operator *L = dyn_cast<Operator>(BO->LHS))
5103 if (L->getOpcode() == Instruction::Shl &&
5104 L->getOperand(1) == BO->RHS) {
5105 uint64_t BitWidth = getTypeSizeInBits(BO->LHS->getType());
Dan Gohmanacd700a2010-04-22 01:35:11 +00005106
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005107 // If the shift count is not less than the bitwidth, the result of
5108 // the shift is undefined. Don't try to analyze it, because the
5109 // resolution chosen here may differ from the resolution chosen in
5110 // other parts of the compiler.
5111 if (CI->getValue().uge(BitWidth))
5112 break;
Dan Gohmanacd700a2010-04-22 01:35:11 +00005113
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005114 uint64_t Amt = BitWidth - CI->getZExtValue();
5115 if (Amt == BitWidth)
5116 return getSCEV(L->getOperand(0)); // shift by zero --> noop
5117 return getSignExtendExpr(
5118 getTruncateExpr(getSCEV(L->getOperand(0)),
5119 IntegerType::get(getContext(), Amt)),
5120 BO->LHS->getType());
5121 }
5122 break;
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005123 }
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005124 }
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00005125
Sanjoy Das2381fcd2016-03-29 16:40:44 +00005126 switch (U->getOpcode()) {
Dan Gohman05e89732008-06-22 19:56:46 +00005127 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005128 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005129
5130 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005131 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005132
5133 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00005134 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00005135
5136 case Instruction::BitCast:
5137 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00005138 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00005139 return getSCEV(U->getOperand(0));
5140 break;
5141
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00005142 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
5143 // lead to pointer expressions which cannot safely be expanded to GEPs,
5144 // because ScalarEvolution doesn't respect the GEP aliasing rules when
5145 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00005146
Dan Gohmanee750d12009-05-08 20:26:55 +00005147 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00005148 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00005149
Dan Gohman05e89732008-06-22 19:56:46 +00005150 case Instruction::PHI:
5151 return createNodeForPHI(cast<PHINode>(U));
5152
5153 case Instruction::Select:
Sanjoy Dasd0671342015-10-02 19:39:59 +00005154 // U can also be a select constant expr, which let fall through. Since
5155 // createNodeForSelect only works for a condition that is an `ICmpInst`, and
5156 // constant expressions cannot have instructions as operands, we'd have
5157 // returned getUnknown for a select constant expressions anyway.
5158 if (isa<Instruction>(U))
Sanjoy Das55015d22015-10-02 23:09:44 +00005159 return createNodeForSelectOrPHI(cast<Instruction>(U), U->getOperand(0),
5160 U->getOperand(1), U->getOperand(2));
Chris Lattnerd934c702004-04-02 20:23:17 +00005161 }
5162
Dan Gohmanc8e23622009-04-21 23:15:49 +00005163 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005164}
5165
5166
5167
5168//===----------------------------------------------------------------------===//
5169// Iteration Count Computation Code
5170//
5171
Chandler Carruth6666c272014-10-11 00:12:11 +00005172unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L) {
5173 if (BasicBlock *ExitingBB = L->getExitingBlock())
5174 return getSmallConstantTripCount(L, ExitingBB);
5175
5176 // No trip count information for multiple exits.
5177 return 0;
5178}
5179
Andrew Trick2b6860f2011-08-11 23:36:16 +00005180/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00005181/// normal unsigned value. Returns 0 if the trip count is unknown or not
5182/// constant. Will also return 0 if the maximum trip count is very large (>=
5183/// 2^32).
5184///
5185/// This "trip count" assumes that control exits via ExitingBlock. More
5186/// precisely, it is the number of times that control may reach ExitingBlock
5187/// before taking the branch. For loops with multiple exits, it may not be the
5188/// number times that the loop header executes because the loop may exit
5189/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005190unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
5191 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005192 assert(ExitingBlock && "Must pass a non-null exiting block!");
5193 assert(L->isLoopExiting(ExitingBlock) &&
5194 "Exiting block must actually branch out of the loop!");
Andrew Trick2b6860f2011-08-11 23:36:16 +00005195 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005196 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005197 if (!ExitCount)
5198 return 0;
5199
5200 ConstantInt *ExitConst = ExitCount->getValue();
5201
5202 // Guard against huge trip counts.
5203 if (ExitConst->getValue().getActiveBits() > 32)
5204 return 0;
5205
5206 // In case of integer overflow, this returns 0, which is correct.
5207 return ((unsigned)ExitConst->getZExtValue()) + 1;
5208}
5209
Chandler Carruth6666c272014-10-11 00:12:11 +00005210unsigned ScalarEvolution::getSmallConstantTripMultiple(Loop *L) {
5211 if (BasicBlock *ExitingBB = L->getExitingBlock())
5212 return getSmallConstantTripMultiple(L, ExitingBB);
5213
5214 // No trip multiple information for multiple exits.
5215 return 0;
5216}
5217
Andrew Trick2b6860f2011-08-11 23:36:16 +00005218/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
5219/// trip count of this loop as a normal unsigned value, if possible. This
5220/// means that the actual trip count is always a multiple of the returned
5221/// value (don't forget the trip count could very well be zero as well!).
5222///
5223/// Returns 1 if the trip count is unknown or not guaranteed to be the
5224/// multiple of a constant (which is also the case if the trip count is simply
5225/// constant, use getSmallConstantTripCount for that case), Will also return 1
5226/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00005227///
5228/// As explained in the comments for getSmallConstantTripCount, this assumes
5229/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005230unsigned
5231ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
5232 BasicBlock *ExitingBlock) {
Chandler Carruth6666c272014-10-11 00:12:11 +00005233 assert(ExitingBlock && "Must pass a non-null exiting block!");
5234 assert(L->isLoopExiting(ExitingBlock) &&
5235 "Exiting block must actually branch out of the loop!");
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005236 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00005237 if (ExitCount == getCouldNotCompute())
5238 return 1;
5239
5240 // Get the trip count from the BE count by adding 1.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005241 const SCEV *TCMul = getAddExpr(ExitCount, getOne(ExitCount->getType()));
Andrew Trick2b6860f2011-08-11 23:36:16 +00005242 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
5243 // to factor simple cases.
5244 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
5245 TCMul = Mul->getOperand(0);
5246
5247 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
5248 if (!MulC)
5249 return 1;
5250
5251 ConstantInt *Result = MulC->getValue();
5252
Hal Finkel30bd9342012-10-24 19:46:44 +00005253 // Guard against huge trip counts (this requires checking
5254 // for zero to handle the case where the trip count == -1 and the
5255 // addition wraps).
5256 if (!Result || Result->getValue().getActiveBits() > 32 ||
5257 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00005258 return 1;
5259
5260 return (unsigned)Result->getZExtValue();
5261}
5262
Andrew Trick3ca3f982011-07-26 17:19:55 +00005263// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00005264// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00005265// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00005266const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
5267 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005268}
5269
Silviu Baranga6f444df2016-04-08 14:29:09 +00005270const SCEV *
5271ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
5272 SCEVUnionPredicate &Preds) {
5273 return getPredicatedBackedgeTakenInfo(L).getExact(this, &Preds);
5274}
5275
Dan Gohman0bddac12009-02-24 18:55:53 +00005276/// getBackedgeTakenCount - If the specified loop has a predictable
5277/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
5278/// object. The backedge-taken count is the number of times the loop header
5279/// will be branched to from within the loop. This is one less than the
5280/// trip count of the loop, since it doesn't count the first iteration,
5281/// when the header is branched to from outside the loop.
5282///
5283/// Note that it is not valid to call this method on a loop without a
5284/// loop-invariant backedge-taken count (see
5285/// hasLoopInvariantBackedgeTakenCount).
5286///
Dan Gohmanaf752342009-07-07 17:06:11 +00005287const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005288 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005289}
5290
5291/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
5292/// return the least SCEV value that is known never to be less than the
5293/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00005294const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005295 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00005296}
5297
Dan Gohmandc191042009-07-08 19:23:34 +00005298/// PushLoopPHIs - Push PHI nodes in the header of the given loop
5299/// onto the given Worklist.
5300static void
5301PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
5302 BasicBlock *Header = L->getHeader();
5303
5304 // Push all Loop-header PHIs onto the Worklist stack.
5305 for (BasicBlock::iterator I = Header->begin();
5306 PHINode *PN = dyn_cast<PHINode>(I); ++I)
5307 Worklist.push_back(PN);
5308}
5309
Dan Gohman2b8da352009-04-30 20:47:05 +00005310const ScalarEvolution::BackedgeTakenInfo &
Silviu Baranga6f444df2016-04-08 14:29:09 +00005311ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
5312 auto &BTI = getBackedgeTakenInfo(L);
5313 if (BTI.hasFullInfo())
5314 return BTI;
5315
5316 auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
5317
5318 if (!Pair.second)
5319 return Pair.first->second;
5320
5321 BackedgeTakenInfo Result =
5322 computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
5323
5324 return PredicatedBackedgeTakenCounts.find(L)->second = Result;
5325}
5326
5327const ScalarEvolution::BackedgeTakenInfo &
Dan Gohman2b8da352009-04-30 20:47:05 +00005328ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005329 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00005330 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00005331 // update the value. The temporary CouldNotCompute value tells SCEV
5332 // code elsewhere that it shouldn't attempt to request a new
5333 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00005334 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00005335 BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
Chris Lattnera337f5e2011-01-09 02:16:18 +00005336 if (!Pair.second)
5337 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00005338
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005339 // computeBackedgeTakenCount may allocate memory for its result. Inserting it
Andrew Trick3ca3f982011-07-26 17:19:55 +00005340 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
5341 // must be cleared in this scope.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005342 BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005343
5344 if (Result.getExact(this) != getCouldNotCompute()) {
5345 assert(isLoopInvariant(Result.getExact(this), L) &&
5346 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00005347 "Computed backedge-taken count isn't loop invariant for loop!");
5348 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005349 }
5350 else if (Result.getMax(this) == getCouldNotCompute() &&
5351 isa<PHINode>(L->getHeader()->begin())) {
5352 // Only count loops that have phi nodes as not being computable.
5353 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00005354 }
Dan Gohman2b8da352009-04-30 20:47:05 +00005355
Chris Lattnera337f5e2011-01-09 02:16:18 +00005356 // Now that we know more about the trip count for this loop, forget any
5357 // existing SCEV values for PHI nodes in this loop since they are only
5358 // conservative estimates made without the benefit of trip count
5359 // information. This is similar to the code in forgetLoop, except that
5360 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005361 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00005362 SmallVector<Instruction *, 16> Worklist;
5363 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005364
Chris Lattnera337f5e2011-01-09 02:16:18 +00005365 SmallPtrSet<Instruction *, 8> Visited;
5366 while (!Worklist.empty()) {
5367 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005368 if (!Visited.insert(I).second)
5369 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005370
Chris Lattnera337f5e2011-01-09 02:16:18 +00005371 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005372 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00005373 if (It != ValueExprMap.end()) {
5374 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00005375
Chris Lattnera337f5e2011-01-09 02:16:18 +00005376 // SCEVUnknown for a PHI either means that it has an unrecognized
5377 // structure, or it's a PHI that's in the progress of being computed
5378 // by createNodeForPHI. In the former case, additional loop trip
5379 // count information isn't going to change anything. In the later
5380 // case, createNodeForPHI will perform the necessary updates on its
5381 // own when it gets to that point.
5382 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
5383 forgetMemoizedResults(Old);
5384 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005385 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005386 if (PHINode *PN = dyn_cast<PHINode>(I))
5387 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00005388 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00005389
5390 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00005391 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005392 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00005393
5394 // Re-lookup the insert position, since the call to
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005395 // computeBackedgeTakenCount above could result in a
Dan Gohman6acd95b2011-04-25 22:48:29 +00005396 // recusive call to getBackedgeTakenInfo (on a different
5397 // loop), which would invalidate the iterator computed
5398 // earlier.
5399 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00005400}
5401
Dan Gohman880c92a2009-10-31 15:04:55 +00005402/// forgetLoop - This method should be called by the client when it has
5403/// changed a loop in a way that may effect ScalarEvolution's ability to
5404/// compute a trip count, or if the loop is deleted.
5405void ScalarEvolution::forgetLoop(const Loop *L) {
5406 // Drop any stored trip count value.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005407 auto RemoveLoopFromBackedgeMap =
5408 [L](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
5409 auto BTCPos = Map.find(L);
5410 if (BTCPos != Map.end()) {
5411 BTCPos->second.clear();
5412 Map.erase(BTCPos);
5413 }
5414 };
5415
5416 RemoveLoopFromBackedgeMap(BackedgeTakenCounts);
5417 RemoveLoopFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohmanf1505722009-05-02 17:43:35 +00005418
Dan Gohman880c92a2009-10-31 15:04:55 +00005419 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00005420 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00005421 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005422
Dan Gohmandc191042009-07-08 19:23:34 +00005423 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00005424 while (!Worklist.empty()) {
5425 Instruction *I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005426 if (!Visited.insert(I).second)
5427 continue;
Dan Gohmandc191042009-07-08 19:23:34 +00005428
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005429 ValueExprMapType::iterator It =
5430 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005431 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005432 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005433 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00005434 if (PHINode *PN = dyn_cast<PHINode>(I))
5435 ConstantEvolutionLoopExitValue.erase(PN);
5436 }
5437
5438 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00005439 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00005440
5441 // Forget all contained loops too, to avoid dangling entries in the
5442 // ValuesAtScopes map.
5443 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
5444 forgetLoop(*I);
Dan Gohman43300342009-02-17 20:49:49 +00005445}
5446
Eric Christopheref6d5932010-07-29 01:25:38 +00005447/// forgetValue - This method should be called by the client when it has
5448/// changed a value in a way that may effect its value, or which may
5449/// disconnect it from a def-use chain linking it to a loop.
5450void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005451 Instruction *I = dyn_cast<Instruction>(V);
5452 if (!I) return;
5453
5454 // Drop information about expressions based on loop-header PHIs.
5455 SmallVector<Instruction *, 16> Worklist;
5456 Worklist.push_back(I);
5457
5458 SmallPtrSet<Instruction *, 8> Visited;
5459 while (!Worklist.empty()) {
5460 I = Worklist.pop_back_val();
David Blaikie70573dc2014-11-19 07:49:26 +00005461 if (!Visited.insert(I).second)
5462 continue;
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005463
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00005464 ValueExprMapType::iterator It =
5465 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005466 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00005467 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00005468 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00005469 if (PHINode *PN = dyn_cast<PHINode>(I))
5470 ConstantEvolutionLoopExitValue.erase(PN);
5471 }
5472
5473 PushDefUseChildren(I, Worklist);
5474 }
5475}
5476
Andrew Trick3ca3f982011-07-26 17:19:55 +00005477/// getExact - Get the exact loop backedge taken count considering all loop
Sanjoy Das135e5b92015-07-21 20:59:22 +00005478/// exits. A computable result can only be returned for loops with a single
5479/// exit. Returning the minimum taken count among all exits is incorrect
5480/// because one of the loop's exit limit's may have been skipped. HowFarToZero
5481/// assumes that the limit of each loop test is never skipped. This is a valid
5482/// assumption as long as the loop exits via that test. For precise results, it
5483/// is the caller's responsibility to specify the relevant loop exit using
Andrew Trick90c7a102011-11-16 00:52:40 +00005484/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00005485const SCEV *
Silviu Baranga6f444df2016-04-08 14:29:09 +00005486ScalarEvolution::BackedgeTakenInfo::getExact(
5487 ScalarEvolution *SE, SCEVUnionPredicate *Preds) const {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005488 // If any exits were not computable, the loop is not computable.
5489 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
5490
Andrew Trick90c7a102011-11-16 00:52:40 +00005491 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00005492 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00005493 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
5494
Craig Topper9f008862014-04-15 04:59:12 +00005495 const SCEV *BECount = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005496 for (auto &ENT : ExitNotTaken) {
5497 assert(ENT.ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005498
5499 if (!BECount)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005500 BECount = ENT.ExactNotTaken;
5501 else if (BECount != ENT.ExactNotTaken)
Andrew Trick90c7a102011-11-16 00:52:40 +00005502 return SE->getCouldNotCompute();
Silviu Baranga6f444df2016-04-08 14:29:09 +00005503 if (Preds && ENT.getPred())
5504 Preds->add(ENT.getPred());
5505
5506 assert((Preds || ENT.hasAlwaysTruePred()) &&
5507 "Predicate should be always true!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005508 }
Silviu Baranga6f444df2016-04-08 14:29:09 +00005509
Andrew Trickbbb226a2011-09-02 21:20:46 +00005510 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005511 return BECount;
5512}
5513
5514/// getExact - Get the exact not taken count for this loop exit.
5515const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00005516ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005517 ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005518 for (auto &ENT : ExitNotTaken)
5519 if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePred())
5520 return ENT.ExactNotTaken;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005521
Andrew Trick3ca3f982011-07-26 17:19:55 +00005522 return SE->getCouldNotCompute();
5523}
5524
5525/// getMax - Get the max backedge taken count for the loop.
5526const SCEV *
5527ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
Silviu Baranga6f444df2016-04-08 14:29:09 +00005528 for (auto &ENT : ExitNotTaken)
5529 if (!ENT.hasAlwaysTruePred())
5530 return SE->getCouldNotCompute();
5531
Andrew Trick3ca3f982011-07-26 17:19:55 +00005532 return Max ? Max : SE->getCouldNotCompute();
5533}
5534
Andrew Trick9093e152013-03-26 03:14:53 +00005535bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
5536 ScalarEvolution *SE) const {
5537 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
5538 return true;
5539
5540 if (!ExitNotTaken.ExitingBlock)
5541 return false;
5542
Silviu Baranga6f444df2016-04-08 14:29:09 +00005543 for (auto &ENT : ExitNotTaken)
5544 if (ENT.ExactNotTaken != SE->getCouldNotCompute() &&
5545 SE->hasOperand(ENT.ExactNotTaken, S))
Silviu Barangaa393baf2016-04-06 14:06:32 +00005546 return true;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005547
Andrew Trick9093e152013-03-26 03:14:53 +00005548 return false;
5549}
5550
Andrew Trick3ca3f982011-07-26 17:19:55 +00005551/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
5552/// computable exit into a persistent ExitNotTakenInfo array.
5553ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
Silviu Baranga6f444df2016-04-08 14:29:09 +00005554 SmallVectorImpl<EdgeInfo> &ExitCounts, bool Complete, const SCEV *MaxCount)
5555 : Max(MaxCount) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005556
5557 if (!Complete)
5558 ExitNotTaken.setIncomplete();
5559
5560 unsigned NumExits = ExitCounts.size();
5561 if (NumExits == 0) return;
5562
Silviu Baranga6f444df2016-04-08 14:29:09 +00005563 ExitNotTaken.ExitingBlock = ExitCounts[0].ExitBlock;
5564 ExitNotTaken.ExactNotTaken = ExitCounts[0].Taken;
5565
5566 // Determine the number of ExitNotTakenExtras structures that we need.
5567 unsigned ExtraInfoSize = 0;
5568 if (NumExits > 1)
5569 ExtraInfoSize = 1 + std::count_if(std::next(ExitCounts.begin()),
5570 ExitCounts.end(), [](EdgeInfo &Entry) {
5571 return !Entry.Pred.isAlwaysTrue();
5572 });
5573 else if (!ExitCounts[0].Pred.isAlwaysTrue())
5574 ExtraInfoSize = 1;
5575
5576 ExitNotTakenExtras *ENT = nullptr;
5577
5578 // Allocate the ExitNotTakenExtras structures and initialize the first
5579 // element (ExitNotTaken).
5580 if (ExtraInfoSize > 0) {
5581 ENT = new ExitNotTakenExtras[ExtraInfoSize];
5582 ExitNotTaken.ExtraInfo = &ENT[0];
5583 *ExitNotTaken.getPred() = std::move(ExitCounts[0].Pred);
5584 }
5585
5586 if (NumExits == 1)
5587 return;
5588
5589 auto &Exits = ExitNotTaken.ExtraInfo->Exits;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005590
5591 // Handle the rare case of multiple computable exits.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005592 for (unsigned i = 1, PredPos = 1; i < NumExits; ++i) {
5593 ExitNotTakenExtras *Ptr = nullptr;
5594 if (!ExitCounts[i].Pred.isAlwaysTrue()) {
5595 Ptr = &ENT[PredPos++];
5596 Ptr->Pred = std::move(ExitCounts[i].Pred);
5597 }
Andrew Trick3ca3f982011-07-26 17:19:55 +00005598
Silviu Baranga6f444df2016-04-08 14:29:09 +00005599 Exits.emplace_back(ExitCounts[i].ExitBlock, ExitCounts[i].Taken, Ptr);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005600 }
5601}
5602
5603/// clear - Invalidate this result and free the ExitNotTakenInfo array.
5604void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00005605 ExitNotTaken.ExitingBlock = nullptr;
5606 ExitNotTaken.ExactNotTaken = nullptr;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005607 delete[] ExitNotTaken.ExtraInfo;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005608}
5609
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005610/// computeBackedgeTakenCount - Compute the number of times the backedge
Dan Gohman0bddac12009-02-24 18:55:53 +00005611/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00005612ScalarEvolution::BackedgeTakenInfo
Silviu Baranga6f444df2016-04-08 14:29:09 +00005613ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
5614 bool AllowPredicates) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00005615 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00005616 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00005617
Silviu Baranga6f444df2016-04-08 14:29:09 +00005618 SmallVector<EdgeInfo, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00005619 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00005620 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00005621 const SCEV *MustExitMaxBECount = nullptr;
5622 const SCEV *MayExitMaxBECount = nullptr;
5623
5624 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
5625 // and compute maxBECount.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005626 // Do a union of all the predicates here.
Dan Gohman96212b62009-06-22 00:31:57 +00005627 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005628 BasicBlock *ExitBB = ExitingBlocks[i];
Silviu Baranga6f444df2016-04-08 14:29:09 +00005629 ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
5630
5631 assert((AllowPredicates || EL.Pred.isAlwaysTrue()) &&
5632 "Predicated exit limit when predicates are not allowed!");
Andrew Trick839e30b2014-05-23 19:47:13 +00005633
5634 // 1. For each exit that can be computed, add an entry to ExitCounts.
5635 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005636 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00005637 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00005638 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005639 CouldComputeBECount = false;
5640 else
Silviu Baranga6f444df2016-04-08 14:29:09 +00005641 ExitCounts.emplace_back(EdgeInfo(ExitBB, EL.Exact, EL.Pred));
Andrew Trick3ca3f982011-07-26 17:19:55 +00005642
Andrew Trick839e30b2014-05-23 19:47:13 +00005643 // 2. Derive the loop's MaxBECount from each exit's max number of
5644 // non-exiting iterations. Partition the loop exits into two kinds:
5645 // LoopMustExits and LoopMayExits.
5646 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005647 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
5648 // is a LoopMayExit. If any computable LoopMustExit is found, then
5649 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
5650 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
5651 // considered greater than any computable EL.Max.
5652 if (EL.Max != getCouldNotCompute() && Latch &&
Chandler Carruth2f1fd162015-08-17 02:08:17 +00005653 DT.dominates(ExitBB, Latch)) {
Andrew Trick839e30b2014-05-23 19:47:13 +00005654 if (!MustExitMaxBECount)
5655 MustExitMaxBECount = EL.Max;
5656 else {
5657 MustExitMaxBECount =
5658 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00005659 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005660 } else if (MayExitMaxBECount != getCouldNotCompute()) {
5661 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
5662 MayExitMaxBECount = EL.Max;
5663 else {
5664 MayExitMaxBECount =
5665 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
5666 }
Andrew Trick90c7a102011-11-16 00:52:40 +00005667 }
Dan Gohman96212b62009-06-22 00:31:57 +00005668 }
Andrew Trick839e30b2014-05-23 19:47:13 +00005669 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
5670 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00005671 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00005672}
5673
Andrew Trick3ca3f982011-07-26 17:19:55 +00005674ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00005675ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
5676 bool AllowPredicates) {
Dan Gohman96212b62009-06-22 00:31:57 +00005677
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005678 // Okay, we've chosen an exiting block. See what condition causes us to exit
5679 // at this block and remember the exit block and whether all other targets
Benjamin Kramer5a188542014-02-11 15:44:32 +00005680 // lead to the loop header.
5681 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00005682 BasicBlock *Exit = nullptr;
Sanjoy Das0ff07872016-01-19 20:53:46 +00005683 for (auto *SBB : successors(ExitingBlock))
5684 if (!L->contains(SBB)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005685 if (Exit) // Multiple exit successors.
5686 return getCouldNotCompute();
Sanjoy Das0ff07872016-01-19 20:53:46 +00005687 Exit = SBB;
5688 } else if (SBB != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005689 MustExecuteLoopHeader = false;
5690 }
Dan Gohmance973df2009-06-24 04:48:43 +00005691
Chris Lattner18954852007-01-07 02:24:26 +00005692 // At this point, we know we have a conditional branch that determines whether
5693 // the loop is exited. However, we don't know if the branch is executed each
5694 // time through the loop. If not, then the execution count of the branch will
5695 // not be equal to the trip count of the loop.
5696 //
5697 // Currently we check for this by checking to see if the Exit branch goes to
5698 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00005699 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00005700 // loop header. This is common for un-rotated loops.
5701 //
5702 // If both of those tests fail, walk up the unique predecessor chain to the
5703 // header, stopping if there is an edge that doesn't exit the loop. If the
5704 // header is reached, the execution count of the branch will be equal to the
5705 // trip count of the loop.
5706 //
5707 // More extensive analysis could be done to handle more cases here.
5708 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00005709 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005710 // The simple checks failed, try climbing the unique predecessor chain
5711 // up to the header.
5712 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00005713 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00005714 BasicBlock *Pred = BB->getUniquePredecessor();
5715 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005716 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005717 TerminatorInst *PredTerm = Pred->getTerminator();
Pete Cooperebcd7482015-08-06 20:22:46 +00005718 for (const BasicBlock *PredSucc : PredTerm->successors()) {
Dan Gohman96212b62009-06-22 00:31:57 +00005719 if (PredSucc == BB)
5720 continue;
5721 // If the predecessor has a successor that isn't BB and isn't
5722 // outside the loop, assume the worst.
5723 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005724 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005725 }
5726 if (Pred == L->getHeader()) {
5727 Ok = true;
5728 break;
5729 }
5730 BB = Pred;
5731 }
5732 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005733 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005734 }
5735
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005736 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005737 TerminatorInst *Term = ExitingBlock->getTerminator();
5738 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
5739 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
5740 // Proceed to the next level to examine the exit condition expression.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005741 return computeExitLimitFromCond(
5742 L, BI->getCondition(), BI->getSuccessor(0), BI->getSuccessor(1),
5743 /*ControlsExit=*/IsOnlyExit, AllowPredicates);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005744 }
5745
5746 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005747 return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005748 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005749
5750 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00005751}
5752
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005753/// computeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00005754/// backedge of the specified loop will execute if its exit condition
5755/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00005756///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005757/// @param ControlsExit is true if ExitCond directly controls the exit
5758/// branch. In this case, we can assume that the loop exits only if the
5759/// condition is true and can infer that failing to meet the condition prior to
5760/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005761ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005762ScalarEvolution::computeExitLimitFromCond(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005763 Value *ExitCond,
5764 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005765 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005766 bool ControlsExit,
5767 bool AllowPredicates) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00005768 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00005769 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
5770 if (BO->getOpcode() == Instruction::And) {
5771 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00005772 bool EitherMayExit = L->contains(TBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005773 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005774 ControlsExit && !EitherMayExit,
5775 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005776 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005777 ControlsExit && !EitherMayExit,
5778 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005779 const SCEV *BECount = getCouldNotCompute();
5780 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005781 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005782 // Both conditions must be true for the loop to continue executing.
5783 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005784 if (EL0.Exact == getCouldNotCompute() ||
5785 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005786 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005787 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005788 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5789 if (EL0.Max == getCouldNotCompute())
5790 MaxBECount = EL1.Max;
5791 else if (EL1.Max == getCouldNotCompute())
5792 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005793 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005794 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005795 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005796 // Both conditions must be true at the same time for the loop to exit.
5797 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005798 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005799 if (EL0.Max == EL1.Max)
5800 MaxBECount = EL0.Max;
5801 if (EL0.Exact == EL1.Exact)
5802 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005803 }
5804
Silviu Baranga6f444df2016-04-08 14:29:09 +00005805 SCEVUnionPredicate NP;
5806 NP.add(&EL0.Pred);
5807 NP.add(&EL1.Pred);
Sanjoy Das29a4b5d2016-01-19 20:53:51 +00005808 // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
5809 // to be more aggressive when computing BECount than when computing
5810 // MaxBECount. In these cases it is possible for EL0.Exact and EL1.Exact
5811 // to match, but for EL0.Max and EL1.Max to not.
5812 if (isa<SCEVCouldNotCompute>(MaxBECount) &&
5813 !isa<SCEVCouldNotCompute>(BECount))
5814 MaxBECount = BECount;
5815
Silviu Baranga6f444df2016-04-08 14:29:09 +00005816 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005817 }
5818 if (BO->getOpcode() == Instruction::Or) {
5819 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00005820 bool EitherMayExit = L->contains(FBB);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005821 ExitLimit EL0 = computeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005822 ControlsExit && !EitherMayExit,
5823 AllowPredicates);
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005824 ExitLimit EL1 = computeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005825 ControlsExit && !EitherMayExit,
5826 AllowPredicates);
Dan Gohmanaf752342009-07-07 17:06:11 +00005827 const SCEV *BECount = getCouldNotCompute();
5828 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00005829 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00005830 // Both conditions must be false for the loop to continue executing.
5831 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005832 if (EL0.Exact == getCouldNotCompute() ||
5833 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005834 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00005835 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005836 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
5837 if (EL0.Max == getCouldNotCompute())
5838 MaxBECount = EL1.Max;
5839 else if (EL1.Max == getCouldNotCompute())
5840 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00005841 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00005842 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00005843 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00005844 // Both conditions must be false at the same time for the loop to exit.
5845 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00005846 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00005847 if (EL0.Max == EL1.Max)
5848 MaxBECount = EL0.Max;
5849 if (EL0.Exact == EL1.Exact)
5850 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00005851 }
5852
Silviu Baranga6f444df2016-04-08 14:29:09 +00005853 SCEVUnionPredicate NP;
5854 NP.add(&EL0.Pred);
5855 NP.add(&EL1.Pred);
5856 return ExitLimit(BECount, MaxBECount, NP);
Dan Gohman96212b62009-06-22 00:31:57 +00005857 }
5858 }
5859
5860 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00005861 // Proceed to the next level to examine the icmp.
Silviu Baranga6f444df2016-04-08 14:29:09 +00005862 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
5863 ExitLimit EL =
5864 computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
5865 if (EL.hasFullInfo() || !AllowPredicates)
5866 return EL;
5867
5868 // Try again, but use SCEV predicates this time.
5869 return computeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit,
5870 /*AllowPredicates=*/true);
5871 }
Reid Spencer266e42b2006-12-23 06:05:41 +00005872
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005873 // Check for a constant condition. These are normally stripped out by
5874 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
5875 // preserve the CFG and is temporarily leaving constant conditions
5876 // in place.
5877 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
5878 if (L->contains(FBB) == !CI->getZExtValue())
5879 // The backedge is always taken.
5880 return getCouldNotCompute();
5881 else
5882 // The backedge is never taken.
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00005883 return getZero(CI->getType());
Dan Gohman6b1e2a82010-02-19 18:12:07 +00005884 }
5885
Eli Friedmanebf98b02009-05-09 12:32:42 +00005886 // If it's not an integer or pointer comparison then compute it the hard way.
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005887 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00005888}
5889
Andrew Trick3ca3f982011-07-26 17:19:55 +00005890ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005891ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
Andrew Trick3ca3f982011-07-26 17:19:55 +00005892 ICmpInst *ExitCond,
5893 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00005894 BasicBlock *FBB,
Silviu Baranga6f444df2016-04-08 14:29:09 +00005895 bool ControlsExit,
5896 bool AllowPredicates) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005897
Reid Spencer266e42b2006-12-23 06:05:41 +00005898 // If the condition was exit on true, convert the condition to exit on false
5899 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00005900 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00005901 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005902 else
Reid Spencer266e42b2006-12-23 06:05:41 +00005903 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005904
5905 // Handle common loops like: for (X = "string"; *X; ++X)
5906 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
5907 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00005908 ExitLimit ItCnt =
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005909 computeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005910 if (ItCnt.hasAnyInfo())
5911 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005912 }
5913
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00005914 ExitLimit ShiftEL = computeShiftCompareExitLimit(
5915 ExitCond->getOperand(0), ExitCond->getOperand(1), L, Cond);
5916 if (ShiftEL.hasAnyInfo())
5917 return ShiftEL;
5918
Dan Gohmanaf752342009-07-07 17:06:11 +00005919 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5920 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005921
5922 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005923 LHS = getSCEVAtScope(LHS, L);
5924 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005925
Dan Gohmance973df2009-06-24 04:48:43 +00005926 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005927 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005928 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005929 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005930 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005931 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005932 }
5933
Dan Gohman81585c12010-05-03 16:35:17 +00005934 // Simplify the operands before analyzing them.
5935 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5936
Chris Lattnerd934c702004-04-02 20:23:17 +00005937 // If we have a comparison of a chrec against a constant, try to use value
5938 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005939 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5940 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005941 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005942 // Form the constant range.
5943 ConstantRange CompRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00005944 ICmpInst::makeConstantRange(Cond, RHSC->getAPInt()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005945
Dan Gohmanaf752342009-07-07 17:06:11 +00005946 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005947 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005948 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005949
Chris Lattnerd934c702004-04-02 20:23:17 +00005950 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005951 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005952 // Convert to: while (X-Y != 0)
Silviu Baranga6f444df2016-04-08 14:29:09 +00005953 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
5954 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005955 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005956 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005957 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005958 case ICmpInst::ICMP_EQ: { // while (X == Y)
5959 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005960 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5961 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005962 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005963 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005964 case ICmpInst::ICMP_SLT:
5965 case ICmpInst::ICMP_ULT: { // while (X < Y)
5966 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005967 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
5968 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005969 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005970 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005971 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005972 case ICmpInst::ICMP_SGT:
5973 case ICmpInst::ICMP_UGT: { // while (X > Y)
5974 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Silviu Baranga6f444df2016-04-08 14:29:09 +00005975 ExitLimit EL =
5976 HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
5977 AllowPredicates);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005978 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005979 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005980 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005981 default:
Chris Lattner0defaa12004-04-03 00:43:03 +00005982 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005983 }
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005984 return computeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00005985}
5986
Benjamin Kramer5a188542014-02-11 15:44:32 +00005987ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00005988ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
Benjamin Kramer5a188542014-02-11 15:44:32 +00005989 SwitchInst *Switch,
5990 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005991 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005992 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5993
5994 // Give up if the exit is the default dest of a switch.
5995 if (Switch->getDefaultDest() == ExitingBlock)
5996 return getCouldNotCompute();
5997
5998 assert(L->contains(Switch->getDefaultDest()) &&
5999 "Default case must not exit the loop!");
6000 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
6001 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
6002
6003 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006004 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00006005 if (EL.hasAnyInfo())
6006 return EL;
6007
6008 return getCouldNotCompute();
6009}
6010
Chris Lattnerec901cc2004-10-12 01:49:27 +00006011static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00006012EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
6013 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006014 const SCEV *InVal = SE.getConstant(C);
6015 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006016 assert(isa<SCEVConstant>(Val) &&
6017 "Evaluation of SCEV at constant didn't fold correctly?");
6018 return cast<SCEVConstant>(Val)->getValue();
6019}
6020
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006021/// computeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00006022/// 'icmp op load X, cst', try to see if we can compute the backedge
6023/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006024ScalarEvolution::ExitLimit
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006025ScalarEvolution::computeLoadConstantCompareExitLimit(
Andrew Trick3ca3f982011-07-26 17:19:55 +00006026 LoadInst *LI,
6027 Constant *RHS,
6028 const Loop *L,
6029 ICmpInst::Predicate predicate) {
6030
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006031 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006032
6033 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00006034 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006035 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006036 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006037
6038 // Make sure that it is really a constant global we are gepping, with an
6039 // initializer, and make sure the first IDX is really 0.
6040 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00006041 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006042 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
6043 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006044 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006045
6046 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00006047 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00006048 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00006049 unsigned VarIdxNum = 0;
6050 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
6051 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
6052 Indexes.push_back(CI);
6053 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006054 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00006055 VarIdx = GEP->getOperand(i);
6056 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00006057 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006058 }
6059
Andrew Trick7004e4b2012-03-26 22:33:59 +00006060 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
6061 if (!VarIdx)
6062 return getCouldNotCompute();
6063
Chris Lattnerec901cc2004-10-12 01:49:27 +00006064 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
6065 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006066 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00006067 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006068
6069 // We can only recognize very limited forms of loop index expressions, in
6070 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00006071 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00006072 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00006073 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
6074 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006075 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006076
6077 unsigned MaxSteps = MaxBruteForceIterations;
6078 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00006079 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00006080 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00006081 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00006082
6083 // Form the GEP offset.
6084 Indexes[VarIdxNum] = Val;
6085
Chris Lattnere166a852012-01-24 05:49:24 +00006086 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
6087 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00006088 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006089
6090 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00006091 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00006092 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00006093 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00006094 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00006095 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00006096 }
6097 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006098 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00006099}
6100
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006101ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
6102 Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
6103 ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
6104 if (!RHS)
6105 return getCouldNotCompute();
6106
6107 const BasicBlock *Latch = L->getLoopLatch();
6108 if (!Latch)
6109 return getCouldNotCompute();
6110
6111 const BasicBlock *Predecessor = L->getLoopPredecessor();
6112 if (!Predecessor)
6113 return getCouldNotCompute();
6114
6115 // Return true if V is of the form "LHS `shift_op` <positive constant>".
6116 // Return LHS in OutLHS and shift_opt in OutOpCode.
6117 auto MatchPositiveShift =
6118 [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
6119
6120 using namespace PatternMatch;
6121
6122 ConstantInt *ShiftAmt;
6123 if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6124 OutOpCode = Instruction::LShr;
6125 else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6126 OutOpCode = Instruction::AShr;
6127 else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
6128 OutOpCode = Instruction::Shl;
6129 else
6130 return false;
6131
6132 return ShiftAmt->getValue().isStrictlyPositive();
6133 };
6134
6135 // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
6136 //
6137 // loop:
6138 // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
6139 // %iv.shifted = lshr i32 %iv, <positive constant>
6140 //
6141 // Return true on a succesful match. Return the corresponding PHI node (%iv
6142 // above) in PNOut and the opcode of the shift operation in OpCodeOut.
6143 auto MatchShiftRecurrence =
6144 [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
6145 Optional<Instruction::BinaryOps> PostShiftOpCode;
6146
6147 {
6148 Instruction::BinaryOps OpC;
6149 Value *V;
6150
6151 // If we encounter a shift instruction, "peel off" the shift operation,
6152 // and remember that we did so. Later when we inspect %iv's backedge
6153 // value, we will make sure that the backedge value uses the same
6154 // operation.
6155 //
6156 // Note: the peeled shift operation does not have to be the same
6157 // instruction as the one feeding into the PHI's backedge value. We only
6158 // really care about it being the same *kind* of shift instruction --
6159 // that's all that is required for our later inferences to hold.
6160 if (MatchPositiveShift(LHS, V, OpC)) {
6161 PostShiftOpCode = OpC;
6162 LHS = V;
6163 }
6164 }
6165
6166 PNOut = dyn_cast<PHINode>(LHS);
6167 if (!PNOut || PNOut->getParent() != L->getHeader())
6168 return false;
6169
6170 Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
6171 Value *OpLHS;
6172
6173 return
6174 // The backedge value for the PHI node must be a shift by a positive
6175 // amount
6176 MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
6177
6178 // of the PHI node itself
6179 OpLHS == PNOut &&
6180
6181 // and the kind of shift should be match the kind of shift we peeled
6182 // off, if any.
6183 (!PostShiftOpCode.hasValue() || *PostShiftOpCode == OpCodeOut);
6184 };
6185
6186 PHINode *PN;
6187 Instruction::BinaryOps OpCode;
6188 if (!MatchShiftRecurrence(LHS, PN, OpCode))
6189 return getCouldNotCompute();
6190
6191 const DataLayout &DL = getDataLayout();
6192
6193 // The key rationale for this optimization is that for some kinds of shift
6194 // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
6195 // within a finite number of iterations. If the condition guarding the
6196 // backedge (in the sense that the backedge is taken if the condition is true)
6197 // is false for the value the shift recurrence stabilizes to, then we know
6198 // that the backedge is taken only a finite number of times.
6199
6200 ConstantInt *StableValue = nullptr;
6201 switch (OpCode) {
6202 default:
6203 llvm_unreachable("Impossible case!");
6204
6205 case Instruction::AShr: {
6206 // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
6207 // bitwidth(K) iterations.
6208 Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
6209 bool KnownZero, KnownOne;
6210 ComputeSignBit(FirstValue, KnownZero, KnownOne, DL, 0, nullptr,
6211 Predecessor->getTerminator(), &DT);
6212 auto *Ty = cast<IntegerType>(RHS->getType());
6213 if (KnownZero)
6214 StableValue = ConstantInt::get(Ty, 0);
6215 else if (KnownOne)
6216 StableValue = ConstantInt::get(Ty, -1, true);
6217 else
6218 return getCouldNotCompute();
6219
6220 break;
6221 }
6222 case Instruction::LShr:
6223 case Instruction::Shl:
6224 // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
6225 // stabilize to 0 in at most bitwidth(K) iterations.
6226 StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
6227 break;
6228 }
6229
6230 auto *Result =
6231 ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
6232 assert(Result->getType()->isIntegerTy(1) &&
6233 "Otherwise cannot be an operand to a branch instruction");
6234
6235 if (Result->isZeroValue()) {
6236 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6237 const SCEV *UpperBound =
6238 getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
Silviu Baranga6f444df2016-04-08 14:29:09 +00006239 SCEVUnionPredicate P;
6240 return ExitLimit(getCouldNotCompute(), UpperBound, P);
Sanjoy Dasc88f5d32015-10-28 21:27:14 +00006241 }
6242
6243 return getCouldNotCompute();
6244}
Chris Lattnerec901cc2004-10-12 01:49:27 +00006245
Chris Lattnerdd730472004-04-17 22:58:41 +00006246/// CanConstantFold - Return true if we can constant fold an instruction of the
6247/// specified type, assuming that all operands were constants.
6248static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00006249 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00006250 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
6251 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00006252 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00006253
Chris Lattnerdd730472004-04-17 22:58:41 +00006254 if (const CallInst *CI = dyn_cast<CallInst>(I))
6255 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00006256 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00006257 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00006258}
6259
Andrew Trick3a86ba72011-10-05 03:25:31 +00006260/// Determine whether this instruction can constant evolve within this loop
6261/// assuming its operands can all constant evolve.
6262static bool canConstantEvolve(Instruction *I, const Loop *L) {
6263 // An instruction outside of the loop can't be derived from a loop PHI.
6264 if (!L->contains(I)) return false;
6265
6266 if (isa<PHINode>(I)) {
David Blaikie19ef0d32015-03-24 16:33:19 +00006267 // We don't currently keep track of the control flow needed to evaluate
6268 // PHIs, so we cannot handle PHIs inside of loops.
6269 return L->getHeader() == I->getParent();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006270 }
6271
6272 // If we won't be able to constant fold this expression even if the operands
6273 // are constants, bail early.
6274 return CanConstantFold(I);
6275}
6276
6277/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
6278/// recursing through each instruction operand until reaching a loop header phi.
6279static PHINode *
6280getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00006281 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00006282
6283 // Otherwise, we can evaluate this instruction if all of its operands are
6284 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00006285 PHINode *PHI = nullptr;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006286 for (Value *Op : UseInst->operands()) {
6287 if (isa<Constant>(Op)) continue;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006288
Sanjoy Dasd87e4352015-12-08 22:53:36 +00006289 Instruction *OpInst = dyn_cast<Instruction>(Op);
Craig Topper9f008862014-04-15 04:59:12 +00006290 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006291
6292 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00006293 if (!P)
6294 // If this operand is already visited, reuse the prior result.
6295 // We may have P != PHI if this is the deepest point at which the
6296 // inconsistent paths meet.
6297 P = PHIMap.lookup(OpInst);
6298 if (!P) {
6299 // Recurse and memoize the results, whether a phi is found or not.
6300 // This recursive call invalidates pointers into PHIMap.
6301 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
6302 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00006303 }
Craig Topper9f008862014-04-15 04:59:12 +00006304 if (!P)
6305 return nullptr; // Not evolving from PHI
6306 if (PHI && PHI != P)
6307 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00006308 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006309 }
6310 // This is a expression evolving from a constant PHI!
6311 return PHI;
6312}
6313
Chris Lattnerdd730472004-04-17 22:58:41 +00006314/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
6315/// in the loop that V is derived from. We allow arbitrary operations along the
6316/// way, but the operands of an operation must either be constants or a value
6317/// derived from a constant PHI. If this expression does not fit with these
6318/// constraints, return null.
6319static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006320 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006321 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006322
Sanjoy Dasd295f2c2015-10-18 00:29:27 +00006323 if (PHINode *PN = dyn_cast<PHINode>(I))
Andrew Trick3a86ba72011-10-05 03:25:31 +00006324 return PN;
Chris Lattnerdd730472004-04-17 22:58:41 +00006325
Andrew Trick3a86ba72011-10-05 03:25:31 +00006326 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00006327 DenseMap<Instruction *, PHINode *> PHIMap;
6328 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00006329}
6330
6331/// EvaluateExpression - Given an expression that passes the
6332/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
6333/// in the loop has the value PHIVal. If we can't fold this expression for some
6334/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006335static Constant *EvaluateExpression(Value *V, const Loop *L,
6336 DenseMap<Instruction *, Constant *> &Vals,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006337 const DataLayout &DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00006338 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006339 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00006340 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006341 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00006342 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00006343
Andrew Trick3a86ba72011-10-05 03:25:31 +00006344 if (Constant *C = Vals.lookup(I)) return C;
6345
Nick Lewyckya6674c72011-10-22 19:58:20 +00006346 // An instruction inside the loop depends on a value outside the loop that we
6347 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00006348 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006349
6350 // An unmapped PHI can be due to a branch or another loop inside this loop,
6351 // or due to this not being the initial iteration through a loop where we
6352 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00006353 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006354
Dan Gohmanf820bd32010-06-22 13:15:46 +00006355 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00006356
6357 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00006358 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
6359 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00006360 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006361 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006362 continue;
6363 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006364 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00006365 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00006366 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00006367 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00006368 }
6369
Nick Lewyckya6674c72011-10-22 19:58:20 +00006370 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00006371 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00006372 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006373 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6374 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006375 return ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006376 }
Manuel Jacobe9024592016-01-21 06:33:22 +00006377 return ConstantFoldInstOperands(I, Operands, DL, TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00006378}
6379
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006380
6381// If every incoming value to PN except the one for BB is a specific Constant,
6382// return that, else return nullptr.
6383static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
6384 Constant *IncomingVal = nullptr;
6385
6386 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6387 if (PN->getIncomingBlock(i) == BB)
6388 continue;
6389
6390 auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
6391 if (!CurrentVal)
6392 return nullptr;
6393
6394 if (IncomingVal != CurrentVal) {
6395 if (IncomingVal)
6396 return nullptr;
6397 IncomingVal = CurrentVal;
6398 }
6399 }
6400
6401 return IncomingVal;
6402}
6403
Chris Lattnerdd730472004-04-17 22:58:41 +00006404/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
6405/// in the header of its containing loop, we know the loop executes a
6406/// constant number of times, and the PHI node is just a recurrence
6407/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00006408Constant *
6409ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00006410 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00006411 const Loop *L) {
Sanjoy Das4493b402015-10-07 17:38:25 +00006412 auto I = ConstantEvolutionLoopExitValue.find(PN);
Chris Lattnerdd730472004-04-17 22:58:41 +00006413 if (I != ConstantEvolutionLoopExitValue.end())
6414 return I->second;
6415
Dan Gohman4ce1fb12010-04-08 23:03:40 +00006416 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00006417 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00006418
6419 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
6420
Andrew Trick3a86ba72011-10-05 03:25:31 +00006421 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006422 BasicBlock *Header = L->getHeader();
6423 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00006424
Sanjoy Dasdd709962015-10-08 18:28:36 +00006425 BasicBlock *Latch = L->getLoopLatch();
6426 if (!Latch)
6427 return nullptr;
6428
Sanjoy Das4493b402015-10-07 17:38:25 +00006429 for (auto &I : *Header) {
6430 PHINode *PHI = dyn_cast<PHINode>(&I);
6431 if (!PHI) break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006432 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006433 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006434 CurrentIterVals[PHI] = StartCST;
6435 }
6436 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00006437 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00006438
Sanjoy Dasdd709962015-10-08 18:28:36 +00006439 Value *BEValue = PN->getIncomingValueForBlock(Latch);
Chris Lattnerdd730472004-04-17 22:58:41 +00006440
6441 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00006442 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00006443 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00006444
Dan Gohman0bddac12009-02-24 18:55:53 +00006445 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00006446 unsigned IterationNum = 0;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006447 const DataLayout &DL = getDataLayout();
Andrew Trick3a86ba72011-10-05 03:25:31 +00006448 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006449 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00006450 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00006451
Nick Lewyckya6674c72011-10-22 19:58:20 +00006452 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00006453 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006454 DenseMap<Instruction *, Constant *> NextIterVals;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006455 Constant *NextPHI =
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006456 EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Craig Topper9f008862014-04-15 04:59:12 +00006457 if (!NextPHI)
6458 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00006459 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006460
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006461 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
6462
Nick Lewyckya6674c72011-10-22 19:58:20 +00006463 // Also evaluate the other PHI nodes. However, we don't get to stop if we
6464 // cease to be able to evaluate one of them or if they stop evolving,
6465 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006466 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006467 for (const auto &I : CurrentIterVals) {
6468 PHINode *PHI = dyn_cast<PHINode>(I.first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00006469 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Sanjoy Das4493b402015-10-07 17:38:25 +00006470 PHIsToCompute.emplace_back(PHI, I.second);
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006471 }
6472 // We use two distinct loops because EvaluateExpression may invalidate any
6473 // iterators into CurrentIterVals.
Sanjoy Das4493b402015-10-07 17:38:25 +00006474 for (const auto &I : PHIsToCompute) {
6475 PHINode *PHI = I.first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006476 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006477 if (!NextPHI) { // Not already computed.
Sanjoy Dasdd709962015-10-08 18:28:36 +00006478 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006479 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006480 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006481 if (NextPHI != I.second)
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006482 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006483 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006484
6485 // If all entries in CurrentIterVals == NextIterVals then we can stop
6486 // iterating, the loop can't continue to change.
6487 if (StoppedEvolving)
6488 return RetVal = CurrentIterVals[PN];
6489
Andrew Trick3a86ba72011-10-05 03:25:31 +00006490 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00006491 }
6492}
6493
Sanjoy Das413dbbb2015-10-08 18:46:59 +00006494const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
Nick Lewyckya6674c72011-10-22 19:58:20 +00006495 Value *Cond,
6496 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006497 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00006498 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006499
Dan Gohman866971e2010-06-19 14:17:24 +00006500 // If the loop is canonicalized, the PHI will have exactly two entries.
6501 // That's the only form we support here.
6502 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
6503
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006504 DenseMap<Instruction *, Constant *> CurrentIterVals;
6505 BasicBlock *Header = L->getHeader();
6506 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
6507
Sanjoy Dasdd709962015-10-08 18:28:36 +00006508 BasicBlock *Latch = L->getLoopLatch();
6509 assert(Latch && "Should follow from NumIncomingValues == 2!");
6510
Sanjoy Das4493b402015-10-07 17:38:25 +00006511 for (auto &I : *Header) {
6512 PHINode *PHI = dyn_cast<PHINode>(&I);
6513 if (!PHI)
6514 break;
Sanjoy Das52bfa0f2015-11-02 02:06:01 +00006515 auto *StartCST = getOtherIncomingValue(PHI, Latch);
Craig Topper9f008862014-04-15 04:59:12 +00006516 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006517 CurrentIterVals[PHI] = StartCST;
6518 }
6519 if (!CurrentIterVals.count(PN))
6520 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00006521
6522 // Okay, we find a PHI node that defines the trip count of this loop. Execute
6523 // the loop symbolically to determine when the condition gets a value of
6524 // "ExitWhen".
Andrew Trick90c7a102011-11-16 00:52:40 +00006525 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006526 const DataLayout &DL = getDataLayout();
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006527 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Sanjoy Das4493b402015-10-07 17:38:25 +00006528 auto *CondVal = dyn_cast_or_null<ConstantInt>(
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006529 EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00006530
Zhou Sheng75b871f2007-01-11 12:24:14 +00006531 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006532 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00006533
Reid Spencer983e3b32007-03-01 07:25:48 +00006534 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00006535 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00006536 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006537 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006538
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006539 // Update all the PHI nodes for the next iteration.
6540 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006541
6542 // Create a list of which PHIs we need to compute. We want to do this before
6543 // calling EvaluateExpression on them because that may invalidate iterators
6544 // into CurrentIterVals.
6545 SmallVector<PHINode *, 8> PHIsToCompute;
Sanjoy Das4493b402015-10-07 17:38:25 +00006546 for (const auto &I : CurrentIterVals) {
6547 PHINode *PHI = dyn_cast<PHINode>(I.first);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006548 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00006549 PHIsToCompute.push_back(PHI);
6550 }
Sanjoy Das4493b402015-10-07 17:38:25 +00006551 for (PHINode *PHI : PHIsToCompute) {
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006552 Constant *&NextPHI = NextIterVals[PHI];
6553 if (NextPHI) continue; // Already computed!
6554
Sanjoy Dasdd709962015-10-08 18:28:36 +00006555 Value *BEValue = PHI->getIncomingValueForBlock(Latch);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006556 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00006557 }
6558 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00006559 }
6560
6561 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006562 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006563}
6564
Dan Gohman237d9e52009-09-03 15:00:26 +00006565/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006566/// at the specified scope in the program. The L value specifies a loop
6567/// nest to evaluate the expression at, where null is the top-level or a
6568/// specified loop is immediately inside of the loop.
6569///
6570/// This method can be used to compute the exit value for a variable defined
6571/// in a loop by querying what the value will hold in the parent loop.
6572///
Dan Gohman8ca08852009-05-24 23:25:42 +00006573/// In the case that a relevant loop exit value cannot be computed, the
6574/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006575const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Sanjoy Das01947432015-11-22 21:20:13 +00006576 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
6577 ValuesAtScopes[V];
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006578 // Check to see if we've folded this expression at this loop before.
Sanjoy Das01947432015-11-22 21:20:13 +00006579 for (auto &LS : Values)
6580 if (LS.first == L)
6581 return LS.second ? LS.second : V;
6582
6583 Values.emplace_back(L, nullptr);
6584
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006585 // Otherwise compute it.
6586 const SCEV *C = computeSCEVAtScope(V, L);
Sanjoy Das01947432015-11-22 21:20:13 +00006587 for (auto &LS : reverse(ValuesAtScopes[V]))
6588 if (LS.first == L) {
6589 LS.second = C;
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00006590 break;
6591 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006592 return C;
6593}
6594
Nick Lewyckya6674c72011-10-22 19:58:20 +00006595/// This builds up a Constant using the ConstantExpr interface. That way, we
6596/// will return Constants for objects which aren't represented by a
6597/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
6598/// Returns NULL if the SCEV isn't representable as a Constant.
6599static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00006600 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00006601 case scCouldNotCompute:
6602 case scAddRecExpr:
6603 break;
6604 case scConstant:
6605 return cast<SCEVConstant>(V)->getValue();
6606 case scUnknown:
6607 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
6608 case scSignExtend: {
6609 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
6610 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
6611 return ConstantExpr::getSExt(CastOp, SS->getType());
6612 break;
6613 }
6614 case scZeroExtend: {
6615 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
6616 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
6617 return ConstantExpr::getZExt(CastOp, SZ->getType());
6618 break;
6619 }
6620 case scTruncate: {
6621 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
6622 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
6623 return ConstantExpr::getTrunc(CastOp, ST->getType());
6624 break;
6625 }
6626 case scAddExpr: {
6627 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
6628 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006629 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6630 unsigned AS = PTy->getAddressSpace();
6631 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
6632 C = ConstantExpr::getBitCast(C, DestPtrTy);
6633 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00006634 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
6635 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006636 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006637
6638 // First pointer!
6639 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006640 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00006641 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006642 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006643 // The offsets have been converted to bytes. We can add bytes to an
6644 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006645 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006646 }
6647
6648 // Don't bother trying to sum two pointers. We probably can't
6649 // statically compute a load that results from it anyway.
6650 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00006651 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006652
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00006653 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
6654 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00006655 C2 = ConstantExpr::getIntegerCast(
6656 C2, Type::getInt32Ty(C->getContext()), true);
David Blaikie4a2e73b2015-04-02 18:55:32 +00006657 C = ConstantExpr::getGetElementPtr(PTy->getElementType(), C, C2);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006658 } else
6659 C = ConstantExpr::getAdd(C, C2);
6660 }
6661 return C;
6662 }
6663 break;
6664 }
6665 case scMulExpr: {
6666 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
6667 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
6668 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00006669 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006670 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
6671 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00006672 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006673 C = ConstantExpr::getMul(C, C2);
6674 }
6675 return C;
6676 }
6677 break;
6678 }
6679 case scUDivExpr: {
6680 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
6681 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
6682 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
6683 if (LHS->getType() == RHS->getType())
6684 return ConstantExpr::getUDiv(LHS, RHS);
6685 break;
6686 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00006687 case scSMaxExpr:
6688 case scUMaxExpr:
6689 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00006690 }
Craig Topper9f008862014-04-15 04:59:12 +00006691 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00006692}
6693
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00006694const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006695 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00006696
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006697 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00006698 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00006699 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006700 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006701 const Loop *LI = this->LI[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00006702 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
6703 if (PHINode *PN = dyn_cast<PHINode>(I))
6704 if (PN->getParent() == LI->getHeader()) {
6705 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00006706 // to see if the loop that contains it has a known backedge-taken
6707 // count. If so, we may be able to force computation of the exit
6708 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00006709 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00006710 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00006711 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006712 // Okay, we know how many times the containing loop executes. If
6713 // this is a constant evolving PHI node, get the final value at
6714 // the specified iteration number.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006715 Constant *RV =
6716 getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00006717 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00006718 }
6719 }
6720
Reid Spencere6328ca2006-12-04 21:33:23 +00006721 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00006722 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00006723 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00006724 // result. This is particularly useful for computing loop exit values.
6725 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006726 SmallVector<Constant *, 4> Operands;
6727 bool MadeImprovement = false;
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00006728 for (Value *Op : I->operands()) {
Chris Lattnerdd730472004-04-17 22:58:41 +00006729 if (Constant *C = dyn_cast<Constant>(Op)) {
6730 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006731 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00006732 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006733
6734 // If any of the operands is non-constant and if they are
6735 // non-integer and non-pointer, don't even try to analyze them
6736 // with scev techniques.
6737 if (!isSCEVable(Op->getType()))
6738 return V;
6739
6740 const SCEV *OrigV = getSCEV(Op);
6741 const SCEV *OpV = getSCEVAtScope(OrigV, L);
6742 MadeImprovement |= OrigV != OpV;
6743
Nick Lewyckya6674c72011-10-22 19:58:20 +00006744 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006745 if (!C) return V;
6746 if (C->getType() != Op->getType())
6747 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
6748 Op->getType(),
6749 false),
6750 C, Op->getType());
6751 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00006752 }
Dan Gohmance973df2009-06-24 04:48:43 +00006753
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006754 // Check to see if getSCEVAtScope actually made an improvement.
6755 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00006756 Constant *C = nullptr;
Sanjoy Das49edd3b2015-10-27 00:52:09 +00006757 const DataLayout &DL = getDataLayout();
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006758 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00006759 C = ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Chandler Carruth2f1fd162015-08-17 02:08:17 +00006760 Operands[1], DL, &TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006761 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
6762 if (!LI->isVolatile())
Eduard Burtescu14239212016-01-22 01:17:26 +00006763 C = ConstantFoldLoadFromConstPtr(Operands[0], LI->getType(), DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00006764 } else
Manuel Jacobe9024592016-01-21 06:33:22 +00006765 C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006766 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00006767 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006768 }
Chris Lattnerdd730472004-04-17 22:58:41 +00006769 }
6770 }
6771
6772 // This is some other type of SCEVUnknown, just return it.
6773 return V;
6774 }
6775
Dan Gohmana30370b2009-05-04 22:02:23 +00006776 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006777 // Avoid performing the look-up in the common case where the specified
6778 // expression has no loop-variant portions.
6779 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006780 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006781 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006782 // Okay, at least one of these operands is loop variant but might be
6783 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00006784 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
6785 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00006786 NewOps.push_back(OpAtScope);
6787
6788 for (++i; i != e; ++i) {
6789 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00006790 NewOps.push_back(OpAtScope);
6791 }
6792 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006793 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006794 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006795 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00006796 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006797 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00006798 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00006799 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00006800 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006801 }
6802 }
6803 // If we got here, all operands are loop invariant.
6804 return Comm;
6805 }
6806
Dan Gohmana30370b2009-05-04 22:02:23 +00006807 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006808 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
6809 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00006810 if (LHS == Div->getLHS() && RHS == Div->getRHS())
6811 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00006812 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00006813 }
6814
6815 // If this is a loop recurrence for a loop that does not contain L, then we
6816 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00006817 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006818 // First, attempt to evaluate each operand.
6819 // Avoid performing the look-up in the common case where the specified
6820 // expression has no loop-variant portions.
6821 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
6822 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
6823 if (OpAtScope == AddRec->getOperand(i))
6824 continue;
6825
6826 // Okay, at least one of these operands is loop variant but might be
6827 // foldable. Build a new instance of the folded commutative expression.
6828 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
6829 AddRec->op_begin()+i);
6830 NewOps.push_back(OpAtScope);
6831 for (++i; i != e; ++i)
6832 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
6833
Andrew Trick759ba082011-04-27 01:21:25 +00006834 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00006835 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00006836 AddRec->getNoWrapFlags(SCEV::FlagNW));
6837 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00006838 // The addrec may be folded to a nonrecurrence, for example, if the
6839 // induction variable is multiplied by zero after constant folding. Go
6840 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00006841 if (!AddRec)
6842 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006843 break;
6844 }
6845
6846 // If the scope is outside the addrec's loop, evaluate it by using the
6847 // loop exit value of the addrec.
6848 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006849 // To evaluate this recurrence, we need to know how many times the AddRec
6850 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00006851 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006852 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00006853
Eli Friedman61f67622008-08-04 23:49:06 +00006854 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006855 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00006856 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00006857
Dan Gohman8ca08852009-05-24 23:25:42 +00006858 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00006859 }
6860
Dan Gohmana30370b2009-05-04 22:02:23 +00006861 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006862 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006863 if (Op == Cast->getOperand())
6864 return Cast; // must be loop invariant
6865 return getZeroExtendExpr(Op, Cast->getType());
6866 }
6867
Dan Gohmana30370b2009-05-04 22:02:23 +00006868 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006869 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006870 if (Op == Cast->getOperand())
6871 return Cast; // must be loop invariant
6872 return getSignExtendExpr(Op, Cast->getType());
6873 }
6874
Dan Gohmana30370b2009-05-04 22:02:23 +00006875 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00006876 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00006877 if (Op == Cast->getOperand())
6878 return Cast; // must be loop invariant
6879 return getTruncateExpr(Op, Cast->getType());
6880 }
6881
Torok Edwinfbcc6632009-07-14 16:55:14 +00006882 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00006883}
6884
Dan Gohmanb81f47d2009-05-08 20:38:54 +00006885/// getSCEVAtScope - This is a convenience function which does
6886/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00006887const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00006888 return getSCEVAtScope(getSCEV(V), L);
6889}
6890
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006891/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
6892/// following equation:
6893///
6894/// A * X = B (mod N)
6895///
6896/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
6897/// A and B isn't important.
6898///
6899/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00006900static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006901 ScalarEvolution &SE) {
6902 uint32_t BW = A.getBitWidth();
6903 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
6904 assert(A != 0 && "A must be non-zero.");
6905
6906 // 1. D = gcd(A, N)
6907 //
6908 // The gcd of A and N may have only one prime factor: 2. The number of
6909 // trailing zeros in A is its multiplicity
6910 uint32_t Mult2 = A.countTrailingZeros();
6911 // D = 2^Mult2
6912
6913 // 2. Check if B is divisible by D.
6914 //
6915 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
6916 // is not less than multiplicity of this prime factor for D.
6917 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00006918 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006919
6920 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
6921 // modulo (N / D).
6922 //
6923 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
6924 // bit width during computations.
6925 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
6926 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00006927 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00006928 APInt I = AD.multiplicativeInverse(Mod);
6929
6930 // 4. Compute the minimum unsigned root of the equation:
6931 // I * (B / D) mod (N / D)
6932 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
6933
6934 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
6935 // bits.
6936 return SE.getConstant(Result.trunc(BW));
6937}
Chris Lattnerd934c702004-04-02 20:23:17 +00006938
6939/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
6940/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
6941/// might be the same) or two SCEVCouldNotCompute objects.
6942///
Dan Gohmanaf752342009-07-07 17:06:11 +00006943static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00006944SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006945 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00006946 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
6947 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
6948 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00006949
Chris Lattnerd934c702004-04-02 20:23:17 +00006950 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00006951 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00006952 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006953 return {CNC, CNC};
Chris Lattnerd934c702004-04-02 20:23:17 +00006954 }
6955
Sanjoy Das0de2fec2015-12-17 20:28:46 +00006956 uint32_t BitWidth = LC->getAPInt().getBitWidth();
6957 const APInt &L = LC->getAPInt();
6958 const APInt &M = MC->getAPInt();
6959 const APInt &N = NC->getAPInt();
Reid Spencer983e3b32007-03-01 07:25:48 +00006960 APInt Two(BitWidth, 2);
6961 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00006962
Dan Gohmance973df2009-06-24 04:48:43 +00006963 {
Reid Spencer983e3b32007-03-01 07:25:48 +00006964 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00006965 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00006966 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
6967 // The B coefficient is M-N/2
6968 APInt B(M);
6969 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00006970
Reid Spencer983e3b32007-03-01 07:25:48 +00006971 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00006972 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00006973
Reid Spencer983e3b32007-03-01 07:25:48 +00006974 // Compute the B^2-4ac term.
6975 APInt SqrtTerm(B);
6976 SqrtTerm *= B;
6977 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00006978
Nick Lewyckyfb780832012-08-01 09:14:36 +00006979 if (SqrtTerm.isNegative()) {
6980 // The loop is provably infinite.
6981 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006982 return {CNC, CNC};
Nick Lewyckyfb780832012-08-01 09:14:36 +00006983 }
6984
Reid Spencer983e3b32007-03-01 07:25:48 +00006985 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
6986 // integer value or else APInt::sqrt() will assert.
6987 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00006988
Dan Gohmance973df2009-06-24 04:48:43 +00006989 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00006990 // The divisions must be performed as signed divisions.
6991 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00006992 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00006993 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00006994 const SCEV *CNC = SE.getCouldNotCompute();
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00006995 return {CNC, CNC};
Nick Lewycky7b14e202008-11-03 02:43:49 +00006996 }
6997
Owen Anderson47db9412009-07-22 00:24:57 +00006998 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00006999
7000 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007001 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00007002 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00007003 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00007004
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007005 return {SE.getConstant(Solution1), SE.getConstant(Solution2)};
Nick Lewycky31555522011-10-03 07:10:45 +00007006 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00007007}
7008
7009/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00007010/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00007011///
7012/// This is only used for loops with a "x != y" exit test. The exit condition is
7013/// now expressed as a single expression, V = x-y. So the exit test is
7014/// effectively V != 0. We know and take advantage of the fact that this
7015/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00007016ScalarEvolution::ExitLimit
Silviu Baranga6f444df2016-04-08 14:29:09 +00007017ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
7018 bool AllowPredicates) {
7019 SCEVUnionPredicate P;
Chris Lattnerd934c702004-04-02 20:23:17 +00007020 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00007021 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007022 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00007023 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007024 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007025 }
7026
Dan Gohman48f82222009-05-04 22:30:44 +00007027 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007028 if (!AddRec && AllowPredicates)
7029 // Try to make this an AddRec using runtime tests, in the first X
7030 // iterations of this loop, where X is the SCEV expression found by the
7031 // algorithm below.
7032 AddRec = convertSCEVToAddRecWithPredicates(V, L, P);
7033
Chris Lattnerd934c702004-04-02 20:23:17 +00007034 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007035 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007036
Chris Lattnerdff679f2011-01-09 22:39:48 +00007037 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
7038 // the quadratic equation to solve it.
7039 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
7040 std::pair<const SCEV *,const SCEV *> Roots =
7041 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00007042 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7043 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00007044 if (R1 && R2) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007045 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007046 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00007047 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
7048 R1->getValue(),
7049 R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00007050 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00007051 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00007052
Chris Lattnerd934c702004-04-02 20:23:17 +00007053 // We can only use this value if the chrec ends up with an exact zero
7054 // value at this index. When solving for "X*X != 5", for example, we
7055 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00007056 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00007057 if (Val->isZero())
Silviu Baranga6f444df2016-04-08 14:29:09 +00007058 return ExitLimit(R1, R1, P); // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00007059 }
7060 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00007061 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007062 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007063
Chris Lattnerdff679f2011-01-09 22:39:48 +00007064 // Otherwise we can only handle this if it is affine.
7065 if (!AddRec->isAffine())
7066 return getCouldNotCompute();
7067
7068 // If this is an affine expression, the execution count of this branch is
7069 // the minimum unsigned root of the following equation:
7070 //
7071 // Start + Step*N = 0 (mod 2^BW)
7072 //
7073 // equivalent to:
7074 //
7075 // Step*N = -Start (mod 2^BW)
7076 //
7077 // where BW is the common bit width of Start and Step.
7078
7079 // Get the initial value for the loop.
7080 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
7081 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
7082
7083 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00007084 //
7085 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
7086 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
7087 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
7088 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00007089 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00007090 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00007091 return getCouldNotCompute();
7092
Andrew Trick8b55b732011-03-14 16:50:06 +00007093 // For positive steps (counting up until unsigned overflow):
7094 // N = -Start/Step (as unsigned)
7095 // For negative steps (counting down to zero):
7096 // N = Start/-Step
7097 // First compute the unsigned distance from zero in the direction of Step.
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007098 bool CountDown = StepC->getAPInt().isNegative();
Andrew Trickf1781db2011-03-14 17:28:02 +00007099 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00007100
7101 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00007102 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
7103 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00007104 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
7105 ConstantRange CR = getUnsignedRange(Start);
7106 const SCEV *MaxBECount;
7107 if (!CountDown && CR.getUnsignedMin().isMinValue())
7108 // When counting up, the worst starting value is 1, not 0.
7109 MaxBECount = CR.getUnsignedMax().isMinValue()
7110 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
7111 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
7112 else
7113 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
7114 : -CR.getUnsignedMin());
Silviu Baranga6f444df2016-04-08 14:29:09 +00007115 return ExitLimit(Distance, MaxBECount, P);
Nick Lewycky31555522011-10-03 07:10:45 +00007116 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00007117
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007118 // As a special case, handle the instance where Step is a positive power of
7119 // two. In this case, determining whether Step divides Distance evenly can be
7120 // done by counting and comparing the number of trailing zeros of Step and
7121 // Distance.
7122 if (!CountDown) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007123 const APInt &StepV = StepC->getAPInt();
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007124 // StepV.isPowerOf2() returns true if StepV is an positive power of two. It
7125 // also returns true if StepV is maximally negative (eg, INT_MIN), but that
7126 // case is not handled as this code is guarded by !CountDown.
7127 if (StepV.isPowerOf2() &&
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007128 GetMinTrailingZeros(Distance) >= StepV.countTrailingZeros()) {
7129 // Here we've constrained the equation to be of the form
7130 //
7131 // 2^(N + k) * Distance' = (StepV == 2^N) * X (mod 2^W) ... (0)
7132 //
7133 // where we're operating on a W bit wide integer domain and k is
7134 // non-negative. The smallest unsigned solution for X is the trip count.
7135 //
7136 // (0) is equivalent to:
7137 //
7138 // 2^(N + k) * Distance' - 2^N * X = L * 2^W
7139 // <=> 2^N(2^k * Distance' - X) = L * 2^(W - N) * 2^N
7140 // <=> 2^k * Distance' - X = L * 2^(W - N)
7141 // <=> 2^k * Distance' = L * 2^(W - N) + X ... (1)
7142 //
7143 // The smallest X satisfying (1) is unsigned remainder of dividing the LHS
7144 // by 2^(W - N).
7145 //
7146 // <=> X = 2^k * Distance' URem 2^(W - N) ... (2)
7147 //
7148 // E.g. say we're solving
7149 //
7150 // 2 * Val = 2 * X (in i8) ... (3)
7151 //
7152 // then from (2), we get X = Val URem i8 128 (k = 0 in this case).
7153 //
7154 // Note: It is tempting to solve (3) by setting X = Val, but Val is not
7155 // necessarily the smallest unsigned value of X that satisfies (3).
7156 // E.g. if Val is i8 -127 then the smallest value of X that satisfies (3)
7157 // is i8 1, not i8 -127
7158
7159 const auto *ModuloResult = getUDivExactExpr(Distance, Step);
7160
7161 // Since SCEV does not have a URem node, we construct one using a truncate
7162 // and a zero extend.
7163
7164 unsigned NarrowWidth = StepV.getBitWidth() - StepV.countTrailingZeros();
7165 auto *NarrowTy = IntegerType::get(getContext(), NarrowWidth);
7166 auto *WideTy = Distance->getType();
7167
Silviu Baranga6f444df2016-04-08 14:29:09 +00007168 const SCEV *Limit =
7169 getZeroExtendExpr(getTruncateExpr(ModuloResult, NarrowTy), WideTy);
7170 return ExitLimit(Limit, Limit, P);
Sanjoy Dasf3132d32015-09-10 05:27:38 +00007171 }
Mark Heffernanacbed5e2014-12-15 21:19:53 +00007172 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007173
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007174 // If the condition controls loop exit (the loop exits only if the expression
7175 // is true) and the addition is no-wrap we can use unsigned divide to
7176 // compute the backedge count. In this case, the step may not divide the
7177 // distance, but we don't care because if the condition is "missed" the loop
7178 // will have undefined behavior due to wrapping.
Sanjoy Das76c48e02016-02-04 18:21:54 +00007179 if (ControlsExit && AddRec->hasNoSelfWrap()) {
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007180 const SCEV *Exact =
7181 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
Silviu Baranga6f444df2016-04-08 14:29:09 +00007182 return ExitLimit(Exact, Exact, P);
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007183 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00007184
Chris Lattnerdff679f2011-01-09 22:39:48 +00007185 // Then, try to solve the above equation provided that Start is constant.
Silviu Baranga6f444df2016-04-08 14:29:09 +00007186 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
7187 const SCEV *E = SolveLinEquationWithOverflow(
7188 StepC->getValue()->getValue(), -StartC->getValue()->getValue(), *this);
7189 return ExitLimit(E, E, P);
7190 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007191 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007192}
7193
7194/// HowFarToNonZero - Return the number of times a backedge checking the
7195/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00007196/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00007197ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00007198ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007199 // Loops that look like: while (X == 0) are very strange indeed. We don't
7200 // handle them yet except for the trivial case. This could be expanded in the
7201 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00007202
Chris Lattnerd934c702004-04-02 20:23:17 +00007203 // If the value is a constant, check to see if it is known to be non-zero
7204 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00007205 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00007206 if (!C->getValue()->isNullValue())
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00007207 return getZero(C->getType());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007208 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00007209 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007210
Chris Lattnerd934c702004-04-02 20:23:17 +00007211 // We could implement others, but I really doubt anyone writes loops like
7212 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007213 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007214}
7215
Dan Gohmanf9081a22008-09-15 22:18:04 +00007216/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
7217/// (which may not be an immediate predecessor) which has exactly one
7218/// successor from which BB is reachable, or null if no such block is
7219/// found.
7220///
Dan Gohman4e3c1132010-04-15 16:19:08 +00007221std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00007222ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00007223 // If the block has a unique predecessor, then there is no path from the
7224 // predecessor to the block that does not go through the direct edge
7225 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00007226 if (BasicBlock *Pred = BB->getSinglePredecessor())
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007227 return {Pred, BB};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007228
7229 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007230 // If the header has a unique predecessor outside the loop, it must be
7231 // a block that has exactly one successor that can reach the loop.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007232 if (Loop *L = LI.getLoopFor(BB))
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007233 return {L->getLoopPredecessor(), L->getHeader()};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007234
Sanjoy Dasc42f7cc2016-02-20 01:35:56 +00007235 return {nullptr, nullptr};
Dan Gohmanf9081a22008-09-15 22:18:04 +00007236}
7237
Dan Gohman450f4e02009-06-20 00:35:32 +00007238/// HasSameValue - SCEV structural equivalence is usually sufficient for
7239/// testing whether two expressions are equal, however for the purposes of
7240/// looking for a condition guarding a loop, it can be useful to be a little
7241/// more general, since a front-end may have replicated the controlling
7242/// expression.
7243///
Dan Gohmanaf752342009-07-07 17:06:11 +00007244static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00007245 // Quick check to see if they are the same SCEV.
7246 if (A == B) return true;
7247
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007248 auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
7249 // Not all instructions that are "identical" compute the same value. For
7250 // instance, two distinct alloca instructions allocating the same type are
7251 // identical and do not read memory; but compute distinct values.
7252 return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
7253 };
7254
Dan Gohman450f4e02009-06-20 00:35:32 +00007255 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
7256 // two different instructions with the same value. Check for this case.
7257 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
7258 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
7259 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
7260 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Sanjoy Dasf1090b62015-09-27 21:09:48 +00007261 if (ComputesEqualValues(AI, BI))
Dan Gohman450f4e02009-06-20 00:35:32 +00007262 return true;
7263
7264 // Otherwise assume they may have a different value.
7265 return false;
7266}
7267
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007268/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00007269/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007270///
7271bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007272 const SCEV *&LHS, const SCEV *&RHS,
7273 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007274 bool Changed = false;
7275
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007276 // If we hit the max recursion limit bail out.
7277 if (Depth >= 3)
7278 return false;
7279
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007280 // Canonicalize a constant to the right side.
7281 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
7282 // Check for both operands constant.
7283 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
7284 if (ConstantExpr::getICmp(Pred,
7285 LHSC->getValue(),
7286 RHSC->getValue())->isNullValue())
7287 goto trivially_false;
7288 else
7289 goto trivially_true;
7290 }
7291 // Otherwise swap the operands to put the constant on the right.
7292 std::swap(LHS, RHS);
7293 Pred = ICmpInst::getSwappedPredicate(Pred);
7294 Changed = true;
7295 }
7296
7297 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00007298 // addrec's loop, put the addrec on the left. Also make a dominance check,
7299 // as both operands could be addrecs loop-invariant in each other's loop.
7300 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
7301 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00007302 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007303 std::swap(LHS, RHS);
7304 Pred = ICmpInst::getSwappedPredicate(Pred);
7305 Changed = true;
7306 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00007307 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007308
7309 // If there's a constant operand, canonicalize comparisons with boundary
7310 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
7311 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007312 const APInt &RA = RC->getAPInt();
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007313 switch (Pred) {
7314 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
7315 case ICmpInst::ICMP_EQ:
7316 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007317 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
7318 if (!RA)
7319 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
7320 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00007321 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
7322 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007323 RHS = AE->getOperand(1);
7324 LHS = ME->getOperand(1);
7325 Changed = true;
7326 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007327 break;
7328 case ICmpInst::ICMP_UGE:
7329 if ((RA - 1).isMinValue()) {
7330 Pred = ICmpInst::ICMP_NE;
7331 RHS = getConstant(RA - 1);
7332 Changed = true;
7333 break;
7334 }
7335 if (RA.isMaxValue()) {
7336 Pred = ICmpInst::ICMP_EQ;
7337 Changed = true;
7338 break;
7339 }
7340 if (RA.isMinValue()) goto trivially_true;
7341
7342 Pred = ICmpInst::ICMP_UGT;
7343 RHS = getConstant(RA - 1);
7344 Changed = true;
7345 break;
7346 case ICmpInst::ICMP_ULE:
7347 if ((RA + 1).isMaxValue()) {
7348 Pred = ICmpInst::ICMP_NE;
7349 RHS = getConstant(RA + 1);
7350 Changed = true;
7351 break;
7352 }
7353 if (RA.isMinValue()) {
7354 Pred = ICmpInst::ICMP_EQ;
7355 Changed = true;
7356 break;
7357 }
7358 if (RA.isMaxValue()) goto trivially_true;
7359
7360 Pred = ICmpInst::ICMP_ULT;
7361 RHS = getConstant(RA + 1);
7362 Changed = true;
7363 break;
7364 case ICmpInst::ICMP_SGE:
7365 if ((RA - 1).isMinSignedValue()) {
7366 Pred = ICmpInst::ICMP_NE;
7367 RHS = getConstant(RA - 1);
7368 Changed = true;
7369 break;
7370 }
7371 if (RA.isMaxSignedValue()) {
7372 Pred = ICmpInst::ICMP_EQ;
7373 Changed = true;
7374 break;
7375 }
7376 if (RA.isMinSignedValue()) goto trivially_true;
7377
7378 Pred = ICmpInst::ICMP_SGT;
7379 RHS = getConstant(RA - 1);
7380 Changed = true;
7381 break;
7382 case ICmpInst::ICMP_SLE:
7383 if ((RA + 1).isMaxSignedValue()) {
7384 Pred = ICmpInst::ICMP_NE;
7385 RHS = getConstant(RA + 1);
7386 Changed = true;
7387 break;
7388 }
7389 if (RA.isMinSignedValue()) {
7390 Pred = ICmpInst::ICMP_EQ;
7391 Changed = true;
7392 break;
7393 }
7394 if (RA.isMaxSignedValue()) goto trivially_true;
7395
7396 Pred = ICmpInst::ICMP_SLT;
7397 RHS = getConstant(RA + 1);
7398 Changed = true;
7399 break;
7400 case ICmpInst::ICMP_UGT:
7401 if (RA.isMinValue()) {
7402 Pred = ICmpInst::ICMP_NE;
7403 Changed = true;
7404 break;
7405 }
7406 if ((RA + 1).isMaxValue()) {
7407 Pred = ICmpInst::ICMP_EQ;
7408 RHS = getConstant(RA + 1);
7409 Changed = true;
7410 break;
7411 }
7412 if (RA.isMaxValue()) goto trivially_false;
7413 break;
7414 case ICmpInst::ICMP_ULT:
7415 if (RA.isMaxValue()) {
7416 Pred = ICmpInst::ICMP_NE;
7417 Changed = true;
7418 break;
7419 }
7420 if ((RA - 1).isMinValue()) {
7421 Pred = ICmpInst::ICMP_EQ;
7422 RHS = getConstant(RA - 1);
7423 Changed = true;
7424 break;
7425 }
7426 if (RA.isMinValue()) goto trivially_false;
7427 break;
7428 case ICmpInst::ICMP_SGT:
7429 if (RA.isMinSignedValue()) {
7430 Pred = ICmpInst::ICMP_NE;
7431 Changed = true;
7432 break;
7433 }
7434 if ((RA + 1).isMaxSignedValue()) {
7435 Pred = ICmpInst::ICMP_EQ;
7436 RHS = getConstant(RA + 1);
7437 Changed = true;
7438 break;
7439 }
7440 if (RA.isMaxSignedValue()) goto trivially_false;
7441 break;
7442 case ICmpInst::ICMP_SLT:
7443 if (RA.isMaxSignedValue()) {
7444 Pred = ICmpInst::ICMP_NE;
7445 Changed = true;
7446 break;
7447 }
7448 if ((RA - 1).isMinSignedValue()) {
7449 Pred = ICmpInst::ICMP_EQ;
7450 RHS = getConstant(RA - 1);
7451 Changed = true;
7452 break;
7453 }
7454 if (RA.isMinSignedValue()) goto trivially_false;
7455 break;
7456 }
7457 }
7458
7459 // Check for obvious equality.
7460 if (HasSameValue(LHS, RHS)) {
7461 if (ICmpInst::isTrueWhenEqual(Pred))
7462 goto trivially_true;
7463 if (ICmpInst::isFalseWhenEqual(Pred))
7464 goto trivially_false;
7465 }
7466
Dan Gohman81585c12010-05-03 16:35:17 +00007467 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
7468 // adding or subtracting 1 from one of the operands.
7469 switch (Pred) {
7470 case ICmpInst::ICMP_SLE:
7471 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
7472 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007473 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007474 Pred = ICmpInst::ICMP_SLT;
7475 Changed = true;
7476 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007477 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007478 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007479 Pred = ICmpInst::ICMP_SLT;
7480 Changed = true;
7481 }
7482 break;
7483 case ICmpInst::ICMP_SGE:
7484 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007485 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007486 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007487 Pred = ICmpInst::ICMP_SGT;
7488 Changed = true;
7489 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
7490 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007491 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00007492 Pred = ICmpInst::ICMP_SGT;
7493 Changed = true;
7494 }
7495 break;
7496 case ICmpInst::ICMP_ULE:
7497 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007498 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007499 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007500 Pred = ICmpInst::ICMP_ULT;
7501 Changed = true;
7502 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007503 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007504 Pred = ICmpInst::ICMP_ULT;
7505 Changed = true;
7506 }
7507 break;
7508 case ICmpInst::ICMP_UGE:
7509 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Peter Collingbournec85f4ce2015-11-20 01:26:13 +00007510 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
Dan Gohman81585c12010-05-03 16:35:17 +00007511 Pred = ICmpInst::ICMP_UGT;
7512 Changed = true;
7513 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00007514 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00007515 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00007516 Pred = ICmpInst::ICMP_UGT;
7517 Changed = true;
7518 }
7519 break;
7520 default:
7521 break;
7522 }
7523
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007524 // TODO: More simplifications are possible here.
7525
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00007526 // Recursively simplify until we either hit a recursion limit or nothing
7527 // changes.
7528 if (Changed)
7529 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
7530
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007531 return Changed;
7532
7533trivially_true:
7534 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007535 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007536 Pred = ICmpInst::ICMP_EQ;
7537 return true;
7538
7539trivially_false:
7540 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00007541 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00007542 Pred = ICmpInst::ICMP_NE;
7543 return true;
7544}
7545
Dan Gohmane65c9172009-07-13 21:35:55 +00007546bool ScalarEvolution::isKnownNegative(const SCEV *S) {
7547 return getSignedRange(S).getSignedMax().isNegative();
7548}
7549
7550bool ScalarEvolution::isKnownPositive(const SCEV *S) {
7551 return getSignedRange(S).getSignedMin().isStrictlyPositive();
7552}
7553
7554bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
7555 return !getSignedRange(S).getSignedMin().isNegative();
7556}
7557
7558bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
7559 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
7560}
7561
7562bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
7563 return isKnownNegative(S) || isKnownPositive(S);
7564}
7565
7566bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
7567 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00007568 // Canonicalize the inputs first.
7569 (void)SimplifyICmpOperands(Pred, LHS, RHS);
7570
Dan Gohman07591692010-04-11 22:16:48 +00007571 // If LHS or RHS is an addrec, check to see if the condition is true in
7572 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00007573 // If LHS and RHS are both addrec, both conditions must be true in
7574 // every iteration of the loop.
7575 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
7576 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
7577 bool LeftGuarded = false;
7578 bool RightGuarded = false;
7579 if (LAR) {
7580 const Loop *L = LAR->getLoop();
7581 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
7582 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
7583 if (!RAR) return true;
7584 LeftGuarded = true;
7585 }
7586 }
7587 if (RAR) {
7588 const Loop *L = RAR->getLoop();
7589 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
7590 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
7591 if (!LAR) return true;
7592 RightGuarded = true;
7593 }
7594 }
7595 if (LeftGuarded && RightGuarded)
7596 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007597
Sanjoy Das7d910f22015-10-02 18:50:30 +00007598 if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
7599 return true;
7600
Dan Gohman07591692010-04-11 22:16:48 +00007601 // Otherwise see what can be done with known constant ranges.
Sanjoy Das401e6312016-02-01 20:48:10 +00007602 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS);
Dan Gohman07591692010-04-11 22:16:48 +00007603}
7604
Sanjoy Das5dab2052015-07-27 21:42:49 +00007605bool ScalarEvolution::isMonotonicPredicate(const SCEVAddRecExpr *LHS,
7606 ICmpInst::Predicate Pred,
7607 bool &Increasing) {
7608 bool Result = isMonotonicPredicateImpl(LHS, Pred, Increasing);
7609
7610#ifndef NDEBUG
7611 // Verify an invariant: inverting the predicate should turn a monotonically
7612 // increasing change to a monotonically decreasing one, and vice versa.
7613 bool IncreasingSwapped;
7614 bool ResultSwapped = isMonotonicPredicateImpl(
7615 LHS, ICmpInst::getSwappedPredicate(Pred), IncreasingSwapped);
7616
7617 assert(Result == ResultSwapped && "should be able to analyze both!");
7618 if (ResultSwapped)
7619 assert(Increasing == !IncreasingSwapped &&
7620 "monotonicity should flip as we flip the predicate");
7621#endif
7622
7623 return Result;
7624}
7625
7626bool ScalarEvolution::isMonotonicPredicateImpl(const SCEVAddRecExpr *LHS,
7627 ICmpInst::Predicate Pred,
7628 bool &Increasing) {
Sanjoy Das5dab2052015-07-27 21:42:49 +00007629
7630 // A zero step value for LHS means the induction variable is essentially a
7631 // loop invariant value. We don't really depend on the predicate actually
7632 // flipping from false to true (for increasing predicates, and the other way
7633 // around for decreasing predicates), all we care about is that *if* the
7634 // predicate changes then it only changes from false to true.
7635 //
7636 // A zero step value in itself is not very useful, but there may be places
7637 // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
7638 // as general as possible.
7639
Sanjoy Das366acc12015-08-06 20:43:41 +00007640 switch (Pred) {
7641 default:
7642 return false; // Conservative answer
7643
7644 case ICmpInst::ICMP_UGT:
7645 case ICmpInst::ICMP_UGE:
7646 case ICmpInst::ICMP_ULT:
7647 case ICmpInst::ICMP_ULE:
Sanjoy Das76c48e02016-02-04 18:21:54 +00007648 if (!LHS->hasNoUnsignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007649 return false;
7650
7651 Increasing = Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007652 return true;
Sanjoy Das366acc12015-08-06 20:43:41 +00007653
7654 case ICmpInst::ICMP_SGT:
7655 case ICmpInst::ICMP_SGE:
7656 case ICmpInst::ICMP_SLT:
7657 case ICmpInst::ICMP_SLE: {
Sanjoy Das76c48e02016-02-04 18:21:54 +00007658 if (!LHS->hasNoSignedWrap())
Sanjoy Das366acc12015-08-06 20:43:41 +00007659 return false;
7660
7661 const SCEV *Step = LHS->getStepRecurrence(*this);
7662
7663 if (isKnownNonNegative(Step)) {
7664 Increasing = Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE;
7665 return true;
7666 }
7667
7668 if (isKnownNonPositive(Step)) {
7669 Increasing = Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE;
7670 return true;
7671 }
7672
7673 return false;
Sanjoy Das5dab2052015-07-27 21:42:49 +00007674 }
7675
Sanjoy Das5dab2052015-07-27 21:42:49 +00007676 }
7677
Sanjoy Das366acc12015-08-06 20:43:41 +00007678 llvm_unreachable("switch has default clause!");
Sanjoy Das5dab2052015-07-27 21:42:49 +00007679}
7680
7681bool ScalarEvolution::isLoopInvariantPredicate(
7682 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
7683 ICmpInst::Predicate &InvariantPred, const SCEV *&InvariantLHS,
7684 const SCEV *&InvariantRHS) {
7685
7686 // If there is a loop-invariant, force it into the RHS, otherwise bail out.
7687 if (!isLoopInvariant(RHS, L)) {
7688 if (!isLoopInvariant(LHS, L))
7689 return false;
7690
7691 std::swap(LHS, RHS);
7692 Pred = ICmpInst::getSwappedPredicate(Pred);
7693 }
7694
7695 const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
7696 if (!ArLHS || ArLHS->getLoop() != L)
7697 return false;
7698
7699 bool Increasing;
7700 if (!isMonotonicPredicate(ArLHS, Pred, Increasing))
7701 return false;
7702
7703 // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
7704 // true as the loop iterates, and the backedge is control dependent on
7705 // "ArLHS `Pred` RHS" == true then we can reason as follows:
7706 //
7707 // * if the predicate was false in the first iteration then the predicate
7708 // is never evaluated again, since the loop exits without taking the
7709 // backedge.
7710 // * if the predicate was true in the first iteration then it will
7711 // continue to be true for all future iterations since it is
7712 // monotonically increasing.
7713 //
7714 // For both the above possibilities, we can replace the loop varying
7715 // predicate with its value on the first iteration of the loop (which is
7716 // loop invariant).
7717 //
7718 // A similar reasoning applies for a monotonically decreasing predicate, by
7719 // replacing true with false and false with true in the above two bullets.
7720
7721 auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
7722
7723 if (!isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
7724 return false;
7725
7726 InvariantPred = Pred;
7727 InvariantLHS = ArLHS->getStart();
7728 InvariantRHS = RHS;
7729 return true;
7730}
7731
Sanjoy Das401e6312016-02-01 20:48:10 +00007732bool ScalarEvolution::isKnownPredicateViaConstantRanges(
7733 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00007734 if (HasSameValue(LHS, RHS))
7735 return ICmpInst::isTrueWhenEqual(Pred);
7736
Dan Gohman07591692010-04-11 22:16:48 +00007737 // This code is split out from isKnownPredicate because it is called from
7738 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00007739
Sanjoy Das4c7b6d72016-02-01 20:48:14 +00007740 auto CheckRanges =
7741 [&](const ConstantRange &RangeLHS, const ConstantRange &RangeRHS) {
7742 return ConstantRange::makeSatisfyingICmpRegion(Pred, RangeRHS)
7743 .contains(RangeLHS);
7744 };
7745
7746 // The check at the top of the function catches the case where the values are
7747 // known to be equal.
7748 if (Pred == CmpInst::ICMP_EQ)
7749 return false;
7750
7751 if (Pred == CmpInst::ICMP_NE)
7752 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS)) ||
7753 CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS)) ||
7754 isKnownNonZero(getMinusSCEV(LHS, RHS));
7755
7756 if (CmpInst::isSigned(Pred))
7757 return CheckRanges(getSignedRange(LHS), getSignedRange(RHS));
7758
7759 return CheckRanges(getUnsignedRange(LHS), getUnsignedRange(RHS));
Dan Gohmane65c9172009-07-13 21:35:55 +00007760}
7761
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007762bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
7763 const SCEV *LHS,
7764 const SCEV *RHS) {
7765
7766 // Match Result to (X + Y)<ExpectedFlags> where Y is a constant integer.
7767 // Return Y via OutY.
7768 auto MatchBinaryAddToConst =
7769 [this](const SCEV *Result, const SCEV *X, APInt &OutY,
7770 SCEV::NoWrapFlags ExpectedFlags) {
7771 const SCEV *NonConstOp, *ConstOp;
7772 SCEV::NoWrapFlags FlagsPresent;
7773
7774 if (!splitBinaryAdd(Result, ConstOp, NonConstOp, FlagsPresent) ||
7775 !isa<SCEVConstant>(ConstOp) || NonConstOp != X)
7776 return false;
7777
Sanjoy Das0de2fec2015-12-17 20:28:46 +00007778 OutY = cast<SCEVConstant>(ConstOp)->getAPInt();
Sanjoy Dasc1a29772015-11-05 23:45:38 +00007779 return (FlagsPresent & ExpectedFlags) == ExpectedFlags;
7780 };
7781
7782 APInt C;
7783
7784 switch (Pred) {
7785 default:
7786 break;
7787
7788 case ICmpInst::ICMP_SGE:
7789 std::swap(LHS, RHS);
7790 case ICmpInst::ICMP_SLE:
7791 // X s<= (X + C)<nsw> if C >= 0
7792 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) && C.isNonNegative())
7793 return true;
7794
7795 // (X + C)<nsw> s<= X if C <= 0
7796 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) &&
7797 !C.isStrictlyPositive())
7798 return true;
7799 break;
7800
7801 case ICmpInst::ICMP_SGT:
7802 std::swap(LHS, RHS);
7803 case ICmpInst::ICMP_SLT:
7804 // X s< (X + C)<nsw> if C > 0
7805 if (MatchBinaryAddToConst(RHS, LHS, C, SCEV::FlagNSW) &&
7806 C.isStrictlyPositive())
7807 return true;
7808
7809 // (X + C)<nsw> s< X if C < 0
7810 if (MatchBinaryAddToConst(LHS, RHS, C, SCEV::FlagNSW) && C.isNegative())
7811 return true;
7812 break;
7813 }
7814
7815 return false;
7816}
7817
Sanjoy Das7d910f22015-10-02 18:50:30 +00007818bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
7819 const SCEV *LHS,
7820 const SCEV *RHS) {
Sanjoy Das10dffcb2015-10-08 03:46:00 +00007821 if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
Sanjoy Das7d910f22015-10-02 18:50:30 +00007822 return false;
7823
7824 // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
7825 // the stack can result in exponential time complexity.
7826 SaveAndRestore<bool> Restore(ProvingSplitPredicate, true);
7827
7828 // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
7829 //
7830 // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
7831 // isKnownPredicate. isKnownPredicate is more powerful, but also more
7832 // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
7833 // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
7834 // use isKnownPredicate later if needed.
Alexander Kornienko484e48e32015-11-05 21:07:12 +00007835 return isKnownNonNegative(RHS) &&
7836 isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
7837 isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
Sanjoy Das7d910f22015-10-02 18:50:30 +00007838}
7839
Dan Gohmane65c9172009-07-13 21:35:55 +00007840/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
7841/// protected by a conditional between LHS and RHS. This is used to
7842/// to eliminate casts.
7843bool
7844ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
7845 ICmpInst::Predicate Pred,
7846 const SCEV *LHS, const SCEV *RHS) {
7847 // Interpret a null as meaning no loop, where there is obviously no guard
7848 // (interprocedural conditions notwithstanding).
7849 if (!L) return true;
7850
Sanjoy Das401e6312016-02-01 20:48:10 +00007851 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7852 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007853
Dan Gohmane65c9172009-07-13 21:35:55 +00007854 BasicBlock *Latch = L->getLoopLatch();
7855 if (!Latch)
7856 return false;
7857
7858 BranchInst *LoopContinuePredicate =
7859 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007860 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
7861 isImpliedCond(Pred, LHS, RHS,
7862 LoopContinuePredicate->getCondition(),
7863 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
7864 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00007865
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007866 // We don't want more than one activation of the following loops on the stack
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007867 // -- that can lead to O(n!) time complexity.
7868 if (WalkingBEDominatingConds)
7869 return false;
7870
Sanjoy Das5d9a8cb2015-09-22 00:10:57 +00007871 SaveAndRestore<bool> ClearOnExit(WalkingBEDominatingConds, true);
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007872
Sanjoy Dasb174f9a2015-09-25 23:53:50 +00007873 // See if we can exploit a trip count to prove the predicate.
7874 const auto &BETakenInfo = getBackedgeTakenInfo(L);
7875 const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
7876 if (LatchBECount != getCouldNotCompute()) {
7877 // We know that Latch branches back to the loop header exactly
7878 // LatchBECount times. This means the backdege condition at Latch is
7879 // equivalent to "{0,+,1} u< LatchBECount".
7880 Type *Ty = LatchBECount->getType();
7881 auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
7882 const SCEV *LoopCounter =
7883 getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
7884 if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
7885 LatchBECount))
7886 return true;
7887 }
7888
Piotr Padlewski0dde00d22015-09-09 20:47:30 +00007889 // Check conditions due to any @llvm.assume intrinsics.
7890 for (auto &AssumeVH : AC.assumptions()) {
7891 if (!AssumeVH)
7892 continue;
7893 auto *CI = cast<CallInst>(AssumeVH);
7894 if (!DT.dominates(CI, Latch->getTerminator()))
7895 continue;
7896
7897 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7898 return true;
7899 }
7900
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007901 // If the loop is not reachable from the entry block, we risk running into an
7902 // infinite loop as we walk up into the dom tree. These loops do not matter
7903 // anyway, so we just return a conservative answer when we see them.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007904 if (!DT.isReachableFromEntry(L->getHeader()))
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007905 return false;
7906
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007907 for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
7908 DTN != HeaderDTN; DTN = DTN->getIDom()) {
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007909
7910 assert(DTN && "should reach the loop header before reaching the root!");
7911
7912 BasicBlock *BB = DTN->getBlock();
7913 BasicBlock *PBB = BB->getSinglePredecessor();
7914 if (!PBB)
7915 continue;
7916
7917 BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
7918 if (!ContinuePredicate || !ContinuePredicate->isConditional())
7919 continue;
7920
7921 Value *Condition = ContinuePredicate->getCondition();
7922
7923 // If we have an edge `E` within the loop body that dominates the only
7924 // latch, the condition guarding `E` also guards the backedge. This
7925 // reasoning works only for loops with a single latch.
7926
7927 BasicBlockEdge DominatingEdge(PBB, BB);
7928 if (DominatingEdge.isSingleEdge()) {
7929 // We're constructively (and conservatively) enumerating edges within the
7930 // loop body that dominate the latch. The dominator tree better agree
7931 // with us on this:
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007932 assert(DT.dominates(DominatingEdge, Latch) && "should be!");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00007933
7934 if (isImpliedCond(Pred, LHS, RHS, Condition,
7935 BB != ContinuePredicate->getSuccessor(0)))
7936 return true;
7937 }
7938 }
7939
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007940 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00007941}
7942
Dan Gohmanb50349a2010-04-11 19:27:13 +00007943/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00007944/// by a conditional between LHS and RHS. This is used to help avoid max
7945/// expressions in loop trip counts, and to eliminate casts.
7946bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00007947ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
7948 ICmpInst::Predicate Pred,
7949 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00007950 // Interpret a null as meaning no loop, where there is obviously no guard
7951 // (interprocedural conditions notwithstanding).
7952 if (!L) return false;
7953
Sanjoy Das401e6312016-02-01 20:48:10 +00007954 if (isKnownPredicateViaConstantRanges(Pred, LHS, RHS))
7955 return true;
Sanjoy Das1f05c512014-10-10 21:22:34 +00007956
Dan Gohman8c77f1a2009-05-18 15:36:09 +00007957 // Starting at the loop predecessor, climb up the predecessor chain, as long
7958 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00007959 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00007960 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00007961 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00007962 Pair.first;
7963 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00007964
7965 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00007966 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00007967 if (!LoopEntryPredicate ||
7968 LoopEntryPredicate->isUnconditional())
7969 continue;
7970
Dan Gohmane18c2d62010-08-10 23:46:30 +00007971 if (isImpliedCond(Pred, LHS, RHS,
7972 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00007973 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00007974 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007975 }
7976
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007977 // Check conditions due to any @llvm.assume intrinsics.
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007978 for (auto &AssumeVH : AC.assumptions()) {
Chandler Carruth66b31302015-01-04 12:03:27 +00007979 if (!AssumeVH)
7980 continue;
7981 auto *CI = cast<CallInst>(AssumeVH);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00007982 if (!DT.dominates(CI, L->getHeader()))
Hal Finkelcebf0cc2014-09-07 21:37:59 +00007983 continue;
7984
7985 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
7986 return true;
7987 }
7988
Dan Gohman2a62fd92008-08-12 20:17:31 +00007989 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00007990}
7991
Benjamin Kramer039b1042015-10-28 13:54:36 +00007992namespace {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007993/// RAII wrapper to prevent recursive application of isImpliedCond.
7994/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
7995/// currently evaluating isImpliedCond.
7996struct MarkPendingLoopPredicate {
7997 Value *Cond;
7998 DenseSet<Value*> &LoopPreds;
7999 bool Pending;
8000
8001 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
8002 : Cond(C), LoopPreds(LP) {
8003 Pending = !LoopPreds.insert(Cond).second;
8004 }
8005 ~MarkPendingLoopPredicate() {
8006 if (!Pending)
8007 LoopPreds.erase(Cond);
8008 }
8009};
Benjamin Kramer039b1042015-10-28 13:54:36 +00008010} // end anonymous namespace
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008011
Dan Gohman430f0cc2009-07-21 23:03:19 +00008012/// isImpliedCond - Test whether the condition described by Pred, LHS,
8013/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008014bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008015 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00008016 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008017 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00008018 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
8019 if (Mark.Pending)
8020 return false;
8021
Dan Gohman8b0a4192010-03-01 17:49:51 +00008022 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00008023 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008024 if (BO->getOpcode() == Instruction::And) {
8025 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008026 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8027 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008028 } else if (BO->getOpcode() == Instruction::Or) {
8029 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00008030 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
8031 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008032 }
8033 }
8034
Dan Gohmane18c2d62010-08-10 23:46:30 +00008035 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008036 if (!ICI) return false;
8037
Andrew Trickfa594032012-11-29 18:35:13 +00008038 // Now that we found a conditional branch that dominates the loop or controls
8039 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00008040 ICmpInst::Predicate FoundPred;
8041 if (Inverse)
8042 FoundPred = ICI->getInversePredicate();
8043 else
8044 FoundPred = ICI->getPredicate();
8045
8046 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
8047 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00008048
Sanjoy Dasdf1635d2015-09-25 19:59:52 +00008049 return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS);
8050}
8051
8052bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
8053 const SCEV *RHS,
8054 ICmpInst::Predicate FoundPred,
8055 const SCEV *FoundLHS,
8056 const SCEV *FoundRHS) {
Sanjoy Das14598832015-03-26 17:28:26 +00008057 // Balance the types.
8058 if (getTypeSizeInBits(LHS->getType()) <
8059 getTypeSizeInBits(FoundLHS->getType())) {
8060 if (CmpInst::isSigned(Pred)) {
8061 LHS = getSignExtendExpr(LHS, FoundLHS->getType());
8062 RHS = getSignExtendExpr(RHS, FoundLHS->getType());
8063 } else {
8064 LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
8065 RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
8066 }
8067 } else if (getTypeSizeInBits(LHS->getType()) >
Dan Gohmane65c9172009-07-13 21:35:55 +00008068 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00008069 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00008070 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
8071 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
8072 } else {
8073 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
8074 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
8075 }
8076 }
8077
Dan Gohman430f0cc2009-07-21 23:03:19 +00008078 // Canonicalize the query to match the way instcombine will have
8079 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00008080 if (SimplifyICmpOperands(Pred, LHS, RHS))
8081 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00008082 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00008083 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
8084 if (FoundLHS == FoundRHS)
8085 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00008086
8087 // Check to see if we can make the LHS or RHS match.
8088 if (LHS == FoundRHS || RHS == FoundLHS) {
8089 if (isa<SCEVConstant>(RHS)) {
8090 std::swap(FoundLHS, FoundRHS);
8091 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
8092 } else {
8093 std::swap(LHS, RHS);
8094 Pred = ICmpInst::getSwappedPredicate(Pred);
8095 }
8096 }
8097
8098 // Check whether the found predicate is the same as the desired predicate.
8099 if (FoundPred == Pred)
8100 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8101
8102 // Check whether swapping the found predicate makes it the same as the
8103 // desired predicate.
8104 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
8105 if (isa<SCEVConstant>(RHS))
8106 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
8107 else
8108 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
8109 RHS, LHS, FoundLHS, FoundRHS);
8110 }
8111
Sanjoy Das6e78b172015-10-22 19:57:34 +00008112 // Unsigned comparison is the same as signed comparison when both the operands
8113 // are non-negative.
8114 if (CmpInst::isUnsigned(FoundPred) &&
8115 CmpInst::getSignedPredicate(FoundPred) == Pred &&
8116 isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS))
8117 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
8118
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008119 // Check if we can make progress by sharpening ranges.
8120 if (FoundPred == ICmpInst::ICMP_NE &&
8121 (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
8122
8123 const SCEVConstant *C = nullptr;
8124 const SCEV *V = nullptr;
8125
8126 if (isa<SCEVConstant>(FoundLHS)) {
8127 C = cast<SCEVConstant>(FoundLHS);
8128 V = FoundRHS;
8129 } else {
8130 C = cast<SCEVConstant>(FoundRHS);
8131 V = FoundLHS;
8132 }
8133
8134 // The guarding predicate tells us that C != V. If the known range
8135 // of V is [C, t), we can sharpen the range to [C + 1, t). The
8136 // range we consider has to correspond to same signedness as the
8137 // predicate we're interested in folding.
8138
8139 APInt Min = ICmpInst::isSigned(Pred) ?
8140 getSignedRange(V).getSignedMin() : getUnsignedRange(V).getUnsignedMin();
8141
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008142 if (Min == C->getAPInt()) {
Sanjoy Dasc5676df2014-11-13 00:00:58 +00008143 // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
8144 // This is true even if (Min + 1) wraps around -- in case of
8145 // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
8146
8147 APInt SharperMin = Min + 1;
8148
8149 switch (Pred) {
8150 case ICmpInst::ICMP_SGE:
8151 case ICmpInst::ICMP_UGE:
8152 // We know V `Pred` SharperMin. If this implies LHS `Pred`
8153 // RHS, we're done.
8154 if (isImpliedCondOperands(Pred, LHS, RHS, V,
8155 getConstant(SharperMin)))
8156 return true;
8157
8158 case ICmpInst::ICMP_SGT:
8159 case ICmpInst::ICMP_UGT:
8160 // We know from the range information that (V `Pred` Min ||
8161 // V == Min). We know from the guarding condition that !(V
8162 // == Min). This gives us
8163 //
8164 // V `Pred` Min || V == Min && !(V == Min)
8165 // => V `Pred` Min
8166 //
8167 // If V `Pred` Min implies LHS `Pred` RHS, we're done.
8168
8169 if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min)))
8170 return true;
8171
8172 default:
8173 // No change
8174 break;
8175 }
8176 }
8177 }
8178
Dan Gohman430f0cc2009-07-21 23:03:19 +00008179 // Check whether the actual condition is beyond sufficient.
8180 if (FoundPred == ICmpInst::ICMP_EQ)
8181 if (ICmpInst::isTrueWhenEqual(Pred))
8182 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
8183 return true;
8184 if (Pred == ICmpInst::ICMP_NE)
8185 if (!ICmpInst::isTrueWhenEqual(FoundPred))
8186 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
8187 return true;
8188
8189 // Otherwise assume the worst.
8190 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00008191}
8192
Sanjoy Das1ed69102015-10-13 02:53:27 +00008193bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
8194 const SCEV *&L, const SCEV *&R,
8195 SCEV::NoWrapFlags &Flags) {
8196 const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
8197 if (!AE || AE->getNumOperands() != 2)
8198 return false;
8199
8200 L = AE->getOperand(0);
8201 R = AE->getOperand(1);
8202 Flags = AE->getNoWrapFlags();
8203 return true;
8204}
8205
8206bool ScalarEvolution::computeConstantDifference(const SCEV *Less,
8207 const SCEV *More,
8208 APInt &C) {
Sanjoy Das96709c42015-09-25 23:53:45 +00008209 // We avoid subtracting expressions here because this function is usually
8210 // fairly deep in the call stack (i.e. is called many times).
8211
Sanjoy Das96709c42015-09-25 23:53:45 +00008212 if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
8213 const auto *LAR = cast<SCEVAddRecExpr>(Less);
8214 const auto *MAR = cast<SCEVAddRecExpr>(More);
8215
8216 if (LAR->getLoop() != MAR->getLoop())
8217 return false;
8218
8219 // We look at affine expressions only; not for correctness but to keep
8220 // getStepRecurrence cheap.
8221 if (!LAR->isAffine() || !MAR->isAffine())
8222 return false;
8223
Sanjoy Das1ed69102015-10-13 02:53:27 +00008224 if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
Sanjoy Das96709c42015-09-25 23:53:45 +00008225 return false;
8226
8227 Less = LAR->getStart();
8228 More = MAR->getStart();
8229
8230 // fall through
8231 }
8232
8233 if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008234 const auto &M = cast<SCEVConstant>(More)->getAPInt();
8235 const auto &L = cast<SCEVConstant>(Less)->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008236 C = M - L;
8237 return true;
8238 }
8239
8240 const SCEV *L, *R;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008241 SCEV::NoWrapFlags Flags;
8242 if (splitBinaryAdd(Less, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008243 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8244 if (R == More) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008245 C = -(LC->getAPInt());
Sanjoy Das96709c42015-09-25 23:53:45 +00008246 return true;
8247 }
8248
Sanjoy Das1ed69102015-10-13 02:53:27 +00008249 if (splitBinaryAdd(More, L, R, Flags))
Sanjoy Das96709c42015-09-25 23:53:45 +00008250 if (const auto *LC = dyn_cast<SCEVConstant>(L))
8251 if (R == Less) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008252 C = LC->getAPInt();
Sanjoy Das96709c42015-09-25 23:53:45 +00008253 return true;
8254 }
8255
8256 return false;
8257}
8258
8259bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
8260 ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
8261 const SCEV *FoundLHS, const SCEV *FoundRHS) {
8262 if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
8263 return false;
8264
8265 const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
8266 if (!AddRecLHS)
8267 return false;
8268
8269 const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
8270 if (!AddRecFoundLHS)
8271 return false;
8272
8273 // We'd like to let SCEV reason about control dependencies, so we constrain
8274 // both the inequalities to be about add recurrences on the same loop. This
8275 // way we can use isLoopEntryGuardedByCond later.
8276
8277 const Loop *L = AddRecFoundLHS->getLoop();
8278 if (L != AddRecLHS->getLoop())
8279 return false;
8280
8281 // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
8282 //
8283 // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
8284 // ... (2)
8285 //
8286 // Informal proof for (2), assuming (1) [*]:
8287 //
8288 // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
8289 //
8290 // Then
8291 //
8292 // FoundLHS s< FoundRHS s< INT_MIN - C
8293 // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
8294 // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
8295 // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
8296 // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
8297 // <=> FoundLHS + C s< FoundRHS + C
8298 //
8299 // [*]: (1) can be proved by ruling out overflow.
8300 //
8301 // [**]: This can be proved by analyzing all the four possibilities:
8302 // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
8303 // (A s>= 0, B s>= 0).
8304 //
8305 // Note:
8306 // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
8307 // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
8308 // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
8309 // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
8310 // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
8311 // C)".
8312
8313 APInt LDiff, RDiff;
Sanjoy Das1ed69102015-10-13 02:53:27 +00008314 if (!computeConstantDifference(FoundLHS, LHS, LDiff) ||
8315 !computeConstantDifference(FoundRHS, RHS, RDiff) ||
Sanjoy Das96709c42015-09-25 23:53:45 +00008316 LDiff != RDiff)
8317 return false;
8318
8319 if (LDiff == 0)
8320 return true;
8321
Sanjoy Das96709c42015-09-25 23:53:45 +00008322 APInt FoundRHSLimit;
8323
8324 if (Pred == CmpInst::ICMP_ULT) {
8325 FoundRHSLimit = -RDiff;
8326 } else {
8327 assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
Sanjoy Das4f1c4592015-09-28 21:14:32 +00008328 FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - RDiff;
Sanjoy Das96709c42015-09-25 23:53:45 +00008329 }
8330
8331 // Try to prove (1) or (2), as needed.
8332 return isLoopEntryGuardedByCond(L, Pred, FoundRHS,
8333 getConstant(FoundRHSLimit));
8334}
8335
Dan Gohman430f0cc2009-07-21 23:03:19 +00008336/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00008337/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008338/// and FoundRHS is true.
8339bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
8340 const SCEV *LHS, const SCEV *RHS,
8341 const SCEV *FoundLHS,
8342 const SCEV *FoundRHS) {
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008343 if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
8344 return true;
8345
Sanjoy Das96709c42015-09-25 23:53:45 +00008346 if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
8347 return true;
8348
Dan Gohman430f0cc2009-07-21 23:03:19 +00008349 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
8350 FoundLHS, FoundRHS) ||
8351 // ~x < ~y --> x > y
8352 isImpliedCondOperandsHelper(Pred, LHS, RHS,
8353 getNotSCEV(FoundRHS),
8354 getNotSCEV(FoundLHS));
8355}
8356
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008357
8358/// If Expr computes ~A, return A else return nullptr
8359static const SCEV *MatchNotExpr(const SCEV *Expr) {
8360 const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008361 if (!Add || Add->getNumOperands() != 2 ||
8362 !Add->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008363 return nullptr;
8364
8365 const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
Sanjoy Das16e7ff12015-10-13 23:28:31 +00008366 if (!AddRHS || AddRHS->getNumOperands() != 2 ||
8367 !AddRHS->getOperand(0)->isAllOnesValue())
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008368 return nullptr;
8369
8370 return AddRHS->getOperand(1);
8371}
8372
8373
8374/// Is MaybeMaxExpr an SMax or UMax of Candidate and some other values?
8375template<typename MaxExprType>
8376static bool IsMaxConsistingOf(const SCEV *MaybeMaxExpr,
8377 const SCEV *Candidate) {
8378 const MaxExprType *MaxExpr = dyn_cast<MaxExprType>(MaybeMaxExpr);
8379 if (!MaxExpr) return false;
8380
Sanjoy Das347d2722015-12-01 07:49:27 +00008381 return find(MaxExpr->operands(), Candidate) != MaxExpr->op_end();
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008382}
8383
8384
8385/// Is MaybeMinExpr an SMin or UMin of Candidate and some other values?
8386template<typename MaxExprType>
8387static bool IsMinConsistingOf(ScalarEvolution &SE,
8388 const SCEV *MaybeMinExpr,
8389 const SCEV *Candidate) {
8390 const SCEV *MaybeMaxExpr = MatchNotExpr(MaybeMinExpr);
8391 if (!MaybeMaxExpr)
8392 return false;
8393
8394 return IsMaxConsistingOf<MaxExprType>(MaybeMaxExpr, SE.getNotSCEV(Candidate));
8395}
8396
Hal Finkela8d205f2015-08-19 01:51:51 +00008397static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
8398 ICmpInst::Predicate Pred,
8399 const SCEV *LHS, const SCEV *RHS) {
8400
8401 // If both sides are affine addrecs for the same loop, with equal
8402 // steps, and we know the recurrences don't wrap, then we only
8403 // need to check the predicate on the starting values.
8404
8405 if (!ICmpInst::isRelational(Pred))
8406 return false;
8407
8408 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
8409 if (!LAR)
8410 return false;
8411 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
8412 if (!RAR)
8413 return false;
8414 if (LAR->getLoop() != RAR->getLoop())
8415 return false;
8416 if (!LAR->isAffine() || !RAR->isAffine())
8417 return false;
8418
8419 if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
8420 return false;
8421
Hal Finkelff08a2e2015-08-19 17:26:07 +00008422 SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
8423 SCEV::FlagNSW : SCEV::FlagNUW;
8424 if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
Hal Finkela8d205f2015-08-19 01:51:51 +00008425 return false;
8426
8427 return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
8428}
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008429
8430/// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
8431/// expression?
8432static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
8433 ICmpInst::Predicate Pred,
8434 const SCEV *LHS, const SCEV *RHS) {
8435 switch (Pred) {
8436 default:
8437 return false;
8438
8439 case ICmpInst::ICMP_SGE:
8440 std::swap(LHS, RHS);
8441 // fall through
8442 case ICmpInst::ICMP_SLE:
8443 return
8444 // min(A, ...) <= A
8445 IsMinConsistingOf<SCEVSMaxExpr>(SE, LHS, RHS) ||
8446 // A <= max(A, ...)
8447 IsMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
8448
8449 case ICmpInst::ICMP_UGE:
8450 std::swap(LHS, RHS);
8451 // fall through
8452 case ICmpInst::ICMP_ULE:
8453 return
8454 // min(A, ...) <= A
8455 IsMinConsistingOf<SCEVUMaxExpr>(SE, LHS, RHS) ||
8456 // A <= max(A, ...)
8457 IsMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
8458 }
8459
8460 llvm_unreachable("covered switch fell through?!");
8461}
8462
Dan Gohman430f0cc2009-07-21 23:03:19 +00008463/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00008464/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00008465/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00008466bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00008467ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
8468 const SCEV *LHS, const SCEV *RHS,
8469 const SCEV *FoundLHS,
8470 const SCEV *FoundRHS) {
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008471 auto IsKnownPredicateFull =
8472 [this](ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
Sanjoy Das401e6312016-02-01 20:48:10 +00008473 return isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
Sanjoy Das11231482015-10-22 19:57:29 +00008474 IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
Sanjoy Dasc1a29772015-11-05 23:45:38 +00008475 IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
8476 isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008477 };
8478
Dan Gohmane65c9172009-07-13 21:35:55 +00008479 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00008480 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
8481 case ICmpInst::ICMP_EQ:
8482 case ICmpInst::ICMP_NE:
8483 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
8484 return true;
8485 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00008486 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008487 case ICmpInst::ICMP_SLE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008488 if (IsKnownPredicateFull(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
8489 IsKnownPredicateFull(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008490 return true;
8491 break;
8492 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008493 case ICmpInst::ICMP_SGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008494 if (IsKnownPredicateFull(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
8495 IsKnownPredicateFull(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008496 return true;
8497 break;
8498 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008499 case ICmpInst::ICMP_ULE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008500 if (IsKnownPredicateFull(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
8501 IsKnownPredicateFull(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008502 return true;
8503 break;
8504 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00008505 case ICmpInst::ICMP_UGE:
Sanjoy Das4555b6d2014-12-15 22:50:15 +00008506 if (IsKnownPredicateFull(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
8507 IsKnownPredicateFull(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00008508 return true;
8509 break;
8510 }
8511
8512 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00008513}
8514
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008515/// isImpliedCondOperandsViaRanges - helper function for isImpliedCondOperands.
8516/// Tries to get cases like "X `sgt` 0 => X - 1 `sgt` -1".
8517bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
8518 const SCEV *LHS,
8519 const SCEV *RHS,
8520 const SCEV *FoundLHS,
8521 const SCEV *FoundRHS) {
8522 if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
8523 // The restriction on `FoundRHS` be lifted easily -- it exists only to
8524 // reduce the compile time impact of this optimization.
8525 return false;
8526
8527 const SCEVAddExpr *AddLHS = dyn_cast<SCEVAddExpr>(LHS);
8528 if (!AddLHS || AddLHS->getOperand(1) != FoundLHS ||
8529 !isa<SCEVConstant>(AddLHS->getOperand(0)))
8530 return false;
8531
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008532 APInt ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008533
8534 // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
8535 // antecedent "`FoundLHS` `Pred` `FoundRHS`".
8536 ConstantRange FoundLHSRange =
8537 ConstantRange::makeAllowedICmpRegion(Pred, ConstFoundRHS);
8538
8539 // Since `LHS` is `FoundLHS` + `AddLHS->getOperand(0)`, we can compute a range
8540 // for `LHS`:
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008541 APInt Addend = cast<SCEVConstant>(AddLHS->getOperand(0))->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008542 ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(Addend));
8543
8544 // We can also compute the range of values for `LHS` that satisfy the
8545 // consequent, "`LHS` `Pred` `RHS`":
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008546 APInt ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
Sanjoy Dascb8bca12015-03-18 00:41:29 +00008547 ConstantRange SatisfyingLHSRange =
8548 ConstantRange::makeSatisfyingICmpRegion(Pred, ConstRHS);
8549
8550 // The antecedent implies the consequent if every value of `LHS` that
8551 // satisfies the antecedent also satisfies the consequent.
8552 return SatisfyingLHSRange.contains(LHSRange);
8553}
8554
Johannes Doerfert2683e562015-02-09 12:34:23 +00008555// Verify if an linear IV with positive stride can overflow when in a
8556// less-than comparison, knowing the invariant term of the comparison, the
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008557// stride and the knowledge of NSW/NUW flags on the recurrence.
8558bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
8559 bool IsSigned, bool NoWrap) {
8560 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00008561
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008562 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008563 const SCEV *One = getOne(Stride->getType());
Andrew Trick2afa3252011-03-09 17:29:58 +00008564
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008565 if (IsSigned) {
8566 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
8567 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
8568 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8569 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00008570
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008571 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
8572 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00008573 }
Dan Gohman01048422009-06-21 23:46:38 +00008574
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008575 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
8576 APInt MaxValue = APInt::getMaxValue(BitWidth);
8577 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8578 .getUnsignedMax();
8579
8580 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
8581 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
8582}
8583
Johannes Doerfert2683e562015-02-09 12:34:23 +00008584// Verify if an linear IV with negative stride can overflow when in a
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008585// greater-than comparison, knowing the invariant term of the comparison,
8586// the stride and the knowledge of NSW/NUW flags on the recurrence.
8587bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
8588 bool IsSigned, bool NoWrap) {
8589 if (NoWrap) return false;
8590
8591 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008592 const SCEV *One = getOne(Stride->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008593
8594 if (IsSigned) {
8595 APInt MinRHS = getSignedRange(RHS).getSignedMin();
8596 APInt MinValue = APInt::getSignedMinValue(BitWidth);
8597 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
8598 .getSignedMax();
8599
8600 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
8601 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
8602 }
8603
8604 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
8605 APInt MinValue = APInt::getMinValue(BitWidth);
8606 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
8607 .getUnsignedMax();
8608
8609 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
8610 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
8611}
8612
8613// Compute the backedge taken count knowing the interval difference, the
8614// stride and presence of the equality in the comparison.
Johannes Doerfert2683e562015-02-09 12:34:23 +00008615const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008616 bool Equality) {
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008617 const SCEV *One = getOne(Step->getType());
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008618 Delta = Equality ? getAddExpr(Delta, Step)
8619 : getAddExpr(Delta, getMinusSCEV(Step, One));
8620 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00008621}
8622
Chris Lattner587a75b2005-08-15 23:33:51 +00008623/// HowManyLessThans - Return the number of times a backedge containing the
8624/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00008625/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00008626///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008627/// @param ControlsExit is true when the LHS < RHS condition directly controls
8628/// the branch (loops exits only if condition is true). In this case, we can use
8629/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00008630ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00008631ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008632 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008633 bool ControlsExit, bool AllowPredicates) {
8634 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008635 // We handle only IV < Invariant
8636 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00008637 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008638
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008639 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008640 if (!IV && AllowPredicates)
8641 // Try to make this an AddRec using runtime tests, in the first X
8642 // iterations of this loop, where X is the SCEV expression found by the
8643 // algorithm below.
8644 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Dan Gohman2b8da352009-04-30 20:47:05 +00008645
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008646 // Avoid weird loops
8647 if (!IV || IV->getLoop() != L || !IV->isAffine())
8648 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00008649
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008650 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008651 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008652
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008653 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00008654
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008655 // Avoid negative or zero stride values
8656 if (!isKnownPositive(Stride))
8657 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008658
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008659 // Avoid proven overflow cases: this will ensure that the backedge taken count
8660 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008661 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008662 // behaviors like the case of C language.
8663 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
8664 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00008665
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008666 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
8667 : ICmpInst::ICMP_ULT;
8668 const SCEV *Start = IV->getStart();
8669 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008670 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS)) {
8671 const SCEV *Diff = getMinusSCEV(RHS, Start);
8672 // If we have NoWrap set, then we can assume that the increment won't
8673 // overflow, in which case if RHS - Start is a constant, we don't need to
8674 // do a max operation since we can just figure it out statically
8675 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008676 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008677 if (D.isNegative())
8678 End = Start;
8679 } else
8680 End = IsSigned ? getSMaxExpr(RHS, Start)
8681 : getUMaxExpr(RHS, Start);
8682 }
Dan Gohman51aaf022010-01-26 04:40:18 +00008683
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008684 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00008685
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008686 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
8687 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00008688
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008689 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8690 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00008691
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008692 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8693 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
8694 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00008695
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008696 // Although End can be a MAX expression we estimate MaxEnd considering only
8697 // the case End = RHS. This is safe because in the other case (End - Start)
8698 // is zero, leading to a zero maximum backedge taken count.
8699 APInt MaxEnd =
8700 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
8701 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
8702
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00008703 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008704 if (isa<SCEVConstant>(BECount))
8705 MaxBECount = BECount;
8706 else
8707 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
8708 getConstant(MinStride), false);
8709
8710 if (isa<SCEVCouldNotCompute>(MaxBECount))
8711 MaxBECount = BECount;
8712
Silviu Baranga6f444df2016-04-08 14:29:09 +00008713 return ExitLimit(BECount, MaxBECount, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008714}
8715
8716ScalarEvolution::ExitLimit
8717ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
8718 const Loop *L, bool IsSigned,
Silviu Baranga6f444df2016-04-08 14:29:09 +00008719 bool ControlsExit, bool AllowPredicates) {
8720 SCEVUnionPredicate P;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008721 // We handle only IV > Invariant
8722 if (!isLoopInvariant(RHS, L))
8723 return getCouldNotCompute();
8724
8725 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Silviu Baranga6f444df2016-04-08 14:29:09 +00008726 if (!IV && AllowPredicates)
8727 // Try to make this an AddRec using runtime tests, in the first X
8728 // iterations of this loop, where X is the SCEV expression found by the
8729 // algorithm below.
8730 IV = convertSCEVToAddRecWithPredicates(LHS, L, P);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008731
8732 // Avoid weird loops
8733 if (!IV || IV->getLoop() != L || !IV->isAffine())
8734 return getCouldNotCompute();
8735
Mark Heffernan2beab5f2014-10-10 17:39:11 +00008736 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008737 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
8738
8739 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
8740
8741 // Avoid negative or zero stride values
8742 if (!isKnownPositive(Stride))
8743 return getCouldNotCompute();
8744
8745 // Avoid proven overflow cases: this will ensure that the backedge taken count
8746 // will not generate any unsigned overflow. Relaxed no-overflow conditions
Johannes Doerfert2683e562015-02-09 12:34:23 +00008747 // exploit NoWrapFlags, allowing to optimize in presence of undefined
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008748 // behaviors like the case of C language.
8749 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
8750 return getCouldNotCompute();
8751
8752 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
8753 : ICmpInst::ICMP_UGT;
8754
8755 const SCEV *Start = IV->getStart();
8756 const SCEV *End = RHS;
Bradley Smith9992b162014-10-31 11:40:32 +00008757 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
8758 const SCEV *Diff = getMinusSCEV(RHS, Start);
8759 // If we have NoWrap set, then we can assume that the increment won't
8760 // overflow, in which case if RHS - Start is a constant, we don't need to
8761 // do a max operation since we can just figure it out statically
8762 if (NoWrap && isa<SCEVConstant>(Diff)) {
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008763 APInt D = dyn_cast<const SCEVConstant>(Diff)->getAPInt();
Bradley Smith9992b162014-10-31 11:40:32 +00008764 if (!D.isNegative())
8765 End = Start;
8766 } else
8767 End = IsSigned ? getSMinExpr(RHS, Start)
8768 : getUMinExpr(RHS, Start);
8769 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008770
8771 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
8772
8773 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
8774 : getUnsignedRange(Start).getUnsignedMax();
8775
8776 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
8777 : getUnsignedRange(Stride).getUnsignedMin();
8778
8779 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
8780 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
8781 : APInt::getMinValue(BitWidth) + (MinStride - 1);
8782
8783 // Although End can be a MIN expression we estimate MinEnd considering only
8784 // the case End = RHS. This is safe because in the other case (Start - End)
8785 // is zero, leading to a zero maximum backedge taken count.
8786 APInt MinEnd =
8787 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
8788 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
8789
8790
8791 const SCEV *MaxBECount = getCouldNotCompute();
8792 if (isa<SCEVConstant>(BECount))
8793 MaxBECount = BECount;
8794 else
Johannes Doerfert2683e562015-02-09 12:34:23 +00008795 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
Andrew Trick34e2f0c2013-11-06 02:08:26 +00008796 getConstant(MinStride), false);
8797
8798 if (isa<SCEVCouldNotCompute>(MaxBECount))
8799 MaxBECount = BECount;
8800
Silviu Baranga6f444df2016-04-08 14:29:09 +00008801 return ExitLimit(BECount, MaxBECount, P);
Chris Lattner587a75b2005-08-15 23:33:51 +00008802}
8803
Chris Lattnerd934c702004-04-02 20:23:17 +00008804/// getNumIterationsInRange - Return the number of iterations of this loop that
8805/// produce values in the specified constant range. Another way of looking at
8806/// this is that it returns the first iteration number where the value is not in
8807/// the condition, thus computing the exit count. If the iteration count can't
8808/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00008809const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00008810 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00008811 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00008812 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008813
8814 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00008815 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00008816 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00008817 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008818 Operands[0] = SE.getZero(SC->getType());
Andrew Trick8b55b732011-03-14 16:50:06 +00008819 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00008820 getNoWrapFlags(FlagNW));
Sanjoy Das63914592015-10-18 00:29:20 +00008821 if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00008822 return ShiftedAddRec->getNumIterationsInRange(
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008823 Range.subtract(SC->getAPInt()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00008824 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00008825 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008826 }
8827
8828 // The only time we can solve this is when we have all constant indices.
8829 // Otherwise, we cannot determine the overflow conditions.
Sanjoy Dasff3b8b42015-12-01 07:49:23 +00008830 if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
Sanjoy Dasf07d2a72015-10-18 00:29:23 +00008831 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008832
8833 // Okay at this point we know that all elements of the chrec are constants and
8834 // that the start element is zero.
8835
8836 // First check to see if the range contains zero. If not, the first
8837 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00008838 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00008839 if (!Range.contains(APInt(BitWidth, 0)))
Sanjoy Das2aacc0e2015-09-23 01:59:04 +00008840 return SE.getZero(getType());
Misha Brukman01808ca2005-04-21 21:13:18 +00008841
Chris Lattnerd934c702004-04-02 20:23:17 +00008842 if (isAffine()) {
8843 // If this is an affine expression then we have this situation:
8844 // Solve {0,+,A} in Range === Ax in Range
8845
Nick Lewycky52460262007-07-16 02:08:00 +00008846 // We know that zero is in the range. If A is positive then we know that
8847 // the upper value of the range must be the first possible exit value.
8848 // If A is negative then the lower of the range is the last possible loop
8849 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00008850 APInt One(BitWidth,1);
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008851 APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
Nick Lewycky52460262007-07-16 02:08:00 +00008852 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00008853
Nick Lewycky52460262007-07-16 02:08:00 +00008854 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00008855 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00008856 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00008857
8858 // Evaluate at the exit value. If we really did fall out of the valid
8859 // range, then we computed our trip count, otherwise wrap around or other
8860 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00008861 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008862 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00008863 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008864
8865 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00008866 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00008867 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00008868 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00008869 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00008870 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00008871 } else if (isQuadratic()) {
8872 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
8873 // quadratic equation to solve it. To do this, we must frame our problem in
8874 // terms of figuring out when zero is crossed, instead of when
8875 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00008876 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00008877 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00008878 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
8879 // getNoWrapFlags(FlagNW)
8880 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00008881
8882 // Next, solve the constructed addrec
Sanjoy Das01947432015-11-22 21:20:13 +00008883 auto Roots = SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00008884 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
8885 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00008886 if (R1) {
8887 // Pick the smallest positive root value.
Sanjoy Das01947432015-11-22 21:20:13 +00008888 if (ConstantInt *CB = dyn_cast<ConstantInt>(ConstantExpr::getICmp(
8889 ICmpInst::ICMP_ULT, R1->getValue(), R2->getValue()))) {
David Blaikiedc3f01e2015-03-09 01:57:13 +00008890 if (!CB->getZExtValue())
Chris Lattnerd934c702004-04-02 20:23:17 +00008891 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00008892
Chris Lattnerd934c702004-04-02 20:23:17 +00008893 // Make sure the root is not off by one. The returned iteration should
8894 // not be in the range, but the previous one should be. When solving
8895 // for "X*X < 5", for example, we should not return a root of 2.
8896 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00008897 R1->getValue(),
8898 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008899 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00008900 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00008901 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008902 ConstantInt::get(SE.getContext(), R1->getAPInt() + 1);
Misha Brukman01808ca2005-04-21 21:13:18 +00008903
Dan Gohmana37eaf22007-10-22 18:31:58 +00008904 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008905 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00008906 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00008907 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008908 }
Misha Brukman01808ca2005-04-21 21:13:18 +00008909
Chris Lattnerd934c702004-04-02 20:23:17 +00008910 // If R1 was not in the range, then it is a good return value. Make
8911 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00008912 ConstantInt *NextVal =
Sanjoy Das0de2fec2015-12-17 20:28:46 +00008913 ConstantInt::get(SE.getContext(), R1->getAPInt() - 1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00008914 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00008915 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00008916 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00008917 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00008918 }
8919 }
8920 }
8921
Dan Gohman31efa302009-04-18 17:58:19 +00008922 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00008923}
8924
Sebastian Pop448712b2014-05-07 18:01:20 +00008925namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008926struct FindUndefs {
8927 bool Found;
8928 FindUndefs() : Found(false) {}
8929
8930 bool follow(const SCEV *S) {
8931 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
8932 if (isa<UndefValue>(C->getValue()))
8933 Found = true;
8934 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
8935 if (isa<UndefValue>(C->getValue()))
8936 Found = true;
8937 }
8938
8939 // Keep looking if we haven't found it yet.
8940 return !Found;
8941 }
8942 bool isDone() const {
8943 // Stop recursion if we have found an undef.
8944 return Found;
8945 }
8946};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00008947}
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008948
8949// Return true when S contains at least an undef value.
8950static inline bool
8951containsUndefs(const SCEV *S) {
8952 FindUndefs F;
8953 SCEVTraversal<FindUndefs> ST(F);
8954 ST.visitAll(S);
8955
8956 return F.Found;
8957}
8958
8959namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00008960// Collect all steps of SCEV expressions.
8961struct SCEVCollectStrides {
8962 ScalarEvolution &SE;
8963 SmallVectorImpl<const SCEV *> &Strides;
8964
8965 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
8966 : SE(SE), Strides(S) {}
8967
8968 bool follow(const SCEV *S) {
8969 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
8970 Strides.push_back(AR->getStepRecurrence(SE));
8971 return true;
8972 }
8973 bool isDone() const { return false; }
8974};
8975
8976// Collect all SCEVUnknown and SCEVMulExpr expressions.
8977struct SCEVCollectTerms {
8978 SmallVectorImpl<const SCEV *> &Terms;
8979
8980 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
8981 : Terms(T) {}
8982
8983 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00008984 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00008985 if (!containsUndefs(S))
8986 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00008987
8988 // Stop recursion: once we collected a term, do not walk its operands.
8989 return false;
8990 }
8991
8992 // Keep looking.
8993 return true;
8994 }
8995 bool isDone() const { return false; }
8996};
Tobias Grosser374bce02015-10-12 08:02:00 +00008997
8998// Check if a SCEV contains an AddRecExpr.
8999struct SCEVHasAddRec {
9000 bool &ContainsAddRec;
9001
9002 SCEVHasAddRec(bool &ContainsAddRec) : ContainsAddRec(ContainsAddRec) {
9003 ContainsAddRec = false;
9004 }
9005
9006 bool follow(const SCEV *S) {
9007 if (isa<SCEVAddRecExpr>(S)) {
9008 ContainsAddRec = true;
9009
9010 // Stop recursion: once we collected a term, do not walk its operands.
9011 return false;
9012 }
9013
9014 // Keep looking.
9015 return true;
9016 }
9017 bool isDone() const { return false; }
9018};
9019
9020// Find factors that are multiplied with an expression that (possibly as a
9021// subexpression) contains an AddRecExpr. In the expression:
9022//
9023// 8 * (100 + %p * %q * (%a + {0, +, 1}_loop))
9024//
9025// "%p * %q" are factors multiplied by the expression "(%a + {0, +, 1}_loop)"
9026// that contains the AddRec {0, +, 1}_loop. %p * %q are likely to be array size
9027// parameters as they form a product with an induction variable.
9028//
9029// This collector expects all array size parameters to be in the same MulExpr.
9030// It might be necessary to later add support for collecting parameters that are
9031// spread over different nested MulExpr.
9032struct SCEVCollectAddRecMultiplies {
9033 SmallVectorImpl<const SCEV *> &Terms;
9034 ScalarEvolution &SE;
9035
9036 SCEVCollectAddRecMultiplies(SmallVectorImpl<const SCEV *> &T, ScalarEvolution &SE)
9037 : Terms(T), SE(SE) {}
9038
9039 bool follow(const SCEV *S) {
9040 if (auto *Mul = dyn_cast<SCEVMulExpr>(S)) {
9041 bool HasAddRec = false;
9042 SmallVector<const SCEV *, 0> Operands;
9043 for (auto Op : Mul->operands()) {
9044 if (isa<SCEVUnknown>(Op)) {
9045 Operands.push_back(Op);
9046 } else {
9047 bool ContainsAddRec;
9048 SCEVHasAddRec ContiansAddRec(ContainsAddRec);
9049 visitAll(Op, ContiansAddRec);
9050 HasAddRec |= ContainsAddRec;
9051 }
9052 }
9053 if (Operands.size() == 0)
9054 return true;
9055
9056 if (!HasAddRec)
9057 return false;
9058
9059 Terms.push_back(SE.getMulExpr(Operands));
9060 // Stop recursion: once we collected a term, do not walk its operands.
9061 return false;
9062 }
9063
9064 // Keep looking.
9065 return true;
9066 }
9067 bool isDone() const { return false; }
9068};
Alexander Kornienkof00654e2015-06-23 09:49:53 +00009069}
Sebastian Pop448712b2014-05-07 18:01:20 +00009070
Tobias Grosser374bce02015-10-12 08:02:00 +00009071/// Find parametric terms in this SCEVAddRecExpr. We first for parameters in
9072/// two places:
9073/// 1) The strides of AddRec expressions.
9074/// 2) Unknowns that are multiplied with AddRec expressions.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009075void ScalarEvolution::collectParametricTerms(const SCEV *Expr,
9076 SmallVectorImpl<const SCEV *> &Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009077 SmallVector<const SCEV *, 4> Strides;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009078 SCEVCollectStrides StrideCollector(*this, Strides);
9079 visitAll(Expr, StrideCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009080
9081 DEBUG({
9082 dbgs() << "Strides:\n";
9083 for (const SCEV *S : Strides)
9084 dbgs() << *S << "\n";
9085 });
9086
9087 for (const SCEV *S : Strides) {
9088 SCEVCollectTerms TermCollector(Terms);
9089 visitAll(S, TermCollector);
9090 }
9091
9092 DEBUG({
9093 dbgs() << "Terms:\n";
9094 for (const SCEV *T : Terms)
9095 dbgs() << *T << "\n";
9096 });
Tobias Grosser374bce02015-10-12 08:02:00 +00009097
9098 SCEVCollectAddRecMultiplies MulCollector(Terms, *this);
9099 visitAll(Expr, MulCollector);
Sebastian Pop448712b2014-05-07 18:01:20 +00009100}
9101
Sebastian Popb1a548f2014-05-12 19:01:53 +00009102static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00009103 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00009104 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00009105 int Last = Terms.size() - 1;
9106 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00009107
Sebastian Pop448712b2014-05-07 18:01:20 +00009108 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00009109 if (Last == 0) {
9110 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009111 SmallVector<const SCEV *, 2> Qs;
9112 for (const SCEV *Op : M->operands())
9113 if (!isa<SCEVConstant>(Op))
9114 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00009115
Sebastian Pope30bd352014-05-27 22:41:56 +00009116 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00009117 }
9118
Sebastian Pope30bd352014-05-27 22:41:56 +00009119 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009120 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00009121 }
9122
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009123 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009124 // Normalize the terms before the next call to findArrayDimensionsRec.
9125 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009126 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009127
9128 // Bail out when GCD does not evenly divide one of the terms.
9129 if (!R->isZero())
9130 return false;
9131
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00009132 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00009133 }
9134
Tobias Grosser3080cf12014-05-08 07:55:34 +00009135 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00009136 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
9137 return isa<SCEVConstant>(E);
9138 }),
9139 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00009140
Sebastian Pop448712b2014-05-07 18:01:20 +00009141 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00009142 if (!findArrayDimensionsRec(SE, Terms, Sizes))
9143 return false;
9144
Sebastian Pope30bd352014-05-27 22:41:56 +00009145 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00009146 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00009147}
Sebastian Popc62c6792013-11-12 22:47:20 +00009148
Sebastian Pop448712b2014-05-07 18:01:20 +00009149// Returns true when S contains at least a SCEVUnknown parameter.
9150static inline bool
9151containsParameters(const SCEV *S) {
Sanjoy Das7d752672015-12-08 04:32:54 +00009152 struct FindParameter {
9153 bool FoundParameter;
9154 FindParameter() : FoundParameter(false) {}
9155
9156 bool follow(const SCEV *S) {
9157 if (isa<SCEVUnknown>(S)) {
9158 FoundParameter = true;
9159 // Stop recursion: we found a parameter.
9160 return false;
9161 }
9162 // Keep looking.
9163 return true;
9164 }
9165 bool isDone() const {
9166 // Stop recursion if we have found a parameter.
9167 return FoundParameter;
9168 }
9169 };
9170
Sebastian Pop448712b2014-05-07 18:01:20 +00009171 FindParameter F;
9172 SCEVTraversal<FindParameter> ST(F);
9173 ST.visitAll(S);
9174
9175 return F.FoundParameter;
9176}
9177
9178// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
9179static inline bool
9180containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
9181 for (const SCEV *T : Terms)
9182 if (containsParameters(T))
9183 return true;
9184 return false;
9185}
9186
9187// Return the number of product terms in S.
9188static inline int numberOfTerms(const SCEV *S) {
9189 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
9190 return Expr->getNumOperands();
9191 return 1;
9192}
9193
Sebastian Popa6e58602014-05-27 22:41:45 +00009194static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
9195 if (isa<SCEVConstant>(T))
9196 return nullptr;
9197
9198 if (isa<SCEVUnknown>(T))
9199 return T;
9200
9201 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
9202 SmallVector<const SCEV *, 2> Factors;
9203 for (const SCEV *Op : M->operands())
9204 if (!isa<SCEVConstant>(Op))
9205 Factors.push_back(Op);
9206
9207 return SE.getMulExpr(Factors);
9208 }
9209
9210 return T;
9211}
9212
9213/// Return the size of an element read or written by Inst.
9214const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
9215 Type *Ty;
9216 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
9217 Ty = Store->getValueOperand()->getType();
9218 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00009219 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00009220 else
9221 return nullptr;
9222
9223 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
9224 return getSizeOfExpr(ETy, Ty);
9225}
9226
Sebastian Pop448712b2014-05-07 18:01:20 +00009227/// Second step of delinearization: compute the array dimensions Sizes from the
9228/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00009229void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
9230 SmallVectorImpl<const SCEV *> &Sizes,
9231 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00009232
Sebastian Pop53524082014-05-29 19:44:05 +00009233 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00009234 return;
9235
9236 // Early return when Terms do not contain parameters: we do not delinearize
9237 // non parametric SCEVs.
9238 if (!containsParameters(Terms))
9239 return;
9240
9241 DEBUG({
9242 dbgs() << "Terms:\n";
9243 for (const SCEV *T : Terms)
9244 dbgs() << *T << "\n";
9245 });
9246
9247 // Remove duplicates.
9248 std::sort(Terms.begin(), Terms.end());
9249 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
9250
9251 // Put larger terms first.
9252 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
9253 return numberOfTerms(LHS) > numberOfTerms(RHS);
9254 });
9255
Sebastian Popa6e58602014-05-27 22:41:45 +00009256 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9257
Tobias Grosser374bce02015-10-12 08:02:00 +00009258 // Try to divide all terms by the element size. If term is not divisible by
9259 // element size, proceed with the original term.
Sebastian Popa6e58602014-05-27 22:41:45 +00009260 for (const SCEV *&Term : Terms) {
9261 const SCEV *Q, *R;
David Majnemer4e879362014-12-14 09:12:33 +00009262 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
Tobias Grosser374bce02015-10-12 08:02:00 +00009263 if (!Q->isZero())
9264 Term = Q;
Sebastian Popa6e58602014-05-27 22:41:45 +00009265 }
9266
9267 SmallVector<const SCEV *, 4> NewTerms;
9268
9269 // Remove constant factors.
9270 for (const SCEV *T : Terms)
9271 if (const SCEV *NewT = removeConstantFactors(SE, T))
9272 NewTerms.push_back(NewT);
9273
Sebastian Pop448712b2014-05-07 18:01:20 +00009274 DEBUG({
9275 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00009276 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00009277 dbgs() << *T << "\n";
9278 });
9279
Sebastian Popa6e58602014-05-27 22:41:45 +00009280 if (NewTerms.empty() ||
9281 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00009282 Sizes.clear();
9283 return;
9284 }
Sebastian Pop448712b2014-05-07 18:01:20 +00009285
Sebastian Popa6e58602014-05-27 22:41:45 +00009286 // The last element to be pushed into Sizes is the size of an element.
9287 Sizes.push_back(ElementSize);
9288
Sebastian Pop448712b2014-05-07 18:01:20 +00009289 DEBUG({
9290 dbgs() << "Sizes:\n";
9291 for (const SCEV *S : Sizes)
9292 dbgs() << *S << "\n";
9293 });
9294}
9295
9296/// Third step of delinearization: compute the access functions for the
9297/// Subscripts based on the dimensions in Sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009298void ScalarEvolution::computeAccessFunctions(
9299 const SCEV *Expr, SmallVectorImpl<const SCEV *> &Subscripts,
9300 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009301
Sebastian Popb1a548f2014-05-12 19:01:53 +00009302 // Early exit in case this SCEV is not an affine multivariate function.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009303 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009304 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009305
Sanjoy Das1195dbe2015-10-08 03:45:58 +00009306 if (auto *AR = dyn_cast<SCEVAddRecExpr>(Expr))
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009307 if (!AR->isAffine())
9308 return;
9309
9310 const SCEV *Res = Expr;
Sebastian Pop448712b2014-05-07 18:01:20 +00009311 int Last = Sizes.size() - 1;
9312 for (int i = Last; i >= 0; i--) {
9313 const SCEV *Q, *R;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009314 SCEVDivision::divide(*this, Res, Sizes[i], &Q, &R);
Sebastian Pop448712b2014-05-07 18:01:20 +00009315
9316 DEBUG({
9317 dbgs() << "Res: " << *Res << "\n";
9318 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
9319 dbgs() << "Res divided by Sizes[i]:\n";
9320 dbgs() << "Quotient: " << *Q << "\n";
9321 dbgs() << "Remainder: " << *R << "\n";
9322 });
9323
9324 Res = Q;
9325
Sebastian Popa6e58602014-05-27 22:41:45 +00009326 // Do not record the last subscript corresponding to the size of elements in
9327 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00009328 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00009329
9330 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00009331 if (isa<SCEVAddRecExpr>(R)) {
9332 Subscripts.clear();
9333 Sizes.clear();
9334 return;
9335 }
Sebastian Popa6e58602014-05-27 22:41:45 +00009336
Sebastian Pop448712b2014-05-07 18:01:20 +00009337 continue;
9338 }
9339
9340 // Record the access function for the current subscript.
9341 Subscripts.push_back(R);
9342 }
9343
9344 // Also push in last position the remainder of the last division: it will be
9345 // the access function of the innermost dimension.
9346 Subscripts.push_back(Res);
9347
9348 std::reverse(Subscripts.begin(), Subscripts.end());
9349
9350 DEBUG({
9351 dbgs() << "Subscripts:\n";
9352 for (const SCEV *S : Subscripts)
9353 dbgs() << *S << "\n";
9354 });
Sebastian Pop448712b2014-05-07 18:01:20 +00009355}
9356
Sebastian Popc62c6792013-11-12 22:47:20 +00009357/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
9358/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00009359/// is the offset start of the array. The SCEV->delinearize algorithm computes
9360/// the multiples of SCEV coefficients: that is a pattern matching of sub
9361/// expressions in the stride and base of a SCEV corresponding to the
9362/// computation of a GCD (greatest common divisor) of base and stride. When
9363/// SCEV->delinearize fails, it returns the SCEV unchanged.
9364///
9365/// For example: when analyzing the memory access A[i][j][k] in this loop nest
9366///
9367/// void foo(long n, long m, long o, double A[n][m][o]) {
9368///
9369/// for (long i = 0; i < n; i++)
9370/// for (long j = 0; j < m; j++)
9371/// for (long k = 0; k < o; k++)
9372/// A[i][j][k] = 1.0;
9373/// }
9374///
9375/// the delinearization input is the following AddRec SCEV:
9376///
9377/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
9378///
9379/// From this SCEV, we are able to say that the base offset of the access is %A
9380/// because it appears as an offset that does not divide any of the strides in
9381/// the loops:
9382///
9383/// CHECK: Base offset: %A
9384///
9385/// and then SCEV->delinearize determines the size of some of the dimensions of
9386/// the array as these are the multiples by which the strides are happening:
9387///
9388/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
9389///
9390/// Note that the outermost dimension remains of UnknownSize because there are
9391/// no strides that would help identifying the size of the last dimension: when
9392/// the array has been statically allocated, one could compute the size of that
9393/// dimension by dividing the overall size of the array by the size of the known
9394/// dimensions: %m * %o * 8.
9395///
9396/// Finally delinearize provides the access functions for the array reference
9397/// that does correspond to A[i][j][k] of the above C testcase:
9398///
9399/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
9400///
9401/// The testcases are checking the output of a function pass:
9402/// DelinearizationPass that walks through all loads and stores of a function
9403/// asking for the SCEV of the memory access with respect to all enclosing
9404/// loops, calling SCEV->delinearize on that and printing the results.
9405
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009406void ScalarEvolution::delinearize(const SCEV *Expr,
Sebastian Pop28e6b972014-05-27 22:41:51 +00009407 SmallVectorImpl<const SCEV *> &Subscripts,
9408 SmallVectorImpl<const SCEV *> &Sizes,
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009409 const SCEV *ElementSize) {
Sebastian Pop448712b2014-05-07 18:01:20 +00009410 // First step: collect parametric terms.
9411 SmallVector<const SCEV *, 4> Terms;
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009412 collectParametricTerms(Expr, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00009413
Sebastian Popb1a548f2014-05-12 19:01:53 +00009414 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009415 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009416
Sebastian Pop448712b2014-05-07 18:01:20 +00009417 // Second step: find subscript sizes.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009418 findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00009419
Sebastian Popb1a548f2014-05-12 19:01:53 +00009420 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00009421 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009422
Sebastian Pop448712b2014-05-07 18:01:20 +00009423 // Third step: compute the access functions for each subscript.
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009424 computeAccessFunctions(Expr, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00009425
Sebastian Pop28e6b972014-05-27 22:41:51 +00009426 if (Subscripts.empty())
9427 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00009428
Sebastian Pop448712b2014-05-07 18:01:20 +00009429 DEBUG({
Tobias Grosser3cdc37c2015-06-29 14:42:48 +00009430 dbgs() << "succeeded to delinearize " << *Expr << "\n";
Sebastian Pop448712b2014-05-07 18:01:20 +00009431 dbgs() << "ArrayDecl[UnknownSize]";
9432 for (const SCEV *S : Sizes)
9433 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00009434
Sebastian Pop444621a2014-05-09 22:45:02 +00009435 dbgs() << "\nArrayRef";
9436 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00009437 dbgs() << "[" << *S << "]";
9438 dbgs() << "\n";
9439 });
Sebastian Popc62c6792013-11-12 22:47:20 +00009440}
Chris Lattnerd934c702004-04-02 20:23:17 +00009441
9442//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00009443// SCEVCallbackVH Class Implementation
9444//===----------------------------------------------------------------------===//
9445
Dan Gohmand33a0902009-05-19 19:22:47 +00009446void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00009447 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00009448 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
9449 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009450 SE->eraseValueFromMap(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00009451 // this now dangles!
9452}
9453
Dan Gohman7a066722010-07-28 01:09:07 +00009454void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00009455 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00009456
Dan Gohman48f82222009-05-04 22:30:44 +00009457 // Forget all the expressions associated with users of the old value,
9458 // so that future queries will recompute the expressions using the new
9459 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00009460 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00009461 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00009462 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00009463 while (!Worklist.empty()) {
9464 User *U = Worklist.pop_back_val();
9465 // Deleting the Old value will cause this to dangle. Postpone
9466 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009467 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00009468 continue;
David Blaikie70573dc2014-11-19 07:49:26 +00009469 if (!Visited.insert(U).second)
Dan Gohmanf34f8632009-07-14 14:34:04 +00009470 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00009471 if (PHINode *PN = dyn_cast<PHINode>(U))
9472 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009473 SE->eraseValueFromMap(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00009474 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00009475 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009476 // Delete the Old value.
9477 if (PHINode *PN = dyn_cast<PHINode>(Old))
9478 SE->ConstantEvolutionLoopExitValue.erase(PN);
Wei Mia49559b2016-02-04 01:27:38 +00009479 SE->eraseValueFromMap(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00009480 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00009481}
9482
Dan Gohmand33a0902009-05-19 19:22:47 +00009483ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00009484 : CallbackVH(V), SE(se) {}
9485
9486//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00009487// ScalarEvolution Class Implementation
9488//===----------------------------------------------------------------------===//
9489
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009490ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
9491 AssumptionCache &AC, DominatorTree &DT,
9492 LoopInfo &LI)
9493 : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
9494 CouldNotCompute(new SCEVCouldNotCompute()),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009495 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
9496 ValuesAtScopes(64), LoopDispositions(64), BlockDispositions(64),
9497 FirstUnknown(nullptr) {}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009498
9499ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
9500 : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
9501 CouldNotCompute(std::move(Arg.CouldNotCompute)),
9502 ValueExprMap(std::move(Arg.ValueExprMap)),
Sanjoy Das7d910f22015-10-02 18:50:30 +00009503 WalkingBEDominatingConds(false), ProvingSplitPredicate(false),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009504 BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
Silviu Baranga6f444df2016-04-08 14:29:09 +00009505 PredicatedBackedgeTakenCounts(
9506 std::move(Arg.PredicatedBackedgeTakenCounts)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009507 ConstantEvolutionLoopExitValue(
9508 std::move(Arg.ConstantEvolutionLoopExitValue)),
9509 ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
9510 LoopDispositions(std::move(Arg.LoopDispositions)),
9511 BlockDispositions(std::move(Arg.BlockDispositions)),
9512 UnsignedRanges(std::move(Arg.UnsignedRanges)),
9513 SignedRanges(std::move(Arg.SignedRanges)),
9514 UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
Silviu Barangae3c05342015-11-02 14:41:02 +00009515 UniquePreds(std::move(Arg.UniquePreds)),
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009516 SCEVAllocator(std::move(Arg.SCEVAllocator)),
9517 FirstUnknown(Arg.FirstUnknown) {
9518 Arg.FirstUnknown = nullptr;
Dan Gohmanc8e23622009-04-21 23:15:49 +00009519}
9520
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009521ScalarEvolution::~ScalarEvolution() {
Dan Gohman7cac9572010-08-02 23:49:30 +00009522 // Iterate through all the SCEVUnknown instances and call their
9523 // destructors, so that they release their references to their values.
Naomi Musgravef90c1be2015-09-16 23:46:40 +00009524 for (SCEVUnknown *U = FirstUnknown; U;) {
9525 SCEVUnknown *Tmp = U;
9526 U = U->Next;
9527 Tmp->~SCEVUnknown();
9528 }
Craig Topper9f008862014-04-15 04:59:12 +00009529 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00009530
Wei Mia49559b2016-02-04 01:27:38 +00009531 ExprValueMap.clear();
Dan Gohman9bad2fb2010-08-27 18:55:03 +00009532 ValueExprMap.clear();
Wei Mia49559b2016-02-04 01:27:38 +00009533 HasRecMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009534
9535 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
9536 // that a loop had multiple computable exits.
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009537 for (auto &BTCI : BackedgeTakenCounts)
9538 BTCI.second.clear();
Silviu Baranga6f444df2016-04-08 14:29:09 +00009539 for (auto &BTCI : PredicatedBackedgeTakenCounts)
9540 BTCI.second.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00009541
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00009542 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
Sanjoy Dasb864c1f2015-04-01 18:24:06 +00009543 assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
Sanjoy Das7d910f22015-10-02 18:50:30 +00009544 assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
Dan Gohman0a40ad92009-04-16 03:18:22 +00009545}
9546
Dan Gohmanc8e23622009-04-21 23:15:49 +00009547bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00009548 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00009549}
9550
Dan Gohmanc8e23622009-04-21 23:15:49 +00009551static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00009552 const Loop *L) {
9553 // Print all inner loops first
9554 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
9555 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00009556
Dan Gohmanbc694912010-01-09 18:17:45 +00009557 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009558 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009559 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009560
Dan Gohmancb0efec2009-12-18 01:14:11 +00009561 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00009562 L->getExitBlocks(ExitBlocks);
9563 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00009564 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009565
Dan Gohman0bddac12009-02-24 18:55:53 +00009566 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
9567 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00009568 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00009569 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00009570 }
9571
Dan Gohmanbc694912010-01-09 18:17:45 +00009572 OS << "\n"
9573 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00009574 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009575 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00009576
9577 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
9578 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
9579 } else {
9580 OS << "Unpredictable max backedge-taken count. ";
9581 }
9582
Silviu Baranga6f444df2016-04-08 14:29:09 +00009583 OS << "\n"
9584 "Loop ";
9585 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
9586 OS << ": ";
9587
9588 SCEVUnionPredicate Pred;
9589 auto PBT = SE->getPredicatedBackedgeTakenCount(L, Pred);
9590 if (!isa<SCEVCouldNotCompute>(PBT)) {
9591 OS << "Predicated backedge-taken count is " << *PBT << "\n";
9592 OS << " Predicates:\n";
9593 Pred.print(OS, 4);
9594 } else {
9595 OS << "Unpredictable predicated backedge-taken count. ";
9596 }
Dan Gohman69942932009-06-24 00:33:16 +00009597 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00009598}
9599
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009600void ScalarEvolution::print(raw_ostream &OS) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00009601 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00009602 // out SCEV values of all instructions that are interesting. Doing
9603 // this potentially causes it to create new SCEV objects though,
9604 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00009605 // observable from outside the class though, so casting away the
9606 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00009607 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00009608
Dan Gohmanbc694912010-01-09 18:17:45 +00009609 OS << "Classifying expressions for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009610 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009611 OS << "\n";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009612 for (Instruction &I : instructions(F))
9613 if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
9614 OS << I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00009615 OS << " --> ";
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009616 const SCEV *SV = SE.getSCEV(&I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009617 SV->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009618 if (!isa<SCEVCouldNotCompute>(SV)) {
9619 OS << " U: ";
9620 SE.getUnsignedRange(SV).print(OS);
9621 OS << " S: ";
9622 SE.getSignedRange(SV).print(OS);
9623 }
Misha Brukman01808ca2005-04-21 21:13:18 +00009624
Sanjoy Dasd9f6d332015-10-18 00:29:16 +00009625 const Loop *L = LI.getLoopFor(I.getParent());
Dan Gohmanb9063a82009-06-19 17:49:54 +00009626
Dan Gohmanaf752342009-07-07 17:06:11 +00009627 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00009628 if (AtUse != SV) {
9629 OS << " --> ";
9630 AtUse->print(OS);
Sanjoy Dasf2574522015-03-09 21:43:39 +00009631 if (!isa<SCEVCouldNotCompute>(AtUse)) {
9632 OS << " U: ";
9633 SE.getUnsignedRange(AtUse).print(OS);
9634 OS << " S: ";
9635 SE.getSignedRange(AtUse).print(OS);
9636 }
Dan Gohmanb9063a82009-06-19 17:49:54 +00009637 }
9638
9639 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00009640 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00009641 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00009642 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00009643 OS << "<<Unknown>>";
9644 } else {
9645 OS << *ExitValue;
9646 }
9647 }
9648
Chris Lattnerd934c702004-04-02 20:23:17 +00009649 OS << "\n";
9650 }
9651
Dan Gohmanbc694912010-01-09 18:17:45 +00009652 OS << "Determining loop execution counts for: ";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009653 F.printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00009654 OS << "\n";
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009655 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
Dan Gohmanc8e23622009-04-21 23:15:49 +00009656 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00009657}
Dan Gohmane20f8242009-04-21 00:47:46 +00009658
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009659ScalarEvolution::LoopDisposition
9660ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009661 auto &Values = LoopDispositions[S];
9662 for (auto &V : Values) {
9663 if (V.getPointer() == L)
9664 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009665 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009666 Values.emplace_back(L, LoopVariant);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009667 LoopDisposition D = computeLoopDisposition(S, L);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009668 auto &Values2 = LoopDispositions[S];
9669 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9670 if (V.getPointer() == L) {
9671 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009672 break;
9673 }
9674 }
9675 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009676}
9677
9678ScalarEvolution::LoopDisposition
9679ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009680 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009681 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009682 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009683 case scTruncate:
9684 case scZeroExtend:
9685 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009686 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00009687 case scAddRecExpr: {
9688 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
9689
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009690 // If L is the addrec's loop, it's computable.
9691 if (AR->getLoop() == L)
9692 return LoopComputable;
9693
Dan Gohmanafd6db92010-11-17 21:23:15 +00009694 // Add recurrences are never invariant in the function-body (null loop).
9695 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009696 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009697
9698 // This recurrence is variant w.r.t. L if L contains AR's loop.
9699 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009700 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009701
9702 // This recurrence is invariant w.r.t. L if AR's loop contains L.
9703 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009704 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009705
9706 // This recurrence is variant w.r.t. L if any of its operands
9707 // are variant.
Sanjoy Das01947432015-11-22 21:20:13 +00009708 for (auto *Op : AR->operands())
9709 if (!isLoopInvariant(Op, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009710 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009711
9712 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009713 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009714 }
9715 case scAddExpr:
9716 case scMulExpr:
9717 case scUMaxExpr:
9718 case scSMaxExpr: {
Dan Gohmanafd6db92010-11-17 21:23:15 +00009719 bool HasVarying = false;
Sanjoy Das01947432015-11-22 21:20:13 +00009720 for (auto *Op : cast<SCEVNAryExpr>(S)->operands()) {
9721 LoopDisposition D = getLoopDisposition(Op, L);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009722 if (D == LoopVariant)
9723 return LoopVariant;
9724 if (D == LoopComputable)
9725 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009726 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009727 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009728 }
9729 case scUDivExpr: {
9730 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009731 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
9732 if (LD == LoopVariant)
9733 return LoopVariant;
9734 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
9735 if (RD == LoopVariant)
9736 return LoopVariant;
9737 return (LD == LoopInvariant && RD == LoopInvariant) ?
9738 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009739 }
9740 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009741 // All non-instruction values are loop invariant. All instructions are loop
9742 // invariant if they are not contained in the specified loop.
9743 // Instructions are never considered invariant in the function body
9744 // (null loop) because they are defined within the "loop".
Sanjoy Das01947432015-11-22 21:20:13 +00009745 if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009746 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
9747 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009748 case scCouldNotCompute:
9749 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00009750 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009751 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00009752}
9753
9754bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
9755 return getLoopDisposition(S, L) == LoopInvariant;
9756}
9757
9758bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
9759 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00009760}
Dan Gohman20d9ce22010-11-17 21:41:58 +00009761
Dan Gohman8ea83d82010-11-18 00:34:22 +00009762ScalarEvolution::BlockDisposition
9763ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009764 auto &Values = BlockDispositions[S];
9765 for (auto &V : Values) {
9766 if (V.getPointer() == BB)
9767 return V.getInt();
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009768 }
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009769 Values.emplace_back(BB, DoesNotDominateBlock);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009770 BlockDisposition D = computeBlockDisposition(S, BB);
Benjamin Kramerd7e331e2015-02-07 16:41:12 +00009771 auto &Values2 = BlockDispositions[S];
9772 for (auto &V : make_range(Values2.rbegin(), Values2.rend())) {
9773 if (V.getPointer() == BB) {
9774 V.setInt(D);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00009775 break;
9776 }
9777 }
9778 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009779}
9780
Dan Gohman8ea83d82010-11-18 00:34:22 +00009781ScalarEvolution::BlockDisposition
9782ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00009783 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00009784 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009785 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009786 case scTruncate:
9787 case scZeroExtend:
9788 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00009789 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00009790 case scAddRecExpr: {
9791 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00009792 // to test for proper dominance too, because the instruction which
9793 // produces the addrec's value is a PHI, and a PHI effectively properly
9794 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00009795 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009796 if (!DT.dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009797 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009798 }
9799 // FALL THROUGH into SCEVNAryExpr handling.
9800 case scAddExpr:
9801 case scMulExpr:
9802 case scUMaxExpr:
9803 case scSMaxExpr: {
9804 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009805 bool Proper = true;
Sanjoy Dasd87e4352015-12-08 22:53:36 +00009806 for (const SCEV *NAryOp : NAry->operands()) {
9807 BlockDisposition D = getBlockDisposition(NAryOp, BB);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009808 if (D == DoesNotDominateBlock)
9809 return DoesNotDominateBlock;
9810 if (D == DominatesBlock)
9811 Proper = false;
9812 }
9813 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009814 }
9815 case scUDivExpr: {
9816 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009817 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
9818 BlockDisposition LD = getBlockDisposition(LHS, BB);
9819 if (LD == DoesNotDominateBlock)
9820 return DoesNotDominateBlock;
9821 BlockDisposition RD = getBlockDisposition(RHS, BB);
9822 if (RD == DoesNotDominateBlock)
9823 return DoesNotDominateBlock;
9824 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
9825 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009826 }
9827 case scUnknown:
9828 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00009829 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
9830 if (I->getParent() == BB)
9831 return DominatesBlock;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009832 if (DT.properlyDominates(I->getParent(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00009833 return ProperlyDominatesBlock;
9834 return DoesNotDominateBlock;
9835 }
9836 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009837 case scCouldNotCompute:
9838 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00009839 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00009840 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00009841}
9842
9843bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
9844 return getBlockDisposition(S, BB) >= DominatesBlock;
9845}
9846
9847bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
9848 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00009849}
Dan Gohman534749b2010-11-17 22:27:42 +00009850
9851bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Sanjoy Das7d752672015-12-08 04:32:54 +00009852 // Search for a SCEV expression node within an expression tree.
9853 // Implements SCEVTraversal::Visitor.
9854 struct SCEVSearch {
9855 const SCEV *Node;
9856 bool IsFound;
9857
9858 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
9859
9860 bool follow(const SCEV *S) {
9861 IsFound |= (S == Node);
9862 return !IsFound;
9863 }
9864 bool isDone() const { return IsFound; }
9865 };
9866
Andrew Trick365e31c2012-07-13 23:33:03 +00009867 SCEVSearch Search(Op);
9868 visitAll(S, Search);
9869 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00009870}
Dan Gohman7e6b3932010-11-17 23:28:48 +00009871
9872void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
9873 ValuesAtScopes.erase(S);
9874 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00009875 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009876 UnsignedRanges.erase(S);
9877 SignedRanges.erase(S);
Wei Mia49559b2016-02-04 01:27:38 +00009878 ExprValueMap.erase(S);
9879 HasRecMap.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00009880
Silviu Baranga6f444df2016-04-08 14:29:09 +00009881 auto RemoveSCEVFromBackedgeMap =
9882 [S, this](DenseMap<const Loop *, BackedgeTakenInfo> &Map) {
9883 for (auto I = Map.begin(), E = Map.end(); I != E;) {
9884 BackedgeTakenInfo &BEInfo = I->second;
9885 if (BEInfo.hasOperand(S, this)) {
9886 BEInfo.clear();
9887 Map.erase(I++);
9888 } else
9889 ++I;
9890 }
9891 };
9892
9893 RemoveSCEVFromBackedgeMap(BackedgeTakenCounts);
9894 RemoveSCEVFromBackedgeMap(PredicatedBackedgeTakenCounts);
Dan Gohman7e6b3932010-11-17 23:28:48 +00009895}
Benjamin Kramer214935e2012-10-26 17:31:32 +00009896
9897typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009898
Alp Tokercb402912014-01-24 17:20:08 +00009899/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00009900static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
9901 size_t Pos = 0;
9902 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
9903 Str.replace(Pos, From.size(), To.data(), To.size());
9904 Pos += To.size();
9905 }
9906}
9907
Benjamin Kramer214935e2012-10-26 17:31:32 +00009908/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
9909static void
9910getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009911 std::string &S = Map[L];
9912 if (S.empty()) {
9913 raw_string_ostream OS(S);
9914 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009915
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009916 // false and 0 are semantically equivalent. This can happen in dead loops.
9917 replaceSubString(OS.str(), "false", "0");
9918 // Remove wrap flags, their use in SCEV is highly fragile.
9919 // FIXME: Remove this when SCEV gets smarter about them.
9920 replaceSubString(OS.str(), "<nw>", "");
9921 replaceSubString(OS.str(), "<nsw>", "");
9922 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00009923 }
Sanjoy Das2fbfb252015-12-23 17:48:14 +00009924
JF Bastien61ad8b32015-12-23 18:18:53 +00009925 for (auto *R : reverse(*L))
9926 getLoopBackedgeTakenCounts(R, Map, SE); // recurse.
Benjamin Kramer214935e2012-10-26 17:31:32 +00009927}
9928
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009929void ScalarEvolution::verify() const {
Benjamin Kramer214935e2012-10-26 17:31:32 +00009930 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
9931
9932 // Gather stringified backedge taken counts for all loops using SCEV's caches.
9933 // FIXME: It would be much better to store actual values instead of strings,
9934 // but SCEV pointers will change if we drop the caches.
9935 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009936 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
Benjamin Kramer214935e2012-10-26 17:31:32 +00009937 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
9938
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009939 // Gather stringified backedge taken counts for all loops using a fresh
9940 // ScalarEvolution object.
9941 ScalarEvolution SE2(F, TLI, AC, DT, LI);
9942 for (LoopInfo::reverse_iterator I = LI.rbegin(), E = LI.rend(); I != E; ++I)
9943 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE2);
Benjamin Kramer214935e2012-10-26 17:31:32 +00009944
9945 // Now compare whether they're the same with and without caches. This allows
9946 // verifying that no pass changed the cache.
9947 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
9948 "New loops suddenly appeared!");
9949
9950 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
9951 OldE = BackedgeDumpsOld.end(),
9952 NewI = BackedgeDumpsNew.begin();
9953 OldI != OldE; ++OldI, ++NewI) {
9954 assert(OldI->first == NewI->first && "Loop order changed!");
9955
9956 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
9957 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009958 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00009959 // means that a pass is buggy or SCEV has to learn a new pattern but is
9960 // usually not harmful.
9961 if (OldI->second != NewI->second &&
9962 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009963 NewI->second.find("undef") == std::string::npos &&
9964 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00009965 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009966 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00009967 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00009968 << "' changed from '" << OldI->second
9969 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00009970 std::abort();
9971 }
9972 }
9973
9974 // TODO: Verify more things.
9975}
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009976
Chandler Carruthb4faf132016-03-11 10:22:49 +00009977char ScalarEvolutionAnalysis::PassID;
NAKAMURA Takumidf0cd722016-02-28 17:17:00 +00009978
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009979ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
Chandler Carruthb47f8012016-03-11 11:05:24 +00009980 AnalysisManager<Function> &AM) {
9981 return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
9982 AM.getResult<AssumptionAnalysis>(F),
9983 AM.getResult<DominatorTreeAnalysis>(F),
9984 AM.getResult<LoopAnalysis>(F));
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009985}
9986
9987PreservedAnalyses
Chandler Carruthb47f8012016-03-11 11:05:24 +00009988ScalarEvolutionPrinterPass::run(Function &F, AnalysisManager<Function> &AM) {
9989 AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
Chandler Carruth2f1fd162015-08-17 02:08:17 +00009990 return PreservedAnalyses::all();
9991}
9992
9993INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
9994 "Scalar Evolution Analysis", false, true)
9995INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9996INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
9997INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
9998INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
9999INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
10000 "Scalar Evolution Analysis", false, true)
10001char ScalarEvolutionWrapperPass::ID = 0;
10002
10003ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
10004 initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
10005}
10006
10007bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
10008 SE.reset(new ScalarEvolution(
10009 F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
10010 getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
10011 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
10012 getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
10013 return false;
10014}
10015
10016void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
10017
10018void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
10019 SE->print(OS);
10020}
10021
10022void ScalarEvolutionWrapperPass::verifyAnalysis() const {
10023 if (!VerifySCEV)
10024 return;
10025
10026 SE->verify();
10027}
10028
10029void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
10030 AU.setPreservesAll();
10031 AU.addRequiredTransitive<AssumptionCacheTracker>();
10032 AU.addRequiredTransitive<LoopInfoWrapperPass>();
10033 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
10034 AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
10035}
Silviu Barangae3c05342015-11-02 14:41:02 +000010036
10037const SCEVPredicate *
10038ScalarEvolution::getEqualPredicate(const SCEVUnknown *LHS,
10039 const SCEVConstant *RHS) {
10040 FoldingSetNodeID ID;
10041 // Unique this node based on the arguments
10042 ID.AddInteger(SCEVPredicate::P_Equal);
10043 ID.AddPointer(LHS);
10044 ID.AddPointer(RHS);
10045 void *IP = nullptr;
10046 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10047 return S;
10048 SCEVEqualPredicate *Eq = new (SCEVAllocator)
10049 SCEVEqualPredicate(ID.Intern(SCEVAllocator), LHS, RHS);
10050 UniquePreds.InsertNode(Eq, IP);
10051 return Eq;
10052}
10053
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010054const SCEVPredicate *ScalarEvolution::getWrapPredicate(
10055 const SCEVAddRecExpr *AR,
10056 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10057 FoldingSetNodeID ID;
10058 // Unique this node based on the arguments
10059 ID.AddInteger(SCEVPredicate::P_Wrap);
10060 ID.AddPointer(AR);
10061 ID.AddInteger(AddedFlags);
10062 void *IP = nullptr;
10063 if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
10064 return S;
10065 auto *OF = new (SCEVAllocator)
10066 SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
10067 UniquePreds.InsertNode(OF, IP);
10068 return OF;
10069}
10070
Benjamin Kramer83709b12015-11-16 09:01:28 +000010071namespace {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010072
Silviu Barangae3c05342015-11-02 14:41:02 +000010073class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
10074public:
Sanjoy Das807d33d2016-02-20 01:44:10 +000010075 // Rewrites \p S in the context of a loop L and the predicate A.
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010076 // If Assume is true, rewrite is free to add further predicates to A
10077 // such that the result will be an AddRecExpr.
Sanjoy Das807d33d2016-02-20 01:44:10 +000010078 static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
10079 SCEVUnionPredicate &A, bool Assume) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010080 SCEVPredicateRewriter Rewriter(L, SE, A, Assume);
Sanjoy Das807d33d2016-02-20 01:44:10 +000010081 return Rewriter.visit(S);
Silviu Barangae3c05342015-11-02 14:41:02 +000010082 }
10083
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010084 SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
10085 SCEVUnionPredicate &P, bool Assume)
10086 : SCEVRewriteVisitor(SE), P(P), L(L), Assume(Assume) {}
Silviu Barangae3c05342015-11-02 14:41:02 +000010087
10088 const SCEV *visitUnknown(const SCEVUnknown *Expr) {
10089 auto ExprPreds = P.getPredicatesForExpr(Expr);
10090 for (auto *Pred : ExprPreds)
10091 if (const auto *IPred = dyn_cast<const SCEVEqualPredicate>(Pred))
10092 if (IPred->getLHS() == Expr)
10093 return IPred->getRHS();
10094
10095 return Expr;
10096 }
10097
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010098 const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
10099 const SCEV *Operand = visit(Expr->getOperand());
10100 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
10101 if (AR && AR->getLoop() == L && AR->isAffine()) {
10102 // This couldn't be folded because the operand didn't have the nuw
10103 // flag. Add the nusw flag as an assumption that we could make.
10104 const SCEV *Step = AR->getStepRecurrence(SE);
10105 Type *Ty = Expr->getType();
10106 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
10107 return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
10108 SE.getSignExtendExpr(Step, Ty), L,
10109 AR->getNoWrapFlags());
10110 }
10111 return SE.getZeroExtendExpr(Operand, Expr->getType());
10112 }
10113
10114 const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
10115 const SCEV *Operand = visit(Expr->getOperand());
10116 const SCEVAddRecExpr *AR = dyn_cast<const SCEVAddRecExpr>(Operand);
10117 if (AR && AR->getLoop() == L && AR->isAffine()) {
10118 // This couldn't be folded because the operand didn't have the nsw
10119 // flag. Add the nssw flag as an assumption that we could make.
10120 const SCEV *Step = AR->getStepRecurrence(SE);
10121 Type *Ty = Expr->getType();
10122 if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
10123 return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
10124 SE.getSignExtendExpr(Step, Ty), L,
10125 AR->getNoWrapFlags());
10126 }
10127 return SE.getSignExtendExpr(Operand, Expr->getType());
10128 }
10129
Silviu Barangae3c05342015-11-02 14:41:02 +000010130private:
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010131 bool addOverflowAssumption(const SCEVAddRecExpr *AR,
10132 SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
10133 auto *A = SE.getWrapPredicate(AR, AddedFlags);
10134 if (!Assume) {
10135 // Check if we've already made this assumption.
10136 if (P.implies(A))
10137 return true;
10138 return false;
10139 }
10140 P.add(A);
10141 return true;
10142 }
10143
Silviu Barangae3c05342015-11-02 14:41:02 +000010144 SCEVUnionPredicate &P;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010145 const Loop *L;
10146 bool Assume;
Silviu Barangae3c05342015-11-02 14:41:02 +000010147};
Benjamin Kramer83709b12015-11-16 09:01:28 +000010148} // end anonymous namespace
Silviu Barangae3c05342015-11-02 14:41:02 +000010149
Sanjoy Das807d33d2016-02-20 01:44:10 +000010150const SCEV *ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
Silviu Barangae3c05342015-11-02 14:41:02 +000010151 SCEVUnionPredicate &Preds) {
Sanjoy Das807d33d2016-02-20 01:44:10 +000010152 return SCEVPredicateRewriter::rewrite(S, L, *this, Preds, false);
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010153}
10154
Silviu Barangad68ed852016-03-23 15:29:30 +000010155const SCEVAddRecExpr *
Sanjoy Das807d33d2016-02-20 01:44:10 +000010156ScalarEvolution::convertSCEVToAddRecWithPredicates(const SCEV *S, const Loop *L,
10157 SCEVUnionPredicate &Preds) {
Silviu Barangad68ed852016-03-23 15:29:30 +000010158 SCEVUnionPredicate TransformPreds;
10159 S = SCEVPredicateRewriter::rewrite(S, L, *this, TransformPreds, true);
10160 auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
10161
10162 if (!AddRec)
10163 return nullptr;
10164
10165 // Since the transformation was successful, we can now transfer the SCEV
10166 // predicates.
10167 Preds.add(&TransformPreds);
10168 return AddRec;
Silviu Barangae3c05342015-11-02 14:41:02 +000010169}
10170
10171/// SCEV predicates
10172SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
10173 SCEVPredicateKind Kind)
10174 : FastID(ID), Kind(Kind) {}
10175
10176SCEVEqualPredicate::SCEVEqualPredicate(const FoldingSetNodeIDRef ID,
10177 const SCEVUnknown *LHS,
10178 const SCEVConstant *RHS)
10179 : SCEVPredicate(ID, P_Equal), LHS(LHS), RHS(RHS) {}
10180
10181bool SCEVEqualPredicate::implies(const SCEVPredicate *N) const {
10182 const auto *Op = dyn_cast<const SCEVEqualPredicate>(N);
10183
10184 if (!Op)
10185 return false;
10186
10187 return Op->LHS == LHS && Op->RHS == RHS;
10188}
10189
10190bool SCEVEqualPredicate::isAlwaysTrue() const { return false; }
10191
10192const SCEV *SCEVEqualPredicate::getExpr() const { return LHS; }
10193
10194void SCEVEqualPredicate::print(raw_ostream &OS, unsigned Depth) const {
10195 OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
10196}
10197
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010198SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
10199 const SCEVAddRecExpr *AR,
10200 IncrementWrapFlags Flags)
10201 : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
10202
10203const SCEV *SCEVWrapPredicate::getExpr() const { return AR; }
10204
10205bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
10206 const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
10207
10208 return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
10209}
10210
10211bool SCEVWrapPredicate::isAlwaysTrue() const {
10212 SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
10213 IncrementWrapFlags IFlags = Flags;
10214
10215 if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
10216 IFlags = clearFlags(IFlags, IncrementNSSW);
10217
10218 return IFlags == IncrementAnyWrap;
10219}
10220
10221void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
10222 OS.indent(Depth) << *getExpr() << " Added Flags: ";
10223 if (SCEVWrapPredicate::IncrementNUSW & getFlags())
10224 OS << "<nusw>";
10225 if (SCEVWrapPredicate::IncrementNSSW & getFlags())
10226 OS << "<nssw>";
10227 OS << "\n";
10228}
10229
10230SCEVWrapPredicate::IncrementWrapFlags
10231SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
10232 ScalarEvolution &SE) {
10233 IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
10234 SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
10235
10236 // We can safely transfer the NSW flag as NSSW.
10237 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
10238 ImpliedFlags = IncrementNSSW;
10239
10240 if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
10241 // If the increment is positive, the SCEV NUW flag will also imply the
10242 // WrapPredicate NUSW flag.
10243 if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
10244 if (Step->getValue()->getValue().isNonNegative())
10245 ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
10246 }
10247
10248 return ImpliedFlags;
10249}
10250
Silviu Barangae3c05342015-11-02 14:41:02 +000010251/// Union predicates don't get cached so create a dummy set ID for it.
10252SCEVUnionPredicate::SCEVUnionPredicate()
10253 : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {}
10254
10255bool SCEVUnionPredicate::isAlwaysTrue() const {
Sanjoy Das3b827c72015-11-29 23:40:53 +000010256 return all_of(Preds,
10257 [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010258}
10259
10260ArrayRef<const SCEVPredicate *>
10261SCEVUnionPredicate::getPredicatesForExpr(const SCEV *Expr) {
10262 auto I = SCEVToPreds.find(Expr);
10263 if (I == SCEVToPreds.end())
10264 return ArrayRef<const SCEVPredicate *>();
10265 return I->second;
10266}
10267
10268bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
10269 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N))
Sanjoy Das3b827c72015-11-29 23:40:53 +000010270 return all_of(Set->Preds,
10271 [this](const SCEVPredicate *I) { return this->implies(I); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010272
10273 auto ScevPredsIt = SCEVToPreds.find(N->getExpr());
10274 if (ScevPredsIt == SCEVToPreds.end())
10275 return false;
10276 auto &SCEVPreds = ScevPredsIt->second;
10277
Sanjoy Dasff3b8b42015-12-01 07:49:23 +000010278 return any_of(SCEVPreds,
10279 [N](const SCEVPredicate *I) { return I->implies(N); });
Silviu Barangae3c05342015-11-02 14:41:02 +000010280}
10281
10282const SCEV *SCEVUnionPredicate::getExpr() const { return nullptr; }
10283
10284void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
10285 for (auto Pred : Preds)
10286 Pred->print(OS, Depth);
10287}
10288
10289void SCEVUnionPredicate::add(const SCEVPredicate *N) {
10290 if (const auto *Set = dyn_cast<const SCEVUnionPredicate>(N)) {
10291 for (auto Pred : Set->Preds)
10292 add(Pred);
10293 return;
10294 }
10295
10296 if (implies(N))
10297 return;
10298
10299 const SCEV *Key = N->getExpr();
10300 assert(Key && "Only SCEVUnionPredicate doesn't have an "
10301 " associated expression!");
10302
10303 SCEVToPreds[Key].push_back(N);
10304 Preds.push_back(N);
10305}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010306
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010307PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
10308 Loop &L)
Silviu Baranga6f444df2016-04-08 14:29:09 +000010309 : SE(SE), L(L), Generation(0), BackedgeCount(nullptr) {}
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010310
10311const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
10312 const SCEV *Expr = SE.getSCEV(V);
10313 RewriteEntry &Entry = RewriteMap[Expr];
10314
10315 // If we already have an entry and the version matches, return it.
10316 if (Entry.second && Generation == Entry.first)
10317 return Entry.second;
10318
10319 // We found an entry but it's stale. Rewrite the stale entry
10320 // acording to the current predicate.
10321 if (Entry.second)
10322 Expr = Entry.second;
10323
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010324 const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, Preds);
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010325 Entry = {Generation, NewSCEV};
10326
10327 return NewSCEV;
10328}
10329
Silviu Baranga6f444df2016-04-08 14:29:09 +000010330const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
10331 if (!BackedgeCount) {
10332 SCEVUnionPredicate BackedgePred;
10333 BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, BackedgePred);
10334 addPredicate(BackedgePred);
10335 }
10336 return BackedgeCount;
10337}
10338
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010339void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
10340 if (Preds.implies(&Pred))
10341 return;
10342 Preds.add(&Pred);
10343 updateGeneration();
10344}
10345
10346const SCEVUnionPredicate &PredicatedScalarEvolution::getUnionPredicate() const {
10347 return Preds;
10348}
10349
10350void PredicatedScalarEvolution::updateGeneration() {
10351 // If the generation number wrapped recompute everything.
10352 if (++Generation == 0) {
10353 for (auto &II : RewriteMap) {
10354 const SCEV *Rewritten = II.second.second;
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010355 II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, Preds)};
Silviu Baranga9cd9a7e2015-12-09 16:06:28 +000010356 }
10357 }
10358}
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010359
10360void PredicatedScalarEvolution::setNoOverflow(
10361 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10362 const SCEV *Expr = getSCEV(V);
10363 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10364
10365 auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
10366
10367 // Clear the statically implied flags.
10368 Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
10369 addPredicate(*SE.getWrapPredicate(AR, Flags));
10370
10371 auto II = FlagsMap.insert({V, Flags});
10372 if (!II.second)
10373 II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
10374}
10375
10376bool PredicatedScalarEvolution::hasNoOverflow(
10377 Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
10378 const SCEV *Expr = getSCEV(V);
10379 const auto *AR = cast<SCEVAddRecExpr>(Expr);
10380
10381 Flags = SCEVWrapPredicate::clearFlags(
10382 Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
10383
10384 auto II = FlagsMap.find(V);
10385
10386 if (II != FlagsMap.end())
10387 Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
10388
10389 return Flags == SCEVWrapPredicate::IncrementAnyWrap;
10390}
10391
Silviu Barangad68ed852016-03-23 15:29:30 +000010392const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010393 const SCEV *Expr = this->getSCEV(V);
Silviu Barangad68ed852016-03-23 15:29:30 +000010394 auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, Preds);
10395
10396 if (!New)
10397 return nullptr;
10398
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010399 updateGeneration();
10400 RewriteMap[SE.getSCEV(V)] = {Generation, New};
10401 return New;
10402}
10403
Silviu Baranga6f444df2016-04-08 14:29:09 +000010404PredicatedScalarEvolution::PredicatedScalarEvolution(
10405 const PredicatedScalarEvolution &Init)
10406 : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L), Preds(Init.Preds),
10407 Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
Silviu Barangaea63a7f2016-02-08 17:02:45 +000010408 for (auto I = Init.FlagsMap.begin(), E = Init.FlagsMap.end(); I != E; ++I)
10409 FlagsMap.insert(*I);
10410}