blob: e40c2f2447aa257724b06f4fcac81c4ada9e5ae4 [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"
Hal Finkel60db0582014-09-07 18:57:58 +000066#include "llvm/Analysis/AssumptionTracker.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"
Dan Gohman1ee696d2009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth8cd041e2014-03-04 12:24:34 +000072#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000073#include "llvm/IR/Constants.h"
74#include "llvm/IR/DataLayout.h"
75#include "llvm/IR/DerivedTypes.h"
Chandler Carruth5ad5f152014-01-13 09:26:24 +000076#include "llvm/IR/Dominators.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000077#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000078#include "llvm/IR/GlobalAlias.h"
79#include "llvm/IR/GlobalVariable.h"
Chandler Carruth83948572014-03-04 10:30:26 +000080#include "llvm/IR/InstIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000081#include "llvm/IR/Instructions.h"
82#include "llvm/IR/LLVMContext.h"
Sanjoy Das1f05c512014-10-10 21:22:34 +000083#include "llvm/IR/Metadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000084#include "llvm/IR/Operator.h"
Chris Lattner996795b2006-06-28 23:17:24 +000085#include "llvm/Support/CommandLine.h"
David Greene2330f782009-12-23 22:58:38 +000086#include "llvm/Support/Debug.h"
Torok Edwin56d06592009-07-11 20:10:48 +000087#include "llvm/Support/ErrorHandling.h"
Chris Lattner0a1e9932006-12-19 01:16:02 +000088#include "llvm/Support/MathExtras.h"
Dan Gohmane20f8242009-04-21 00:47:46 +000089#include "llvm/Support/raw_ostream.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000090#include "llvm/Target/TargetLibraryInfo.h"
Alkis Evlogimenosa5c04ee2004-09-03 18:19:51 +000091#include <algorithm>
Chris Lattnerd934c702004-04-02 20:23:17 +000092using namespace llvm;
93
Chandler Carruthf1221bd2014-04-22 02:48:03 +000094#define DEBUG_TYPE "scalar-evolution"
95
Chris Lattner57ef9422006-12-19 22:30:33 +000096STATISTIC(NumArrayLenItCounts,
97 "Number of trip counts computed with array length");
98STATISTIC(NumTripCountsComputed,
99 "Number of loops with predictable loop counts");
100STATISTIC(NumTripCountsNotComputed,
101 "Number of loops without predictable loop counts");
102STATISTIC(NumBruteForceTripCountsComputed,
103 "Number of loops with trip counts computed by force");
104
Dan Gohmand78c4002008-05-13 00:00:25 +0000105static cl::opt<unsigned>
Chris Lattner57ef9422006-12-19 22:30:33 +0000106MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
107 cl::desc("Maximum number of iterations SCEV will "
Dan Gohmance973df2009-06-24 04:48:43 +0000108 "symbolically execute a constant "
109 "derived loop"),
Chris Lattner57ef9422006-12-19 22:30:33 +0000110 cl::init(100));
111
Benjamin Kramer214935e2012-10-26 17:31:32 +0000112// FIXME: Enable this with XDEBUG when the test suite is clean.
113static cl::opt<bool>
114VerifySCEV("verify-scev",
115 cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
116
Owen Anderson8ac477f2010-10-12 19:48:12 +0000117INITIALIZE_PASS_BEGIN(ScalarEvolution, "scalar-evolution",
118 "Scalar Evolution Analysis", false, true)
Hal Finkel60db0582014-09-07 18:57:58 +0000119INITIALIZE_PASS_DEPENDENCY(AssumptionTracker)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000120INITIALIZE_PASS_DEPENDENCY(LoopInfo)
Chandler Carruth73523022014-01-13 13:07:17 +0000121INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
Chad Rosierc24b86f2011-12-01 03:08:23 +0000122INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
Owen Anderson8ac477f2010-10-12 19:48:12 +0000123INITIALIZE_PASS_END(ScalarEvolution, "scalar-evolution",
Owen Andersondf7a4f22010-10-07 22:25:06 +0000124 "Scalar Evolution Analysis", false, true)
Devang Patel8c78a0b2007-05-03 01:11:54 +0000125char ScalarEvolution::ID = 0;
Chris Lattnerd934c702004-04-02 20:23:17 +0000126
127//===----------------------------------------------------------------------===//
128// SCEV class definitions
129//===----------------------------------------------------------------------===//
130
131//===----------------------------------------------------------------------===//
132// Implementation of the SCEV class.
133//
Dan Gohman3423e722009-06-30 20:13:32 +0000134
Manman Ren49d684e2012-09-12 05:06:18 +0000135#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
Chris Lattnerd934c702004-04-02 20:23:17 +0000136void SCEV::dump() const {
David Greenedf1c4972009-12-23 22:18:14 +0000137 print(dbgs());
138 dbgs() << '\n';
Dan Gohmane20f8242009-04-21 00:47:46 +0000139}
Manman Renc3366cc2012-09-06 19:55:56 +0000140#endif
Dan Gohmane20f8242009-04-21 00:47:46 +0000141
Dan Gohman534749b2010-11-17 22:27:42 +0000142void SCEV::print(raw_ostream &OS) const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000143 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000144 case scConstant:
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000145 cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000146 return;
147 case scTruncate: {
148 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
149 const SCEV *Op = Trunc->getOperand();
150 OS << "(trunc " << *Op->getType() << " " << *Op << " to "
151 << *Trunc->getType() << ")";
152 return;
153 }
154 case scZeroExtend: {
155 const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
156 const SCEV *Op = ZExt->getOperand();
157 OS << "(zext " << *Op->getType() << " " << *Op << " to "
158 << *ZExt->getType() << ")";
159 return;
160 }
161 case scSignExtend: {
162 const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
163 const SCEV *Op = SExt->getOperand();
164 OS << "(sext " << *Op->getType() << " " << *Op << " to "
165 << *SExt->getType() << ")";
166 return;
167 }
168 case scAddRecExpr: {
169 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
170 OS << "{" << *AR->getOperand(0);
171 for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
172 OS << ",+," << *AR->getOperand(i);
173 OS << "}<";
Andrew Trick8b55b732011-03-14 16:50:06 +0000174 if (AR->getNoWrapFlags(FlagNUW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000175 OS << "nuw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000176 if (AR->getNoWrapFlags(FlagNSW))
Chris Lattnera337f5e2011-01-09 02:16:18 +0000177 OS << "nsw><";
Andrew Trick8b55b732011-03-14 16:50:06 +0000178 if (AR->getNoWrapFlags(FlagNW) &&
179 !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
180 OS << "nw><";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000181 AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohman534749b2010-11-17 22:27:42 +0000182 OS << ">";
183 return;
184 }
185 case scAddExpr:
186 case scMulExpr:
187 case scUMaxExpr:
188 case scSMaxExpr: {
189 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
Craig Topper9f008862014-04-15 04:59:12 +0000190 const char *OpStr = nullptr;
Dan Gohman534749b2010-11-17 22:27:42 +0000191 switch (NAry->getSCEVType()) {
192 case scAddExpr: OpStr = " + "; break;
193 case scMulExpr: OpStr = " * "; break;
194 case scUMaxExpr: OpStr = " umax "; break;
195 case scSMaxExpr: OpStr = " smax "; break;
196 }
197 OS << "(";
198 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
199 I != E; ++I) {
200 OS << **I;
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +0000201 if (std::next(I) != E)
Dan Gohman534749b2010-11-17 22:27:42 +0000202 OS << OpStr;
203 }
204 OS << ")";
Andrew Trickd912a5b2011-11-29 02:06:35 +0000205 switch (NAry->getSCEVType()) {
206 case scAddExpr:
207 case scMulExpr:
208 if (NAry->getNoWrapFlags(FlagNUW))
209 OS << "<nuw>";
210 if (NAry->getNoWrapFlags(FlagNSW))
211 OS << "<nsw>";
212 }
Dan Gohman534749b2010-11-17 22:27:42 +0000213 return;
214 }
215 case scUDivExpr: {
216 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
217 OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
218 return;
219 }
220 case scUnknown: {
221 const SCEVUnknown *U = cast<SCEVUnknown>(this);
Chris Lattner229907c2011-07-18 04:54:35 +0000222 Type *AllocTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000223 if (U->isSizeOf(AllocTy)) {
224 OS << "sizeof(" << *AllocTy << ")";
225 return;
226 }
227 if (U->isAlignOf(AllocTy)) {
228 OS << "alignof(" << *AllocTy << ")";
229 return;
230 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000231
Chris Lattner229907c2011-07-18 04:54:35 +0000232 Type *CTy;
Dan Gohman534749b2010-11-17 22:27:42 +0000233 Constant *FieldNo;
234 if (U->isOffsetOf(CTy, FieldNo)) {
235 OS << "offsetof(" << *CTy << ", ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000236 FieldNo->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000237 OS << ")";
238 return;
239 }
Andrew Trick2a3b7162011-03-09 17:23:39 +0000240
Dan Gohman534749b2010-11-17 22:27:42 +0000241 // Otherwise just print it normally.
Chandler Carruthd48cdbf2014-01-09 02:29:41 +0000242 U->getValue()->printAsOperand(OS, false);
Dan Gohman534749b2010-11-17 22:27:42 +0000243 return;
244 }
245 case scCouldNotCompute:
246 OS << "***COULDNOTCOMPUTE***";
247 return;
Dan Gohman534749b2010-11-17 22:27:42 +0000248 }
249 llvm_unreachable("Unknown SCEV kind!");
250}
251
Chris Lattner229907c2011-07-18 04:54:35 +0000252Type *SCEV::getType() const {
Benjamin Kramer987b8502014-02-11 19:02:55 +0000253 switch (static_cast<SCEVTypes>(getSCEVType())) {
Dan Gohman534749b2010-11-17 22:27:42 +0000254 case scConstant:
255 return cast<SCEVConstant>(this)->getType();
256 case scTruncate:
257 case scZeroExtend:
258 case scSignExtend:
259 return cast<SCEVCastExpr>(this)->getType();
260 case scAddRecExpr:
261 case scMulExpr:
262 case scUMaxExpr:
263 case scSMaxExpr:
264 return cast<SCEVNAryExpr>(this)->getType();
265 case scAddExpr:
266 return cast<SCEVAddExpr>(this)->getType();
267 case scUDivExpr:
268 return cast<SCEVUDivExpr>(this)->getType();
269 case scUnknown:
270 return cast<SCEVUnknown>(this)->getType();
271 case scCouldNotCompute:
272 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman534749b2010-11-17 22:27:42 +0000273 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000274 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman534749b2010-11-17 22:27:42 +0000275}
276
Dan Gohmanbe928e32008-06-18 16:23:07 +0000277bool SCEV::isZero() const {
278 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
279 return SC->getValue()->isZero();
280 return false;
281}
282
Dan Gohmanba7f6d82009-05-18 15:22:39 +0000283bool SCEV::isOne() const {
284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
285 return SC->getValue()->isOne();
286 return false;
287}
Chris Lattnerd934c702004-04-02 20:23:17 +0000288
Dan Gohman18a96bb2009-06-24 00:30:26 +0000289bool SCEV::isAllOnesValue() const {
290 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
291 return SC->getValue()->isAllOnesValue();
292 return false;
293}
294
Andrew Trick881a7762012-01-07 00:27:31 +0000295/// isNonConstantNegative - Return true if the specified scev is negated, but
296/// not a constant.
297bool SCEV::isNonConstantNegative() const {
298 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
299 if (!Mul) return false;
300
301 // If there is a constant factor, it will be first.
302 const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
303 if (!SC) return false;
304
305 // Return true if the value is negative, this matches things like (-42 * V).
306 return SC->getValue()->getValue().isNegative();
307}
308
Owen Anderson04052ec2009-06-22 21:57:23 +0000309SCEVCouldNotCompute::SCEVCouldNotCompute() :
Dan Gohman24ceda82010-06-18 19:54:20 +0000310 SCEV(FoldingSetNodeIDRef(), scCouldNotCompute) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000311
Chris Lattnerd934c702004-04-02 20:23:17 +0000312bool SCEVCouldNotCompute::classof(const SCEV *S) {
313 return S->getSCEVType() == scCouldNotCompute;
314}
315
Dan Gohmanaf752342009-07-07 17:06:11 +0000316const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000317 FoldingSetNodeID ID;
318 ID.AddInteger(scConstant);
319 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +0000320 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000321 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman24ceda82010-06-18 19:54:20 +0000322 SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000323 UniqueSCEVs.InsertNode(S, IP);
324 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000325}
Chris Lattnerd934c702004-04-02 20:23:17 +0000326
Nick Lewycky31eaca52014-01-27 10:04:03 +0000327const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
Owen Andersonedb4a702009-07-24 23:12:02 +0000328 return getConstant(ConstantInt::get(getContext(), Val));
Dan Gohman0a76e7f2007-07-09 15:25:17 +0000329}
330
Dan Gohmanaf752342009-07-07 17:06:11 +0000331const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +0000332ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
333 IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
Dan Gohmana029cbe2010-04-21 16:04:04 +0000334 return getConstant(ConstantInt::get(ITy, V, isSigned));
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000335}
336
Dan Gohman24ceda82010-06-18 19:54:20 +0000337SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000338 unsigned SCEVTy, const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000339 : SCEV(ID, SCEVTy), Op(op), Ty(ty) {}
Dan Gohmanc5c85c02009-06-27 21:21:31 +0000340
Dan Gohman24ceda82010-06-18 19:54:20 +0000341SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000342 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000343 : SCEVCastExpr(ID, scTruncate, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000344 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
345 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000346 "Cannot truncate non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000347}
Chris Lattnerd934c702004-04-02 20:23:17 +0000348
Dan Gohman24ceda82010-06-18 19:54:20 +0000349SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000350 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000351 : SCEVCastExpr(ID, scZeroExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000352 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
353 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000354 "Cannot zero extend non-integer value!");
Chris Lattnerb4f681b2004-04-15 15:07:24 +0000355}
356
Dan Gohman24ceda82010-06-18 19:54:20 +0000357SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
Chris Lattner229907c2011-07-18 04:54:35 +0000358 const SCEV *op, Type *ty)
Dan Gohman24ceda82010-06-18 19:54:20 +0000359 : SCEVCastExpr(ID, scSignExtend, op, ty) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000360 assert((Op->getType()->isIntegerTy() || Op->getType()->isPointerTy()) &&
361 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000362 "Cannot sign extend non-integer value!");
Dan Gohmancb9e09a2007-06-15 14:38:12 +0000363}
364
Dan Gohman7cac9572010-08-02 23:49:30 +0000365void SCEVUnknown::deleted() {
Dan Gohman761065e2010-11-17 02:44:44 +0000366 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000367 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000368
369 // Remove this SCEVUnknown from the uniquing map.
370 SE->UniqueSCEVs.RemoveNode(this);
371
372 // Release the value.
Craig Topper9f008862014-04-15 04:59:12 +0000373 setValPtr(nullptr);
Dan Gohman7cac9572010-08-02 23:49:30 +0000374}
375
376void SCEVUnknown::allUsesReplacedWith(Value *New) {
Dan Gohman761065e2010-11-17 02:44:44 +0000377 // Clear this SCEVUnknown from various maps.
Dan Gohman7e6b3932010-11-17 23:28:48 +0000378 SE->forgetMemoizedResults(this);
Dan Gohman7cac9572010-08-02 23:49:30 +0000379
380 // Remove this SCEVUnknown from the uniquing map.
381 SE->UniqueSCEVs.RemoveNode(this);
382
383 // Update this SCEVUnknown to point to the new value. This is needed
384 // because there may still be outstanding SCEVs which still point to
385 // this SCEVUnknown.
386 setValPtr(New);
387}
388
Chris Lattner229907c2011-07-18 04:54:35 +0000389bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000390 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000391 if (VCE->getOpcode() == Instruction::PtrToInt)
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000393 if (CE->getOpcode() == Instruction::GetElementPtr &&
394 CE->getOperand(0)->isNullValue() &&
395 CE->getNumOperands() == 2)
396 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
397 if (CI->isOne()) {
398 AllocTy = cast<PointerType>(CE->getOperand(0)->getType())
399 ->getElementType();
400 return true;
401 }
Dan Gohmancf913832010-01-28 02:15:55 +0000402
403 return false;
404}
405
Chris Lattner229907c2011-07-18 04:54:35 +0000406bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000407 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmancf913832010-01-28 02:15:55 +0000408 if (VCE->getOpcode() == Instruction::PtrToInt)
409 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000410 if (CE->getOpcode() == Instruction::GetElementPtr &&
411 CE->getOperand(0)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000412 Type *Ty =
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000413 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000414 if (StructType *STy = dyn_cast<StructType>(Ty))
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000415 if (!STy->isPacked() &&
416 CE->getNumOperands() == 3 &&
417 CE->getOperand(1)->isNullValue()) {
418 if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
419 if (CI->isOne() &&
420 STy->getNumElements() == 2 &&
Duncan Sands9dff9be2010-02-15 16:12:20 +0000421 STy->getElementType(0)->isIntegerTy(1)) {
Dan Gohman7e5f1b22010-02-02 01:38:49 +0000422 AllocTy = STy->getElementType(1);
423 return true;
424 }
425 }
426 }
Dan Gohmancf913832010-01-28 02:15:55 +0000427
428 return false;
429}
430
Chris Lattner229907c2011-07-18 04:54:35 +0000431bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
Dan Gohman7cac9572010-08-02 23:49:30 +0000432 if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000433 if (VCE->getOpcode() == Instruction::PtrToInt)
434 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
435 if (CE->getOpcode() == Instruction::GetElementPtr &&
436 CE->getNumOperands() == 3 &&
437 CE->getOperand(0)->isNullValue() &&
438 CE->getOperand(1)->isNullValue()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000439 Type *Ty =
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000440 cast<PointerType>(CE->getOperand(0)->getType())->getElementType();
441 // Ignore vector types here so that ScalarEvolutionExpander doesn't
442 // emit getelementptrs that index into vectors.
Duncan Sands19d0b472010-02-16 11:11:14 +0000443 if (Ty->isStructTy() || Ty->isArrayTy()) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000444 CTy = Ty;
445 FieldNo = CE->getOperand(2);
446 return true;
447 }
448 }
449
450 return false;
451}
452
Chris Lattnereb3e8402004-06-20 06:23:15 +0000453//===----------------------------------------------------------------------===//
454// SCEV Utilities
455//===----------------------------------------------------------------------===//
456
457namespace {
458 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
459 /// than the complexity of the RHS. This comparator is used to canonicalize
460 /// expressions.
Nick Lewycky02d5f772009-10-25 06:33:48 +0000461 class SCEVComplexityCompare {
Dan Gohman3324b9e2010-08-13 20:17:27 +0000462 const LoopInfo *const LI;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000463 public:
Dan Gohman992db002010-07-23 21:18:55 +0000464 explicit SCEVComplexityCompare(const LoopInfo *li) : LI(li) {}
Dan Gohman9ba542c2009-05-07 14:39:04 +0000465
Dan Gohman27065672010-08-27 15:26:01 +0000466 // Return true or false if LHS is less than, or at least RHS, respectively.
Dan Gohman5e6ce7b2008-04-14 18:23:56 +0000467 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman27065672010-08-27 15:26:01 +0000468 return compare(LHS, RHS) < 0;
469 }
470
471 // Return negative, zero, or positive, if LHS is less than, equal to, or
472 // greater than RHS, respectively. A three-way result allows recursive
473 // comparisons to be more efficient.
474 int compare(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000475 // Fast-path: SCEVs are uniqued so we can do a quick equality check.
476 if (LHS == RHS)
Dan Gohman27065672010-08-27 15:26:01 +0000477 return 0;
Dan Gohmancc2f1eb2009-08-31 21:15:23 +0000478
Dan Gohman9ba542c2009-05-07 14:39:04 +0000479 // Primarily, sort the SCEVs by their getSCEVType().
Dan Gohman5ae31022010-07-23 21:20:52 +0000480 unsigned LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
481 if (LType != RType)
Dan Gohman27065672010-08-27 15:26:01 +0000482 return (int)LType - (int)RType;
Dan Gohman9ba542c2009-05-07 14:39:04 +0000483
Dan Gohman24ceda82010-06-18 19:54:20 +0000484 // Aside from the getSCEVType() ordering, the particular ordering
485 // isn't very important except that it's beneficial to be consistent,
486 // so that (a + b) and (b + a) don't end up as different expressions.
Benjamin Kramer987b8502014-02-11 19:02:55 +0000487 switch (static_cast<SCEVTypes>(LType)) {
Dan Gohman27065672010-08-27 15:26:01 +0000488 case scUnknown: {
489 const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000490 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000491
492 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
493 // not as complete as it could be.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000494 const Value *LV = LU->getValue(), *RV = RU->getValue();
Dan Gohman24ceda82010-06-18 19:54:20 +0000495
496 // Order pointer values after integer values. This helps SCEVExpander
497 // form GEPs.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000498 bool LIsPointer = LV->getType()->isPointerTy(),
499 RIsPointer = RV->getType()->isPointerTy();
Dan Gohman5ae31022010-07-23 21:20:52 +0000500 if (LIsPointer != RIsPointer)
Dan Gohman27065672010-08-27 15:26:01 +0000501 return (int)LIsPointer - (int)RIsPointer;
Dan Gohman24ceda82010-06-18 19:54:20 +0000502
503 // Compare getValueID values.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000504 unsigned LID = LV->getValueID(),
505 RID = RV->getValueID();
Dan Gohman5ae31022010-07-23 21:20:52 +0000506 if (LID != RID)
Dan Gohman27065672010-08-27 15:26:01 +0000507 return (int)LID - (int)RID;
Dan Gohman24ceda82010-06-18 19:54:20 +0000508
509 // Sort arguments by their position.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000510 if (const Argument *LA = dyn_cast<Argument>(LV)) {
511 const Argument *RA = cast<Argument>(RV);
Dan Gohman27065672010-08-27 15:26:01 +0000512 unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
513 return (int)LArgNo - (int)RArgNo;
Dan Gohman24ceda82010-06-18 19:54:20 +0000514 }
515
Dan Gohman27065672010-08-27 15:26:01 +0000516 // For instructions, compare their loop depth, and their operand
517 // count. This is pretty loose.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000518 if (const Instruction *LInst = dyn_cast<Instruction>(LV)) {
519 const Instruction *RInst = cast<Instruction>(RV);
Dan Gohman24ceda82010-06-18 19:54:20 +0000520
521 // Compare loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000522 const BasicBlock *LParent = LInst->getParent(),
523 *RParent = RInst->getParent();
524 if (LParent != RParent) {
525 unsigned LDepth = LI->getLoopDepth(LParent),
526 RDepth = LI->getLoopDepth(RParent);
527 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000528 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000529 }
Dan Gohman24ceda82010-06-18 19:54:20 +0000530
531 // Compare the number of operands.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000532 unsigned LNumOps = LInst->getNumOperands(),
533 RNumOps = RInst->getNumOperands();
Dan Gohman27065672010-08-27 15:26:01 +0000534 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000535 }
536
Dan Gohman27065672010-08-27 15:26:01 +0000537 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000538 }
539
Dan Gohman27065672010-08-27 15:26:01 +0000540 case scConstant: {
541 const SCEVConstant *LC = cast<SCEVConstant>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000542 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000543
544 // Compare constant values.
Dan Gohmanf2961822010-08-16 16:25:35 +0000545 const APInt &LA = LC->getValue()->getValue();
546 const APInt &RA = RC->getValue()->getValue();
547 unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
Dan Gohman5ae31022010-07-23 21:20:52 +0000548 if (LBitWidth != RBitWidth)
Dan Gohman27065672010-08-27 15:26:01 +0000549 return (int)LBitWidth - (int)RBitWidth;
550 return LA.ult(RA) ? -1 : 1;
Dan Gohman24ceda82010-06-18 19:54:20 +0000551 }
552
Dan Gohman27065672010-08-27 15:26:01 +0000553 case scAddRecExpr: {
554 const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000555 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000556
557 // Compare addrec loop depths.
Dan Gohman0c436ab2010-08-13 21:24:58 +0000558 const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
559 if (LLoop != RLoop) {
560 unsigned LDepth = LLoop->getLoopDepth(),
561 RDepth = RLoop->getLoopDepth();
562 if (LDepth != RDepth)
Dan Gohman27065672010-08-27 15:26:01 +0000563 return (int)LDepth - (int)RDepth;
Dan Gohman0c436ab2010-08-13 21:24:58 +0000564 }
Dan Gohman27065672010-08-27 15:26:01 +0000565
566 // Addrec complexity grows with operand count.
567 unsigned LNumOps = LA->getNumOperands(), RNumOps = RA->getNumOperands();
568 if (LNumOps != RNumOps)
569 return (int)LNumOps - (int)RNumOps;
570
571 // Lexicographically compare.
572 for (unsigned i = 0; i != LNumOps; ++i) {
573 long X = compare(LA->getOperand(i), RA->getOperand(i));
574 if (X != 0)
575 return X;
576 }
577
578 return 0;
Dan Gohman24ceda82010-06-18 19:54:20 +0000579 }
580
Dan Gohman27065672010-08-27 15:26:01 +0000581 case scAddExpr:
582 case scMulExpr:
583 case scSMaxExpr:
584 case scUMaxExpr: {
585 const SCEVNAryExpr *LC = cast<SCEVNAryExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000586 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000587
588 // Lexicographically compare n-ary expressions.
Dan Gohman5ae31022010-07-23 21:20:52 +0000589 unsigned LNumOps = LC->getNumOperands(), RNumOps = RC->getNumOperands();
Andrew Trickc3bc8b82013-07-31 02:43:40 +0000590 if (LNumOps != RNumOps)
591 return (int)LNumOps - (int)RNumOps;
592
Dan Gohman5ae31022010-07-23 21:20:52 +0000593 for (unsigned i = 0; i != LNumOps; ++i) {
594 if (i >= RNumOps)
Dan Gohman27065672010-08-27 15:26:01 +0000595 return 1;
596 long X = compare(LC->getOperand(i), RC->getOperand(i));
597 if (X != 0)
598 return X;
Dan Gohman24ceda82010-06-18 19:54:20 +0000599 }
Dan Gohman27065672010-08-27 15:26:01 +0000600 return (int)LNumOps - (int)RNumOps;
Dan Gohman24ceda82010-06-18 19:54:20 +0000601 }
602
Dan Gohman27065672010-08-27 15:26:01 +0000603 case scUDivExpr: {
604 const SCEVUDivExpr *LC = cast<SCEVUDivExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000605 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000606
607 // Lexicographically compare udiv expressions.
608 long X = compare(LC->getLHS(), RC->getLHS());
609 if (X != 0)
610 return X;
611 return compare(LC->getRHS(), RC->getRHS());
Dan Gohman24ceda82010-06-18 19:54:20 +0000612 }
613
Dan Gohman27065672010-08-27 15:26:01 +0000614 case scTruncate:
615 case scZeroExtend:
616 case scSignExtend: {
617 const SCEVCastExpr *LC = cast<SCEVCastExpr>(LHS);
Dan Gohman24ceda82010-06-18 19:54:20 +0000618 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
Dan Gohman27065672010-08-27 15:26:01 +0000619
620 // Compare cast expressions by operand.
621 return compare(LC->getOperand(), RC->getOperand());
622 }
623
Benjamin Kramer987b8502014-02-11 19:02:55 +0000624 case scCouldNotCompute:
625 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman24ceda82010-06-18 19:54:20 +0000626 }
Benjamin Kramer987b8502014-02-11 19:02:55 +0000627 llvm_unreachable("Unknown SCEV kind!");
Chris Lattnereb3e8402004-06-20 06:23:15 +0000628 }
629 };
630}
631
632/// GroupByComplexity - Given a list of SCEV objects, order them by their
633/// complexity, and group objects of the same complexity together by value.
634/// When this routine is finished, we know that any duplicates in the vector are
635/// consecutive and that complexity is monotonically increasing.
636///
Dan Gohman8b0a4192010-03-01 17:49:51 +0000637/// Note that we go take special precautions to ensure that we get deterministic
Chris Lattnereb3e8402004-06-20 06:23:15 +0000638/// results from this routine. In other words, we don't want the results of
639/// this to depend on where the addresses of various SCEV objects happened to
640/// land in memory.
641///
Dan Gohmanaf752342009-07-07 17:06:11 +0000642static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
Dan Gohman9ba542c2009-05-07 14:39:04 +0000643 LoopInfo *LI) {
Chris Lattnereb3e8402004-06-20 06:23:15 +0000644 if (Ops.size() < 2) return; // Noop
645 if (Ops.size() == 2) {
646 // This is the common case, which also happens to be trivially simple.
647 // Special case it.
Dan Gohman7712d292010-08-29 15:07:13 +0000648 const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
649 if (SCEVComplexityCompare(LI)(RHS, LHS))
650 std::swap(LHS, RHS);
Chris Lattnereb3e8402004-06-20 06:23:15 +0000651 return;
652 }
653
Dan Gohman24ceda82010-06-18 19:54:20 +0000654 // Do the rough sort by complexity.
655 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
656
657 // Now that we are sorted by complexity, group elements of the same
658 // complexity. Note that this is, at worst, N^2, but the vector is likely to
659 // be extremely short in practice. Note that we take this approach because we
660 // do not want to depend on the addresses of the objects we are grouping.
661 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
662 const SCEV *S = Ops[i];
663 unsigned Complexity = S->getSCEVType();
664
665 // If there are any objects of the same complexity and same value as this
666 // one, group them.
667 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
668 if (Ops[j] == S) { // Found a duplicate.
669 // Move it to immediately after i'th element.
670 std::swap(Ops[i+1], Ops[j]);
671 ++i; // no need to rescan it.
672 if (i == e-2) return; // Done!
673 }
674 }
675 }
Chris Lattnereb3e8402004-06-20 06:23:15 +0000676}
677
Mark Heffernan2beab5f2014-10-10 17:39:11 +0000678static const APInt srem(const SCEVConstant *C1, const SCEVConstant *C2) {
679 APInt A = C1->getValue()->getValue();
680 APInt B = C2->getValue()->getValue();
681 uint32_t ABW = A.getBitWidth();
682 uint32_t BBW = B.getBitWidth();
683
684 if (ABW > BBW)
685 B = B.sext(ABW);
686 else if (ABW < BBW)
687 A = A.sext(BBW);
688
689 return APIntOps::srem(A, B);
690}
691
692static const APInt sdiv(const SCEVConstant *C1, const SCEVConstant *C2) {
693 APInt A = C1->getValue()->getValue();
694 APInt B = C2->getValue()->getValue();
695 uint32_t ABW = A.getBitWidth();
696 uint32_t BBW = B.getBitWidth();
697
698 if (ABW > BBW)
699 B = B.sext(ABW);
700 else if (ABW < BBW)
701 A = A.sext(BBW);
702
703 return APIntOps::sdiv(A, B);
704}
705
706namespace {
707struct FindSCEVSize {
708 int Size;
709 FindSCEVSize() : Size(0) {}
710
711 bool follow(const SCEV *S) {
712 ++Size;
713 // Keep looking at all operands of S.
714 return true;
715 }
716 bool isDone() const {
717 return false;
718 }
719};
720}
721
722// Returns the size of the SCEV S.
723static inline int sizeOfSCEV(const SCEV *S) {
724 FindSCEVSize F;
725 SCEVTraversal<FindSCEVSize> ST(F);
726 ST.visitAll(S);
727 return F.Size;
728}
729
730namespace {
731
732struct SCEVDivision : public SCEVVisitor<SCEVDivision, void> {
733public:
734 // Computes the Quotient and Remainder of the division of Numerator by
735 // Denominator.
736 static void divide(ScalarEvolution &SE, const SCEV *Numerator,
737 const SCEV *Denominator, const SCEV **Quotient,
738 const SCEV **Remainder) {
739 assert(Numerator && Denominator && "Uninitialized SCEV");
740
741 SCEVDivision D(SE, Numerator, Denominator);
742
743 // Check for the trivial case here to avoid having to check for it in the
744 // rest of the code.
745 if (Numerator == Denominator) {
746 *Quotient = D.One;
747 *Remainder = D.Zero;
748 return;
749 }
750
751 if (Numerator->isZero()) {
752 *Quotient = D.Zero;
753 *Remainder = D.Zero;
754 return;
755 }
756
757 // Split the Denominator when it is a product.
758 if (const SCEVMulExpr *T = dyn_cast<const SCEVMulExpr>(Denominator)) {
759 const SCEV *Q, *R;
760 *Quotient = Numerator;
761 for (const SCEV *Op : T->operands()) {
762 divide(SE, *Quotient, Op, &Q, &R);
763 *Quotient = Q;
764
765 // Bail out when the Numerator is not divisible by one of the terms of
766 // the Denominator.
767 if (!R->isZero()) {
768 *Quotient = D.Zero;
769 *Remainder = Numerator;
770 return;
771 }
772 }
773 *Remainder = D.Zero;
774 return;
775 }
776
777 D.visit(Numerator);
778 *Quotient = D.Quotient;
779 *Remainder = D.Remainder;
780 }
781
782 SCEVDivision(ScalarEvolution &S, const SCEV *Numerator, const SCEV *Denominator)
783 : SE(S), Denominator(Denominator) {
784 Zero = SE.getConstant(Denominator->getType(), 0);
785 One = SE.getConstant(Denominator->getType(), 1);
786
787 // By default, we don't know how to divide Expr by Denominator.
788 // Providing the default here simplifies the rest of the code.
789 Quotient = Zero;
790 Remainder = Numerator;
791 }
792
793 // Except in the trivial case described above, we do not know how to divide
794 // Expr by Denominator for the following functions with empty implementation.
795 void visitTruncateExpr(const SCEVTruncateExpr *Numerator) {}
796 void visitZeroExtendExpr(const SCEVZeroExtendExpr *Numerator) {}
797 void visitSignExtendExpr(const SCEVSignExtendExpr *Numerator) {}
798 void visitUDivExpr(const SCEVUDivExpr *Numerator) {}
799 void visitSMaxExpr(const SCEVSMaxExpr *Numerator) {}
800 void visitUMaxExpr(const SCEVUMaxExpr *Numerator) {}
801 void visitUnknown(const SCEVUnknown *Numerator) {}
802 void visitCouldNotCompute(const SCEVCouldNotCompute *Numerator) {}
803
804 void visitConstant(const SCEVConstant *Numerator) {
805 if (const SCEVConstant *D = dyn_cast<SCEVConstant>(Denominator)) {
806 Quotient = SE.getConstant(sdiv(Numerator, D));
807 Remainder = SE.getConstant(srem(Numerator, D));
808 return;
809 }
810 }
811
812 void visitAddRecExpr(const SCEVAddRecExpr *Numerator) {
813 const SCEV *StartQ, *StartR, *StepQ, *StepR;
814 assert(Numerator->isAffine() && "Numerator should be affine");
815 divide(SE, Numerator->getStart(), Denominator, &StartQ, &StartR);
816 divide(SE, Numerator->getStepRecurrence(SE), Denominator, &StepQ, &StepR);
817 Quotient = SE.getAddRecExpr(StartQ, StepQ, Numerator->getLoop(),
818 Numerator->getNoWrapFlags());
819 Remainder = SE.getAddRecExpr(StartR, StepR, Numerator->getLoop(),
820 Numerator->getNoWrapFlags());
821 }
822
823 void visitAddExpr(const SCEVAddExpr *Numerator) {
824 SmallVector<const SCEV *, 2> Qs, Rs;
825 Type *Ty = Denominator->getType();
826
827 for (const SCEV *Op : Numerator->operands()) {
828 const SCEV *Q, *R;
829 divide(SE, Op, Denominator, &Q, &R);
830
831 // Bail out if types do not match.
832 if (Ty != Q->getType() || Ty != R->getType()) {
833 Quotient = Zero;
834 Remainder = Numerator;
835 return;
836 }
837
838 Qs.push_back(Q);
839 Rs.push_back(R);
840 }
841
842 if (Qs.size() == 1) {
843 Quotient = Qs[0];
844 Remainder = Rs[0];
845 return;
846 }
847
848 Quotient = SE.getAddExpr(Qs);
849 Remainder = SE.getAddExpr(Rs);
850 }
851
852 void visitMulExpr(const SCEVMulExpr *Numerator) {
853 SmallVector<const SCEV *, 2> Qs;
854 Type *Ty = Denominator->getType();
855
856 bool FoundDenominatorTerm = false;
857 for (const SCEV *Op : Numerator->operands()) {
858 // Bail out if types do not match.
859 if (Ty != Op->getType()) {
860 Quotient = Zero;
861 Remainder = Numerator;
862 return;
863 }
864
865 if (FoundDenominatorTerm) {
866 Qs.push_back(Op);
867 continue;
868 }
869
870 // Check whether Denominator divides one of the product operands.
871 const SCEV *Q, *R;
872 divide(SE, Op, Denominator, &Q, &R);
873 if (!R->isZero()) {
874 Qs.push_back(Op);
875 continue;
876 }
877
878 // Bail out if types do not match.
879 if (Ty != Q->getType()) {
880 Quotient = Zero;
881 Remainder = Numerator;
882 return;
883 }
884
885 FoundDenominatorTerm = true;
886 Qs.push_back(Q);
887 }
888
889 if (FoundDenominatorTerm) {
890 Remainder = Zero;
891 if (Qs.size() == 1)
892 Quotient = Qs[0];
893 else
894 Quotient = SE.getMulExpr(Qs);
895 return;
896 }
897
898 if (!isa<SCEVUnknown>(Denominator)) {
899 Quotient = Zero;
900 Remainder = Numerator;
901 return;
902 }
903
904 // The Remainder is obtained by replacing Denominator by 0 in Numerator.
905 ValueToValueMap RewriteMap;
906 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
907 cast<SCEVConstant>(Zero)->getValue();
908 Remainder = SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
909
910 if (Remainder->isZero()) {
911 // The Quotient is obtained by replacing Denominator by 1 in Numerator.
912 RewriteMap[cast<SCEVUnknown>(Denominator)->getValue()] =
913 cast<SCEVConstant>(One)->getValue();
914 Quotient =
915 SCEVParameterRewriter::rewrite(Numerator, SE, RewriteMap, true);
916 return;
917 }
918
919 // Quotient is (Numerator - Remainder) divided by Denominator.
920 const SCEV *Q, *R;
921 const SCEV *Diff = SE.getMinusSCEV(Numerator, Remainder);
922 if (sizeOfSCEV(Diff) > sizeOfSCEV(Numerator)) {
923 // This SCEV does not seem to simplify: fail the division here.
924 Quotient = Zero;
925 Remainder = Numerator;
926 return;
927 }
928 divide(SE, Diff, Denominator, &Q, &R);
929 assert(R == Zero &&
930 "(Numerator - Remainder) should evenly divide Denominator");
931 Quotient = Q;
932 }
933
934private:
935 ScalarEvolution &SE;
936 const SCEV *Denominator, *Quotient, *Remainder, *Zero, *One;
937};
938}
939
Chris Lattnerd934c702004-04-02 20:23:17 +0000940
Chris Lattnerd934c702004-04-02 20:23:17 +0000941
942//===----------------------------------------------------------------------===//
943// Simple SCEV method implementations
944//===----------------------------------------------------------------------===//
945
Eli Friedman61f67622008-08-04 23:49:06 +0000946/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohman4d5435d2009-05-24 23:45:28 +0000947/// Assume, K > 0.
Dan Gohmanaf752342009-07-07 17:06:11 +0000948static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
Dan Gohman32291b12009-07-21 00:38:55 +0000949 ScalarEvolution &SE,
Nick Lewycky702cf1e2011-09-06 06:39:54 +0000950 Type *ResultTy) {
Eli Friedman61f67622008-08-04 23:49:06 +0000951 // Handle the simplest case efficiently.
952 if (K == 1)
953 return SE.getTruncateOrZeroExtend(It, ResultTy);
954
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000955 // We are using the following formula for BC(It, K):
956 //
957 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
958 //
Eli Friedman61f67622008-08-04 23:49:06 +0000959 // Suppose, W is the bitwidth of the return value. We must be prepared for
960 // overflow. Hence, we must assure that the result of our computation is
961 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
962 // safe in modular arithmetic.
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000963 //
Eli Friedman61f67622008-08-04 23:49:06 +0000964 // However, this code doesn't use exactly that formula; the formula it uses
Dan Gohmance973df2009-06-24 04:48:43 +0000965 // is something like the following, where T is the number of factors of 2 in
Eli Friedman61f67622008-08-04 23:49:06 +0000966 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
967 // exponentiation:
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000968 //
Eli Friedman61f67622008-08-04 23:49:06 +0000969 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +0000970 //
Eli Friedman61f67622008-08-04 23:49:06 +0000971 // This formula is trivially equivalent to the previous formula. However,
972 // this formula can be implemented much more efficiently. The trick is that
973 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
974 // arithmetic. To do exact division in modular arithmetic, all we have
975 // to do is multiply by the inverse. Therefore, this step can be done at
976 // width W.
Dan Gohmance973df2009-06-24 04:48:43 +0000977 //
Eli Friedman61f67622008-08-04 23:49:06 +0000978 // The next issue is how to safely do the division by 2^T. The way this
979 // is done is by doing the multiplication step at a width of at least W + T
980 // bits. This way, the bottom W+T bits of the product are accurate. Then,
981 // when we perform the division by 2^T (which is equivalent to a right shift
982 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
983 // truncated out after the division by 2^T.
984 //
985 // In comparison to just directly using the first formula, this technique
986 // is much more efficient; using the first formula requires W * K bits,
987 // but this formula less than W + K bits. Also, the first formula requires
988 // a division step, whereas this formula only requires multiplies and shifts.
989 //
990 // It doesn't matter whether the subtraction step is done in the calculation
991 // width or the input iteration count's width; if the subtraction overflows,
992 // the result must be zero anyway. We prefer here to do it in the width of
993 // the induction variable because it helps a lot for certain cases; CodeGen
994 // isn't smart enough to ignore the overflow, which leads to much less
995 // efficient code if the width of the subtraction is wider than the native
996 // register width.
997 //
998 // (It's possible to not widen at all by pulling out factors of 2 before
999 // the multiplication; for example, K=2 can be calculated as
1000 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
1001 // extra arithmetic, so it's not an obvious win, and it gets
1002 // much more complicated for K > 3.)
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001003
Eli Friedman61f67622008-08-04 23:49:06 +00001004 // Protection from insane SCEVs; this bound is conservative,
1005 // but it probably doesn't matter.
1006 if (K > 1000)
Dan Gohman31efa302009-04-18 17:58:19 +00001007 return SE.getCouldNotCompute();
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001008
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001009 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001010
Eli Friedman61f67622008-08-04 23:49:06 +00001011 // Calculate K! / 2^T and T; we divide out the factors of two before
1012 // multiplying for calculating K! / 2^T to avoid overflow.
1013 // Other overflow doesn't matter because we only care about the bottom
1014 // W bits of the result.
1015 APInt OddFactorial(W, 1);
1016 unsigned T = 1;
1017 for (unsigned i = 3; i <= K; ++i) {
1018 APInt Mult(W, i);
1019 unsigned TwoFactors = Mult.countTrailingZeros();
1020 T += TwoFactors;
1021 Mult = Mult.lshr(TwoFactors);
1022 OddFactorial *= Mult;
Chris Lattnerd934c702004-04-02 20:23:17 +00001023 }
Nick Lewyckyed169d52008-06-13 04:38:55 +00001024
Eli Friedman61f67622008-08-04 23:49:06 +00001025 // We need at least W + T bits for the multiplication step
Nick Lewycky21add8f2009-01-25 08:16:27 +00001026 unsigned CalculationBits = W + T;
Eli Friedman61f67622008-08-04 23:49:06 +00001027
Dan Gohman8b0a4192010-03-01 17:49:51 +00001028 // Calculate 2^T, at width T+W.
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00001029 APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
Eli Friedman61f67622008-08-04 23:49:06 +00001030
1031 // Calculate the multiplicative inverse of K! / 2^T;
1032 // this multiplication factor will perform the exact division by
1033 // K! / 2^T.
1034 APInt Mod = APInt::getSignedMinValue(W+1);
1035 APInt MultiplyFactor = OddFactorial.zext(W+1);
1036 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
1037 MultiplyFactor = MultiplyFactor.trunc(W);
1038
1039 // Calculate the product, at width T+W
Chris Lattner229907c2011-07-18 04:54:35 +00001040 IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
Owen Anderson55f1c092009-08-13 21:58:54 +00001041 CalculationBits);
Dan Gohmanaf752342009-07-07 17:06:11 +00001042 const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman61f67622008-08-04 23:49:06 +00001043 for (unsigned i = 1; i != K; ++i) {
Dan Gohman1d2ded72010-05-03 22:09:21 +00001044 const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
Eli Friedman61f67622008-08-04 23:49:06 +00001045 Dividend = SE.getMulExpr(Dividend,
1046 SE.getTruncateOrZeroExtend(S, CalculationTy));
1047 }
1048
1049 // Divide by 2^T
Dan Gohmanaf752342009-07-07 17:06:11 +00001050 const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman61f67622008-08-04 23:49:06 +00001051
1052 // Truncate the result, and divide by K! / 2^T.
1053
1054 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
1055 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Chris Lattnerd934c702004-04-02 20:23:17 +00001056}
1057
Chris Lattnerd934c702004-04-02 20:23:17 +00001058/// evaluateAtIteration - Return the value of this chain of recurrences at
1059/// the specified iteration number. We can evaluate this recurrence by
1060/// multiplying each element in the chain by the binomial coefficient
1061/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
1062///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001063/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Chris Lattnerd934c702004-04-02 20:23:17 +00001064///
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001065/// where BC(It, k) stands for binomial coefficient.
Chris Lattnerd934c702004-04-02 20:23:17 +00001066///
Dan Gohmanaf752342009-07-07 17:06:11 +00001067const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
Dan Gohman32291b12009-07-21 00:38:55 +00001068 ScalarEvolution &SE) const {
Dan Gohmanaf752342009-07-07 17:06:11 +00001069 const SCEV *Result = getStart();
Chris Lattnerd934c702004-04-02 20:23:17 +00001070 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewiczd2d97642008-02-11 11:03:14 +00001071 // The computation is correct in the face of overflow provided that the
1072 // multiplication is performed _after_ the evaluation of the binomial
1073 // coefficient.
Dan Gohmanaf752342009-07-07 17:06:11 +00001074 const SCEV *Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewycky707663e2008-10-13 03:58:02 +00001075 if (isa<SCEVCouldNotCompute>(Coeff))
1076 return Coeff;
1077
1078 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Chris Lattnerd934c702004-04-02 20:23:17 +00001079 }
1080 return Result;
1081}
1082
Chris Lattnerd934c702004-04-02 20:23:17 +00001083//===----------------------------------------------------------------------===//
1084// SCEV Expression folder implementations
1085//===----------------------------------------------------------------------===//
1086
Dan Gohmanaf752342009-07-07 17:06:11 +00001087const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001088 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001089 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001090 "This is not a truncating conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001091 assert(isSCEVable(Ty) &&
1092 "This is not a conversion to a SCEVable type!");
1093 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001094
Dan Gohman3a302cb2009-07-13 20:50:19 +00001095 FoldingSetNodeID ID;
1096 ID.AddInteger(scTruncate);
1097 ID.AddPointer(Op);
1098 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001099 void *IP = nullptr;
Dan Gohman3a302cb2009-07-13 20:50:19 +00001100 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1101
Dan Gohman3423e722009-06-30 20:13:32 +00001102 // Fold if the operand is constant.
Dan Gohmana30370b2009-05-04 22:02:23 +00001103 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman8d7576e2009-06-24 00:38:39 +00001104 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001105 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001106
Dan Gohman79af8542009-04-22 16:20:48 +00001107 // trunc(trunc(x)) --> trunc(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001108 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001109 return getTruncateExpr(ST->getOperand(), Ty);
1110
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001111 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001112 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001113 return getTruncateOrSignExtend(SS->getOperand(), Ty);
1114
1115 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmana30370b2009-05-04 22:02:23 +00001116 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewyckyb4d9f7a2009-04-23 05:15:08 +00001117 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
1118
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001119 // trunc(x1+x2+...+xN) --> trunc(x1)+trunc(x2)+...+trunc(xN) if we can
1120 // eliminate all the truncates.
1121 if (const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Op)) {
1122 SmallVector<const SCEV *, 4> Operands;
1123 bool hasTrunc = false;
1124 for (unsigned i = 0, e = SA->getNumOperands(); i != e && !hasTrunc; ++i) {
1125 const SCEV *S = getTruncateExpr(SA->getOperand(i), Ty);
1126 hasTrunc = isa<SCEVTruncateExpr>(S);
1127 Operands.push_back(S);
1128 }
1129 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001130 return getAddExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001131 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5143f0f2011-01-19 16:59:46 +00001132 }
1133
Nick Lewycky5c901f32011-01-19 18:56:00 +00001134 // trunc(x1*x2*...*xN) --> trunc(x1)*trunc(x2)*...*trunc(xN) if we can
1135 // eliminate all the truncates.
1136 if (const SCEVMulExpr *SM = dyn_cast<SCEVMulExpr>(Op)) {
1137 SmallVector<const SCEV *, 4> Operands;
1138 bool hasTrunc = false;
1139 for (unsigned i = 0, e = SM->getNumOperands(); i != e && !hasTrunc; ++i) {
1140 const SCEV *S = getTruncateExpr(SM->getOperand(i), Ty);
1141 hasTrunc = isa<SCEVTruncateExpr>(S);
1142 Operands.push_back(S);
1143 }
1144 if (!hasTrunc)
Andrew Trick8b55b732011-03-14 16:50:06 +00001145 return getMulExpr(Operands);
Nick Lewyckyd9e6b4a2011-01-26 08:40:22 +00001146 UniqueSCEVs.FindNodeOrInsertPos(ID, IP); // Mutates IP, returns NULL.
Nick Lewycky5c901f32011-01-19 18:56:00 +00001147 }
1148
Dan Gohman5a728c92009-06-18 16:24:47 +00001149 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmana30370b2009-05-04 22:02:23 +00001150 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001151 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00001152 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman2e55cc52009-05-08 21:03:19 +00001153 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Andrew Trick8b55b732011-03-14 16:50:06 +00001154 return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00001155 }
1156
Dan Gohman89dd42a2010-06-25 18:47:08 +00001157 // The cast wasn't folded; create an explicit cast node. We can reuse
1158 // the existing insert position since if we get here, we won't have
1159 // made any changes which would invalidate it.
Dan Gohman01c65a22010-03-18 18:49:47 +00001160 SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
1161 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001162 UniqueSCEVs.InsertNode(S, IP);
1163 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001164}
1165
Dan Gohmanaf752342009-07-07 17:06:11 +00001166const SCEV *ScalarEvolution::getZeroExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001167 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001168 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001169 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001170 assert(isSCEVable(Ty) &&
1171 "This is not a conversion to a SCEVable type!");
1172 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanc1c2ba72009-04-16 19:25:55 +00001173
Dan Gohman3423e722009-06-30 20:13:32 +00001174 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001175 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1176 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001177 cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
Chris Lattnerd934c702004-04-02 20:23:17 +00001178
Dan Gohman79af8542009-04-22 16:20:48 +00001179 // zext(zext(x)) --> zext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001180 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001181 return getZeroExtendExpr(SZ->getOperand(), Ty);
1182
Dan Gohman74a0ba12009-07-13 20:55:53 +00001183 // Before doing any expensive analysis, check to see if we've already
1184 // computed a SCEV for this Op and Ty.
1185 FoldingSetNodeID ID;
1186 ID.AddInteger(scZeroExtend);
1187 ID.AddPointer(Op);
1188 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001189 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001190 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1191
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001192 // zext(trunc(x)) --> zext(x) or x or trunc(x)
1193 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1194 // It's possible the bits taken off by the truncate were all zero bits. If
1195 // so, we should be able to simplify this further.
1196 const SCEV *X = ST->getOperand();
1197 ConstantRange CR = getUnsignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001198 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1199 unsigned NewBits = getTypeSizeInBits(Ty);
1200 if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001201 CR.zextOrTrunc(NewBits)))
1202 return getTruncateOrZeroExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001203 }
1204
Dan Gohman76466372009-04-27 20:16:15 +00001205 // If the input value is a chrec scev, and we can prove that the value
Chris Lattnerd934c702004-04-02 20:23:17 +00001206 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001207 // operands (often constants). This allows analysis of something like
Chris Lattnerd934c702004-04-02 20:23:17 +00001208 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001209 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001210 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001211 const SCEV *Start = AR->getStart();
1212 const SCEV *Step = AR->getStepRecurrence(*this);
1213 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1214 const Loop *L = AR->getLoop();
1215
Dan Gohman62ef6a72009-07-25 01:22:26 +00001216 // If we have special knowledge that this addrec won't overflow,
1217 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001218 if (AR->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohman62ef6a72009-07-25 01:22:26 +00001219 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1220 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001221 L, AR->getNoWrapFlags());
Dan Gohman62ef6a72009-07-25 01:22:26 +00001222
Dan Gohman76466372009-04-27 20:16:15 +00001223 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1224 // Note that this serves two purposes: It filters out loops that are
1225 // simply not analyzable, and it covers the case where this code is
1226 // being called from within backedge-taken count analysis, such that
1227 // attempting to ask for the backedge-taken count would likely result
1228 // in infinite recursion. In the later case, the analysis code will
1229 // cope with a conservative value, and it will take care to purge
1230 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001231 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001232 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001233 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001234 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001235
1236 // Check whether the backedge-taken count can be losslessly casted to
1237 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001238 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001239 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001240 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001241 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1242 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001243 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001244 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001245 const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001246 const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul), WideTy);
1247 const SCEV *WideStart = getZeroExtendExpr(Start, WideTy);
1248 const SCEV *WideMaxBECount =
1249 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001250 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001251 getAddExpr(WideStart,
1252 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001253 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001254 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001255 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1256 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohman494dac32009-04-29 22:28:28 +00001257 // Return the expression with the addrec on the outside.
1258 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1259 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001260 L, AR->getNoWrapFlags());
1261 }
Dan Gohman76466372009-04-27 20:16:15 +00001262 // Similar to above, only this time treat the step value as signed.
1263 // This covers loops that count down.
Dan Gohman4fc36682009-05-18 15:58:39 +00001264 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001265 getAddExpr(WideStart,
1266 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001267 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001268 if (ZAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001269 // Cache knowledge of AR NW, which is propagated to this AddRec.
1270 // Negative step causes unsigned wrap, but it still can't self-wrap.
1271 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
Dan Gohman494dac32009-04-29 22:28:28 +00001272 // Return the expression with the addrec on the outside.
1273 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1274 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001275 L, AR->getNoWrapFlags());
1276 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001277 }
1278
1279 // If the backedge is guarded by a comparison with the pre-inc value
1280 // the addrec is safe. Also, if the entry is guarded by a comparison
1281 // with the start value and the backedge is guarded by a comparison
1282 // with the post-inc value, the addrec is safe.
1283 if (isKnownPositive(Step)) {
1284 const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
1285 getUnsignedRange(Step).getUnsignedMax());
1286 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
Dan Gohmanb50349a2010-04-11 19:27:13 +00001287 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_ULT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001288 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001289 AR->getPostIncExpr(*this), N))) {
1290 // Cache knowledge of AR NUW, which is propagated to this AddRec.
1291 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNUW);
Dan Gohmane65c9172009-07-13 21:35:55 +00001292 // Return the expression with the addrec on the outside.
1293 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1294 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001295 L, AR->getNoWrapFlags());
1296 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001297 } else if (isKnownNegative(Step)) {
1298 const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
1299 getSignedRange(Step).getSignedMin());
Dan Gohman5f18c542010-05-04 01:11:15 +00001300 if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
1301 (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_UGT, Start, N) &&
Dan Gohmane65c9172009-07-13 21:35:55 +00001302 isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT,
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001303 AR->getPostIncExpr(*this), N))) {
1304 // Cache knowledge of AR NW, which is propagated to this AddRec.
1305 // Negative step causes unsigned wrap, but it still can't self-wrap.
1306 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNW);
1307 // Return the expression with the addrec on the outside.
Dan Gohmane65c9172009-07-13 21:35:55 +00001308 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
1309 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001310 L, AR->getNoWrapFlags());
1311 }
Dan Gohman76466372009-04-27 20:16:15 +00001312 }
1313 }
1314 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001315
Dan Gohman74a0ba12009-07-13 20:55:53 +00001316 // The cast wasn't folded; create an explicit cast node.
1317 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001318 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001319 SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
1320 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001321 UniqueSCEVs.InsertNode(S, IP);
1322 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00001323}
1324
Andrew Trick812276e2011-05-31 21:17:47 +00001325// Get the limit of a recurrence such that incrementing by Step cannot cause
1326// signed overflow as long as the value of the recurrence within the loop does
1327// not exceed this limit before incrementing.
1328static const SCEV *getOverflowLimitForStep(const SCEV *Step,
1329 ICmpInst::Predicate *Pred,
1330 ScalarEvolution *SE) {
1331 unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
1332 if (SE->isKnownPositive(Step)) {
1333 *Pred = ICmpInst::ICMP_SLT;
1334 return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
1335 SE->getSignedRange(Step).getSignedMax());
1336 }
1337 if (SE->isKnownNegative(Step)) {
1338 *Pred = ICmpInst::ICMP_SGT;
1339 return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
1340 SE->getSignedRange(Step).getSignedMin());
1341 }
Craig Topper9f008862014-04-15 04:59:12 +00001342 return nullptr;
Andrew Trick812276e2011-05-31 21:17:47 +00001343}
1344
1345// The recurrence AR has been shown to have no signed wrap. Typically, if we can
1346// prove NSW for AR, then we can just as easily prove NSW for its preincrement
1347// or postincrement sibling. This allows normalizing a sign extended AddRec as
1348// such: {sext(Step + Start),+,Step} => {(Step + sext(Start),+,Step} As a
1349// result, the expression "Step + sext(PreIncAR)" is congruent with
1350// "sext(PostIncAR)"
1351static const SCEV *getPreStartForSignExtend(const SCEVAddRecExpr *AR,
Chris Lattner229907c2011-07-18 04:54:35 +00001352 Type *Ty,
Andrew Trick812276e2011-05-31 21:17:47 +00001353 ScalarEvolution *SE) {
1354 const Loop *L = AR->getLoop();
1355 const SCEV *Start = AR->getStart();
1356 const SCEV *Step = AR->getStepRecurrence(*SE);
1357
1358 // Check for a simple looking step prior to loop entry.
1359 const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001360 if (!SA)
Craig Topper9f008862014-04-15 04:59:12 +00001361 return nullptr;
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001362
1363 // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
1364 // subtraction is expensive. For this purpose, perform a quick and dirty
1365 // difference, by checking for Step in the operand list.
1366 SmallVector<const SCEV *, 4> DiffOps;
Tobias Grosser924221c2014-05-07 06:07:47 +00001367 for (const SCEV *Op : SA->operands())
1368 if (Op != Step)
1369 DiffOps.push_back(Op);
1370
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001371 if (DiffOps.size() == SA->getNumOperands())
Craig Topper9f008862014-04-15 04:59:12 +00001372 return nullptr;
Andrew Trick812276e2011-05-31 21:17:47 +00001373
1374 // This is a postinc AR. Check for overflow on the preinc recurrence using the
1375 // same three conditions that getSignExtendedExpr checks.
1376
1377 // 1. NSW flags on the step increment.
Andrew Trickef8e4ef2011-09-28 17:02:54 +00001378 const SCEV *PreStart = SE->getAddExpr(DiffOps, SA->getNoWrapFlags());
Andrew Trick812276e2011-05-31 21:17:47 +00001379 const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
1380 SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
1381
Andrew Trick8ef3ad02011-06-01 19:14:56 +00001382 if (PreAR && PreAR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trick812276e2011-05-31 21:17:47 +00001383 return PreStart;
Andrew Trick812276e2011-05-31 21:17:47 +00001384
1385 // 2. Direct overflow check on the step operation's expression.
1386 unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
Chris Lattner229907c2011-07-18 04:54:35 +00001387 Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
Andrew Trick812276e2011-05-31 21:17:47 +00001388 const SCEV *OperandExtendedStart =
1389 SE->getAddExpr(SE->getSignExtendExpr(PreStart, WideTy),
1390 SE->getSignExtendExpr(Step, WideTy));
1391 if (SE->getSignExtendExpr(Start, WideTy) == OperandExtendedStart) {
1392 // Cache knowledge of PreAR NSW.
1393 if (PreAR)
1394 const_cast<SCEVAddRecExpr *>(PreAR)->setNoWrapFlags(SCEV::FlagNSW);
1395 // FIXME: this optimization needs a unit test
1396 DEBUG(dbgs() << "SCEV: untested prestart overflow check\n");
1397 return PreStart;
1398 }
1399
1400 // 3. Loop precondition.
1401 ICmpInst::Predicate Pred;
1402 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, SE);
1403
Andrew Trick8ef3ad02011-06-01 19:14:56 +00001404 if (OverflowLimit &&
1405 SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit)) {
Andrew Trick812276e2011-05-31 21:17:47 +00001406 return PreStart;
1407 }
Craig Topper9f008862014-04-15 04:59:12 +00001408 return nullptr;
Andrew Trick812276e2011-05-31 21:17:47 +00001409}
1410
1411// Get the normalized sign-extended expression for this AddRec's Start.
1412static const SCEV *getSignExtendAddRecStart(const SCEVAddRecExpr *AR,
Chris Lattner229907c2011-07-18 04:54:35 +00001413 Type *Ty,
Andrew Trick812276e2011-05-31 21:17:47 +00001414 ScalarEvolution *SE) {
1415 const SCEV *PreStart = getPreStartForSignExtend(AR, Ty, SE);
1416 if (!PreStart)
1417 return SE->getSignExtendExpr(AR->getStart(), Ty);
1418
1419 return SE->getAddExpr(SE->getSignExtendExpr(AR->getStepRecurrence(*SE), Ty),
1420 SE->getSignExtendExpr(PreStart, Ty));
1421}
1422
Dan Gohmanaf752342009-07-07 17:06:11 +00001423const SCEV *ScalarEvolution::getSignExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001424 Type *Ty) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00001425 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman413e91f2009-04-21 00:55:22 +00001426 "This is not an extending conversion!");
Dan Gohman194e42c2009-05-01 16:44:18 +00001427 assert(isSCEVable(Ty) &&
1428 "This is not a conversion to a SCEVable type!");
1429 Ty = getEffectiveSCEVType(Ty);
Dan Gohman413e91f2009-04-21 00:55:22 +00001430
Dan Gohman3423e722009-06-30 20:13:32 +00001431 // Fold if the operand is constant.
Dan Gohman5235cc22010-06-24 16:47:03 +00001432 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1433 return getConstant(
Nuno Lopesab5c9242012-05-15 15:44:38 +00001434 cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001435
Dan Gohman79af8542009-04-22 16:20:48 +00001436 // sext(sext(x)) --> sext(x)
Dan Gohmana30370b2009-05-04 22:02:23 +00001437 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman79af8542009-04-22 16:20:48 +00001438 return getSignExtendExpr(SS->getOperand(), Ty);
1439
Nick Lewyckye9ea75e2011-01-19 15:56:12 +00001440 // sext(zext(x)) --> zext(x)
1441 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
1442 return getZeroExtendExpr(SZ->getOperand(), Ty);
1443
Dan Gohman74a0ba12009-07-13 20:55:53 +00001444 // Before doing any expensive analysis, check to see if we've already
1445 // computed a SCEV for this Op and Ty.
1446 FoldingSetNodeID ID;
1447 ID.AddInteger(scSignExtend);
1448 ID.AddPointer(Op);
1449 ID.AddPointer(Ty);
Craig Topper9f008862014-04-15 04:59:12 +00001450 void *IP = nullptr;
Dan Gohman74a0ba12009-07-13 20:55:53 +00001451 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
1452
Nick Lewyckyb32c8942011-01-22 22:06:21 +00001453 // If the input value is provably positive, build a zext instead.
1454 if (isKnownNonNegative(Op))
1455 return getZeroExtendExpr(Op, Ty);
1456
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001457 // sext(trunc(x)) --> sext(x) or x or trunc(x)
1458 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
1459 // It's possible the bits taken off by the truncate were all sign bits. If
1460 // so, we should be able to simplify this further.
1461 const SCEV *X = ST->getOperand();
1462 ConstantRange CR = getSignedRange(X);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001463 unsigned TruncBits = getTypeSizeInBits(ST->getType());
1464 unsigned NewBits = getTypeSizeInBits(Ty);
1465 if (CR.truncate(TruncBits).signExtend(NewBits).contains(
Nick Lewyckyd4192f72011-01-23 20:06:05 +00001466 CR.sextOrTrunc(NewBits)))
1467 return getTruncateOrSignExtend(X, Ty);
Nick Lewyckybc98f5b2011-01-23 06:20:19 +00001468 }
1469
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001470 // sext(C1 + (C2 * x)) --> C1 + sext(C2 * x) if C1 < C2
1471 if (auto SA = dyn_cast<SCEVAddExpr>(Op)) {
1472 if (SA->getNumOperands() == 2) {
1473 auto SC1 = dyn_cast<SCEVConstant>(SA->getOperand(0));
1474 auto SMul = dyn_cast<SCEVMulExpr>(SA->getOperand(1));
1475 if (SMul && SC1) {
1476 if (auto SC2 = dyn_cast<SCEVConstant>(SMul->getOperand(0))) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001477 const APInt &C1 = SC1->getValue()->getValue();
1478 const APInt &C2 = SC2->getValue()->getValue();
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001479 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() &&
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001480 C2.ugt(C1) && C2.isPowerOf2())
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001481 return getAddExpr(getSignExtendExpr(SC1, Ty),
1482 getSignExtendExpr(SMul, Ty));
1483 }
1484 }
1485 }
1486 }
Dan Gohman76466372009-04-27 20:16:15 +00001487 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001488 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohman76466372009-04-27 20:16:15 +00001489 // operands (often constants). This allows analysis of something like
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001490 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmana30370b2009-05-04 22:02:23 +00001491 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohman76466372009-04-27 20:16:15 +00001492 if (AR->isAffine()) {
Dan Gohmane65c9172009-07-13 21:35:55 +00001493 const SCEV *Start = AR->getStart();
1494 const SCEV *Step = AR->getStepRecurrence(*this);
1495 unsigned BitWidth = getTypeSizeInBits(AR->getType());
1496 const Loop *L = AR->getLoop();
1497
Dan Gohman62ef6a72009-07-25 01:22:26 +00001498 // If we have special knowledge that this addrec won't overflow,
1499 // we don't need to do any further analysis.
Andrew Trick8b55b732011-03-14 16:50:06 +00001500 if (AR->getNoWrapFlags(SCEV::FlagNSW))
Andrew Trick812276e2011-05-31 21:17:47 +00001501 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman62ef6a72009-07-25 01:22:26 +00001502 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001503 L, SCEV::FlagNSW);
Dan Gohman62ef6a72009-07-25 01:22:26 +00001504
Dan Gohman76466372009-04-27 20:16:15 +00001505 // Check whether the backedge-taken count is SCEVCouldNotCompute.
1506 // Note that this serves two purposes: It filters out loops that are
1507 // simply not analyzable, and it covers the case where this code is
1508 // being called from within backedge-taken count analysis, such that
1509 // attempting to ask for the backedge-taken count would likely result
1510 // in infinite recursion. In the later case, the analysis code will
1511 // cope with a conservative value, and it will take care to purge
1512 // that value once it has finished.
Dan Gohmane65c9172009-07-13 21:35:55 +00001513 const SCEV *MaxBECount = getMaxBackedgeTakenCount(L);
Dan Gohman2b8da352009-04-30 20:47:05 +00001514 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman95c5b0e2009-04-29 01:54:20 +00001515 // Manually compute the final value for AR, checking for
Dan Gohman494dac32009-04-29 22:28:28 +00001516 // overflow.
Dan Gohman76466372009-04-27 20:16:15 +00001517
1518 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman494dac32009-04-29 22:28:28 +00001519 // the addrec's type. The count is always unsigned.
Dan Gohmanaf752342009-07-07 17:06:11 +00001520 const SCEV *CastedMaxBECount =
Dan Gohman2b8da352009-04-30 20:47:05 +00001521 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Dan Gohmanaf752342009-07-07 17:06:11 +00001522 const SCEV *RecastedMaxBECount =
Dan Gohman4fc36682009-05-18 15:58:39 +00001523 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
1524 if (MaxBECount == RecastedMaxBECount) {
Chris Lattner229907c2011-07-18 04:54:35 +00001525 Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
Dan Gohman2b8da352009-04-30 20:47:05 +00001526 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohman007f5042010-02-24 19:31:06 +00001527 const SCEV *SMul = getMulExpr(CastedMaxBECount, Step);
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001528 const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul), WideTy);
1529 const SCEV *WideStart = getSignExtendExpr(Start, WideTy);
1530 const SCEV *WideMaxBECount =
1531 getZeroExtendExpr(CastedMaxBECount, WideTy);
Dan Gohmanaf752342009-07-07 17:06:11 +00001532 const SCEV *OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001533 getAddExpr(WideStart,
1534 getMulExpr(WideMaxBECount,
Dan Gohman4fc36682009-05-18 15:58:39 +00001535 getSignExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001536 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001537 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1538 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman494dac32009-04-29 22:28:28 +00001539 // Return the expression with the addrec on the outside.
Andrew Trick812276e2011-05-31 21:17:47 +00001540 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman494dac32009-04-29 22:28:28 +00001541 getSignExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001542 L, AR->getNoWrapFlags());
1543 }
Dan Gohman8c129d72009-07-16 17:34:36 +00001544 // Similar to above, only this time treat the step value as unsigned.
1545 // This covers loops that count up with an unsigned step.
Dan Gohman8c129d72009-07-16 17:34:36 +00001546 OperandExtendedAdd =
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001547 getAddExpr(WideStart,
1548 getMulExpr(WideMaxBECount,
Dan Gohman8c129d72009-07-16 17:34:36 +00001549 getZeroExtendExpr(Step, WideTy)));
Nuno Lopesc2a170e2012-05-15 20:20:14 +00001550 if (SAdd == OperandExtendedAdd) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001551 // Cache knowledge of AR NSW, which is propagated to this AddRec.
1552 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
Dan Gohman8c129d72009-07-16 17:34:36 +00001553 // Return the expression with the addrec on the outside.
Andrew Trick812276e2011-05-31 21:17:47 +00001554 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
Dan Gohman8c129d72009-07-16 17:34:36 +00001555 getZeroExtendExpr(Step, Ty),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001556 L, AR->getNoWrapFlags());
1557 }
Dan Gohmane65c9172009-07-13 21:35:55 +00001558 }
1559
1560 // If the backedge is guarded by a comparison with the pre-inc value
1561 // the addrec is safe. Also, if the entry is guarded by a comparison
1562 // with the start value and the backedge is guarded by a comparison
1563 // with the post-inc value, the addrec is safe.
Andrew Trick812276e2011-05-31 21:17:47 +00001564 ICmpInst::Predicate Pred;
1565 const SCEV *OverflowLimit = getOverflowLimitForStep(Step, &Pred, this);
1566 if (OverflowLimit &&
1567 (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
1568 (isLoopEntryGuardedByCond(L, Pred, Start, OverflowLimit) &&
1569 isLoopBackedgeGuardedByCond(L, Pred, AR->getPostIncExpr(*this),
1570 OverflowLimit)))) {
1571 // Cache knowledge of AR NSW, then propagate NSW to the wide AddRec.
1572 const_cast<SCEVAddRecExpr *>(AR)->setNoWrapFlags(SCEV::FlagNSW);
1573 return getAddRecExpr(getSignExtendAddRecStart(AR, Ty, this),
1574 getSignExtendExpr(Step, Ty),
1575 L, AR->getNoWrapFlags());
Dan Gohman76466372009-04-27 20:16:15 +00001576 }
1577 }
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001578 // If Start and Step are constants, check if we can apply this
1579 // transformation:
1580 // sext{C1,+,C2} --> C1 + sext{0,+,C2} if C1 < C2
1581 auto SC1 = dyn_cast<SCEVConstant>(Start);
1582 auto SC2 = dyn_cast<SCEVConstant>(Step);
1583 if (SC1 && SC2) {
Michael Zolotukhin265dfa42014-05-26 14:49:46 +00001584 const APInt &C1 = SC1->getValue()->getValue();
1585 const APInt &C2 = SC2->getValue()->getValue();
1586 if (C1.isStrictlyPositive() && C2.isStrictlyPositive() && C2.ugt(C1) &&
1587 C2.isPowerOf2()) {
Michael Zolotukhind4c72462014-05-24 08:09:57 +00001588 Start = getSignExtendExpr(Start, Ty);
1589 const SCEV *NewAR = getAddRecExpr(getConstant(AR->getType(), 0), Step,
1590 L, AR->getNoWrapFlags());
1591 return getAddExpr(Start, getSignExtendExpr(NewAR, Ty));
1592 }
1593 }
Dan Gohman76466372009-04-27 20:16:15 +00001594 }
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001595
Dan Gohman74a0ba12009-07-13 20:55:53 +00001596 // The cast wasn't folded; create an explicit cast node.
1597 // Recompute the insert position, as it may have been invalidated.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001598 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00001599 SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
1600 Op, Ty);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00001601 UniqueSCEVs.InsertNode(S, IP);
1602 return S;
Dan Gohmancb9e09a2007-06-15 14:38:12 +00001603}
1604
Dan Gohman8db2edc2009-06-13 15:56:47 +00001605/// getAnyExtendExpr - Return a SCEV for the given operand extended with
1606/// unspecified bits out to the given type.
1607///
Dan Gohmanaf752342009-07-07 17:06:11 +00001608const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
Chris Lattner229907c2011-07-18 04:54:35 +00001609 Type *Ty) {
Dan Gohman8db2edc2009-06-13 15:56:47 +00001610 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
1611 "This is not an extending conversion!");
1612 assert(isSCEVable(Ty) &&
1613 "This is not a conversion to a SCEVable type!");
1614 Ty = getEffectiveSCEVType(Ty);
1615
1616 // Sign-extend negative constants.
1617 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
1618 if (SC->getValue()->getValue().isNegative())
1619 return getSignExtendExpr(Op, Ty);
1620
1621 // Peel off a truncate cast.
1622 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001623 const SCEV *NewOp = T->getOperand();
Dan Gohman8db2edc2009-06-13 15:56:47 +00001624 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
1625 return getAnyExtendExpr(NewOp, Ty);
1626 return getTruncateOrNoop(NewOp, Ty);
1627 }
1628
1629 // Next try a zext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001630 const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001631 if (!isa<SCEVZeroExtendExpr>(ZExt))
1632 return ZExt;
1633
1634 // Next try a sext cast. If the cast is folded, use it.
Dan Gohmanaf752342009-07-07 17:06:11 +00001635 const SCEV *SExt = getSignExtendExpr(Op, Ty);
Dan Gohman8db2edc2009-06-13 15:56:47 +00001636 if (!isa<SCEVSignExtendExpr>(SExt))
1637 return SExt;
1638
Dan Gohman51ad99d2010-01-21 02:09:26 +00001639 // Force the cast to be folded into the operands of an addrec.
1640 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
1641 SmallVector<const SCEV *, 4> Ops;
Tobias Grosser924221c2014-05-07 06:07:47 +00001642 for (const SCEV *Op : AR->operands())
1643 Ops.push_back(getAnyExtendExpr(Op, Ty));
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001644 return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001645 }
1646
Dan Gohman8db2edc2009-06-13 15:56:47 +00001647 // If the expression is obviously signed, use the sext cast value.
1648 if (isa<SCEVSMaxExpr>(Op))
1649 return SExt;
1650
1651 // Absent any other information, use the zext cast value.
1652 return ZExt;
1653}
1654
Dan Gohman038d02e2009-06-14 22:58:51 +00001655/// CollectAddOperandsWithScales - Process the given Ops list, which is
1656/// a list of operands to be added under the given scale, update the given
1657/// map. This is a helper function for getAddRecExpr. As an example of
1658/// what it does, given a sequence of operands that would form an add
1659/// expression like this:
1660///
Tobias Grosserba49e422014-03-05 10:37:17 +00001661/// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
Dan Gohman038d02e2009-06-14 22:58:51 +00001662///
1663/// where A and B are constants, update the map with these values:
1664///
1665/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
1666///
1667/// and add 13 + A*B*29 to AccumulatedConstant.
1668/// This will allow getAddRecExpr to produce this:
1669///
1670/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
1671///
1672/// This form often exposes folding opportunities that are hidden in
1673/// the original operand list.
1674///
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00001675/// Return true iff it appears that any interesting folding opportunities
Dan Gohman038d02e2009-06-14 22:58:51 +00001676/// may be exposed. This helps getAddRecExpr short-circuit extra work in
1677/// the common case where no interesting opportunities are present, and
1678/// is also used as a check to avoid infinite recursion.
1679///
1680static bool
Dan Gohmanaf752342009-07-07 17:06:11 +00001681CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
Craig Topper2cd5ff82013-07-11 16:22:38 +00001682 SmallVectorImpl<const SCEV *> &NewOps,
Dan Gohman038d02e2009-06-14 22:58:51 +00001683 APInt &AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001684 const SCEV *const *Ops, size_t NumOperands,
Dan Gohman038d02e2009-06-14 22:58:51 +00001685 const APInt &Scale,
1686 ScalarEvolution &SE) {
1687 bool Interesting = false;
1688
Dan Gohman45073042010-06-18 19:12:32 +00001689 // Iterate over the add operands. They are sorted, with constants first.
1690 unsigned i = 0;
1691 while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1692 ++i;
1693 // Pull a buried constant out to the outside.
1694 if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
1695 Interesting = true;
1696 AccumulatedConstant += Scale * C->getValue()->getValue();
1697 }
1698
1699 // Next comes everything else. We're especially interested in multiplies
1700 // here, but they're in the middle, so just visit the rest with one loop.
1701 for (; i != NumOperands; ++i) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001702 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
1703 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
1704 APInt NewScale =
1705 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
1706 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
1707 // A multiplication of a constant with another add; recurse.
Dan Gohman00524492010-03-18 01:17:13 +00001708 const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
Dan Gohman038d02e2009-06-14 22:58:51 +00001709 Interesting |=
1710 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001711 Add->op_begin(), Add->getNumOperands(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001712 NewScale, SE);
1713 } else {
1714 // A multiplication of a constant with some other value. Update
1715 // the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001716 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1717 const SCEV *Key = SE.getMulExpr(MulOps);
1718 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohmane00beaa2009-06-29 18:25:52 +00001719 M.insert(std::make_pair(Key, NewScale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001720 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001721 NewOps.push_back(Pair.first->first);
1722 } else {
1723 Pair.first->second += NewScale;
1724 // The map already had an entry for this value, which may indicate
1725 // a folding opportunity.
1726 Interesting = true;
1727 }
1728 }
Dan Gohman038d02e2009-06-14 22:58:51 +00001729 } else {
1730 // An ordinary operand. Update the map.
Dan Gohmanaf752342009-07-07 17:06:11 +00001731 std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
Dan Gohmane00beaa2009-06-29 18:25:52 +00001732 M.insert(std::make_pair(Ops[i], Scale));
Dan Gohman038d02e2009-06-14 22:58:51 +00001733 if (Pair.second) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001734 NewOps.push_back(Pair.first->first);
1735 } else {
1736 Pair.first->second += Scale;
1737 // The map already had an entry for this value, which may indicate
1738 // a folding opportunity.
1739 Interesting = true;
1740 }
1741 }
1742 }
1743
1744 return Interesting;
1745}
1746
1747namespace {
1748 struct APIntCompare {
1749 bool operator()(const APInt &LHS, const APInt &RHS) const {
1750 return LHS.ult(RHS);
1751 }
1752 };
1753}
1754
Dan Gohman4d5435d2009-05-24 23:45:28 +00001755/// getAddExpr - Get a canonical add expression, or something simpler if
1756/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00001757const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00001758 SCEV::NoWrapFlags Flags) {
1759 assert(!(Flags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
1760 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00001761 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner74498e12004-04-07 16:16:11 +00001762 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00001763#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00001764 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00001765 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohman9136d9f2010-06-18 19:09:27 +00001766 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00001767 "SCEVAddExpr operand types don't match!");
1768#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00001769
Andrew Trick8b55b732011-03-14 16:50:06 +00001770 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001771 // And vice-versa.
1772 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
1773 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
1774 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001775 bool All = true;
Dan Gohman74c61502010-08-16 16:27:53 +00001776 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
1777 E = Ops.end(); I != E; ++I)
1778 if (!isKnownNonNegative(*I)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00001779 All = false;
1780 break;
1781 }
Andrew Trickf6b01ff2011-03-15 00:37:00 +00001782 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohman51ad99d2010-01-21 02:09:26 +00001783 }
1784
Chris Lattnerd934c702004-04-02 20:23:17 +00001785 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00001786 GroupByComplexity(Ops, LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00001787
1788 // If there are any constants, fold them together.
1789 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00001790 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001791 ++Idx;
Chris Lattner74498e12004-04-07 16:16:11 +00001792 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00001793 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001794 // We found two constants, fold them together!
Dan Gohman0652fd52009-06-14 22:47:23 +00001795 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1796 RHSC->getValue()->getValue());
Dan Gohman011cf682009-06-14 22:53:57 +00001797 if (Ops.size() == 2) return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001798 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00001799 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00001800 }
1801
1802 // If we are left with a constant zero being added, strip it off.
Dan Gohmanebbd05f2010-04-12 23:08:18 +00001803 if (LHSC->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001804 Ops.erase(Ops.begin());
1805 --Idx;
1806 }
Chris Lattnerd934c702004-04-02 20:23:17 +00001807
Dan Gohmanebbd05f2010-04-12 23:08:18 +00001808 if (Ops.size() == 1) return Ops[0];
1809 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001810
Dan Gohman15871f22010-08-27 21:39:59 +00001811 // Okay, check to see if the same value occurs in the operand list more than
1812 // once. If so, merge them together into an multiply expression. Since we
1813 // sorted the list, these values are required to be adjacent.
Chris Lattner229907c2011-07-18 04:54:35 +00001814 Type *Ty = Ops[0]->getType();
Dan Gohmane67b2872010-08-12 14:46:54 +00001815 bool FoundMatch = false;
Dan Gohman15871f22010-08-27 21:39:59 +00001816 for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
Chris Lattnerd934c702004-04-02 20:23:17 +00001817 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
Dan Gohman15871f22010-08-27 21:39:59 +00001818 // Scan ahead to count how many equal operands there are.
1819 unsigned Count = 2;
1820 while (i+Count != e && Ops[i+Count] == Ops[i])
1821 ++Count;
1822 // Merge the values into a multiply.
1823 const SCEV *Scale = getConstant(Ty, Count);
1824 const SCEV *Mul = getMulExpr(Scale, Ops[i]);
1825 if (Ops.size() == Count)
Chris Lattnerd934c702004-04-02 20:23:17 +00001826 return Mul;
Dan Gohmane67b2872010-08-12 14:46:54 +00001827 Ops[i] = Mul;
Dan Gohman15871f22010-08-27 21:39:59 +00001828 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
Dan Gohmanfe22f1d2010-08-28 00:39:27 +00001829 --i; e -= Count - 1;
Dan Gohmane67b2872010-08-12 14:46:54 +00001830 FoundMatch = true;
Chris Lattnerd934c702004-04-02 20:23:17 +00001831 }
Dan Gohmane67b2872010-08-12 14:46:54 +00001832 if (FoundMatch)
Andrew Trick8b55b732011-03-14 16:50:06 +00001833 return getAddExpr(Ops, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00001834
Dan Gohman2e55cc52009-05-08 21:03:19 +00001835 // Check for truncates. If all the operands are truncated from the same
1836 // type, see if factoring out the truncate would permit the result to be
1837 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1838 // if the contents of the resulting outer trunc fold to something simple.
1839 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1840 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
Chris Lattner229907c2011-07-18 04:54:35 +00001841 Type *DstType = Trunc->getType();
1842 Type *SrcType = Trunc->getOperand()->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00001843 SmallVector<const SCEV *, 8> LargeOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00001844 bool Ok = true;
1845 // Check all the operands to see if they can be represented in the
1846 // source type of the truncate.
1847 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1848 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1849 if (T->getOperand()->getType() != SrcType) {
1850 Ok = false;
1851 break;
1852 }
1853 LargeOps.push_back(T->getOperand());
1854 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00001855 LargeOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00001856 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Dan Gohmanaf752342009-07-07 17:06:11 +00001857 SmallVector<const SCEV *, 8> LargeMulOps;
Dan Gohman2e55cc52009-05-08 21:03:19 +00001858 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1859 if (const SCEVTruncateExpr *T =
1860 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1861 if (T->getOperand()->getType() != SrcType) {
1862 Ok = false;
1863 break;
1864 }
1865 LargeMulOps.push_back(T->getOperand());
1866 } else if (const SCEVConstant *C =
1867 dyn_cast<SCEVConstant>(M->getOperand(j))) {
Dan Gohmanff3174e2010-04-23 01:51:29 +00001868 LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
Dan Gohman2e55cc52009-05-08 21:03:19 +00001869 } else {
1870 Ok = false;
1871 break;
1872 }
1873 }
1874 if (Ok)
1875 LargeOps.push_back(getMulExpr(LargeMulOps));
1876 } else {
1877 Ok = false;
1878 break;
1879 }
1880 }
1881 if (Ok) {
1882 // Evaluate the expression in the larger type.
Andrew Trick8b55b732011-03-14 16:50:06 +00001883 const SCEV *Fold = getAddExpr(LargeOps, Flags);
Dan Gohman2e55cc52009-05-08 21:03:19 +00001884 // If it folds to something simple, use it. Otherwise, don't.
1885 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1886 return getTruncateExpr(Fold, DstType);
1887 }
1888 }
1889
1890 // Skip past any other cast SCEVs.
Dan Gohmaneed125f2007-06-18 19:30:09 +00001891 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1892 ++Idx;
1893
1894 // If there are add operands they would be next.
Chris Lattnerd934c702004-04-02 20:23:17 +00001895 if (Idx < Ops.size()) {
1896 bool DeletedAdd = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00001897 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001898 // If we have an add, expand the add operands onto the end of the operands
1899 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00001900 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00001901 Ops.append(Add->op_begin(), Add->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00001902 DeletedAdd = true;
1903 }
1904
1905 // If we deleted at least one add, we added operands to the end of the list,
1906 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00001907 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00001908 if (DeletedAdd)
Dan Gohmana37eaf22007-10-22 18:31:58 +00001909 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001910 }
1911
1912 // Skip over the add expression until we get to a multiply.
1913 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1914 ++Idx;
1915
Dan Gohman038d02e2009-06-14 22:58:51 +00001916 // Check to see if there are any folding opportunities present with
1917 // operands multiplied by constant values.
1918 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1919 uint64_t BitWidth = getTypeSizeInBits(Ty);
Dan Gohmanaf752342009-07-07 17:06:11 +00001920 DenseMap<const SCEV *, APInt> M;
1921 SmallVector<const SCEV *, 8> NewOps;
Dan Gohman038d02e2009-06-14 22:58:51 +00001922 APInt AccumulatedConstant(BitWidth, 0);
1923 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
Dan Gohman00524492010-03-18 01:17:13 +00001924 Ops.data(), Ops.size(),
1925 APInt(BitWidth, 1), *this)) {
Dan Gohman038d02e2009-06-14 22:58:51 +00001926 // Some interesting folding opportunity is present, so its worthwhile to
1927 // re-generate the operands list. Group the operands by constant scale,
1928 // to avoid multiplying by the same constant scale multiple times.
Dan Gohmanaf752342009-07-07 17:06:11 +00001929 std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
Craig Topper31ee5862013-07-03 15:07:05 +00001930 for (SmallVectorImpl<const SCEV *>::const_iterator I = NewOps.begin(),
Dan Gohman038d02e2009-06-14 22:58:51 +00001931 E = NewOps.end(); I != E; ++I)
1932 MulOpLists[M.find(*I)->second].push_back(*I);
1933 // Re-generate the operands list.
1934 Ops.clear();
1935 if (AccumulatedConstant != 0)
1936 Ops.push_back(getConstant(AccumulatedConstant));
Dan Gohmance973df2009-06-24 04:48:43 +00001937 for (std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare>::iterator
1938 I = MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
Dan Gohman038d02e2009-06-14 22:58:51 +00001939 if (I->first != 0)
Dan Gohmance973df2009-06-24 04:48:43 +00001940 Ops.push_back(getMulExpr(getConstant(I->first),
1941 getAddExpr(I->second)));
Dan Gohman038d02e2009-06-14 22:58:51 +00001942 if (Ops.empty())
Dan Gohman1d2ded72010-05-03 22:09:21 +00001943 return getConstant(Ty, 0);
Dan Gohman038d02e2009-06-14 22:58:51 +00001944 if (Ops.size() == 1)
1945 return Ops[0];
1946 return getAddExpr(Ops);
1947 }
1948 }
1949
Chris Lattnerd934c702004-04-02 20:23:17 +00001950 // If we are adding something to a multiply expression, make sure the
1951 // something is not already an operand of the multiply. If so, merge it into
1952 // the multiply.
1953 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohman48f82222009-05-04 22:30:44 +00001954 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00001955 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohman48f82222009-05-04 22:30:44 +00001956 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohman157847f2010-08-12 14:52:55 +00001957 if (isa<SCEVConstant>(MulOpSCEV))
1958 continue;
Chris Lattnerd934c702004-04-02 20:23:17 +00001959 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman157847f2010-08-12 14:52:55 +00001960 if (MulOpSCEV == Ops[AddOp]) {
Chris Lattnerd934c702004-04-02 20:23:17 +00001961 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Dan Gohmanaf752342009-07-07 17:06:11 +00001962 const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00001963 if (Mul->getNumOperands() != 2) {
1964 // If the multiply has more than two operands, we must get the
1965 // Y*Z term.
Dan Gohman797a1db2010-08-16 16:57:24 +00001966 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
1967 Mul->op_begin()+MulOp);
1968 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00001969 InnerMul = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00001970 }
Dan Gohman1d2ded72010-05-03 22:09:21 +00001971 const SCEV *One = getConstant(Ty, 1);
Dan Gohmancf32f2b2010-08-13 20:17:14 +00001972 const SCEV *AddOne = getAddExpr(One, InnerMul);
Dan Gohman157847f2010-08-12 14:52:55 +00001973 const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV);
Chris Lattnerd934c702004-04-02 20:23:17 +00001974 if (Ops.size() == 2) return OuterMul;
1975 if (AddOp < Idx) {
1976 Ops.erase(Ops.begin()+AddOp);
1977 Ops.erase(Ops.begin()+Idx-1);
1978 } else {
1979 Ops.erase(Ops.begin()+Idx);
1980 Ops.erase(Ops.begin()+AddOp-1);
1981 }
1982 Ops.push_back(OuterMul);
Dan Gohmana37eaf22007-10-22 18:31:58 +00001983 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00001984 }
Misha Brukman01808ca2005-04-21 21:13:18 +00001985
Chris Lattnerd934c702004-04-02 20:23:17 +00001986 // Check this multiply against other multiplies being added together.
1987 for (unsigned OtherMulIdx = Idx+1;
1988 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1989 ++OtherMulIdx) {
Dan Gohman48f82222009-05-04 22:30:44 +00001990 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Chris Lattnerd934c702004-04-02 20:23:17 +00001991 // If MulOp occurs in OtherMul, we can fold the two multiplies
1992 // together.
1993 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1994 OMulOp != e; ++OMulOp)
1995 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1996 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Dan Gohmanaf752342009-07-07 17:06:11 +00001997 const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00001998 if (Mul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00001999 SmallVector<const SCEV *, 4> MulOps(Mul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002000 Mul->op_begin()+MulOp);
2001 MulOps.append(Mul->op_begin()+MulOp+1, Mul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002002 InnerMul1 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002003 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002004 const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Chris Lattnerd934c702004-04-02 20:23:17 +00002005 if (OtherMul->getNumOperands() != 2) {
Dan Gohmance973df2009-06-24 04:48:43 +00002006 SmallVector<const SCEV *, 4> MulOps(OtherMul->op_begin(),
Dan Gohman797a1db2010-08-16 16:57:24 +00002007 OtherMul->op_begin()+OMulOp);
2008 MulOps.append(OtherMul->op_begin()+OMulOp+1, OtherMul->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002009 InnerMul2 = getMulExpr(MulOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002010 }
Dan Gohmanaf752342009-07-07 17:06:11 +00002011 const SCEV *InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
2012 const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Chris Lattnerd934c702004-04-02 20:23:17 +00002013 if (Ops.size() == 2) return OuterMul;
Dan Gohmanaabfc522010-08-31 22:50:31 +00002014 Ops.erase(Ops.begin()+Idx);
2015 Ops.erase(Ops.begin()+OtherMulIdx-1);
2016 Ops.push_back(OuterMul);
2017 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002018 }
2019 }
2020 }
2021 }
2022
2023 // If there are any add recurrences in the operands list, see if any other
2024 // added values are loop invariant. If so, we can fold them into the
2025 // recurrence.
2026 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2027 ++Idx;
2028
2029 // Scan over all recurrences, trying to fold loop invariants into them.
2030 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2031 // Scan all of the other operands to this add and add them to the vector if
2032 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002033 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002034 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanebbd05f2010-04-12 23:08:18 +00002035 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002036 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002037 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002038 LIOps.push_back(Ops[i]);
2039 Ops.erase(Ops.begin()+i);
2040 --i; --e;
2041 }
2042
2043 // If we found some loop invariants, fold them into the recurrence.
2044 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002045 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Chris Lattnerd934c702004-04-02 20:23:17 +00002046 LIOps.push_back(AddRec->getStart());
2047
Dan Gohmanaf752342009-07-07 17:06:11 +00002048 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman7a2dab82009-12-18 03:57:04 +00002049 AddRec->op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00002050 AddRecOps[0] = getAddExpr(LIOps);
Chris Lattnerd934c702004-04-02 20:23:17 +00002051
Dan Gohman16206132010-06-30 07:16:37 +00002052 // Build the new addrec. Propagate the NUW and NSW flags if both the
Eric Christopher23bf3ba2011-01-11 09:02:09 +00002053 // outer add and the inner addrec are guaranteed to have no overflow.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002054 // Always propagate NW.
2055 Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
Andrew Trick8b55b732011-03-14 16:50:06 +00002056 const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
Dan Gohman51f13052009-12-18 18:45:31 +00002057
Chris Lattnerd934c702004-04-02 20:23:17 +00002058 // If all of the other operands were loop invariant, we are done.
2059 if (Ops.size() == 1) return NewRec;
2060
Nick Lewyckydb66b822011-09-06 05:08:09 +00002061 // Otherwise, add the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002062 for (unsigned i = 0;; ++i)
2063 if (Ops[i] == AddRec) {
2064 Ops[i] = NewRec;
2065 break;
2066 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002067 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002068 }
2069
2070 // Okay, if there weren't any loop invariants to be folded, check to see if
2071 // there are multiple AddRec's with the same loop induction variable being
2072 // added together. If so, we can fold them.
2073 for (unsigned OtherIdx = Idx+1;
Dan Gohmanc866bf42010-08-27 20:45:56 +00002074 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2075 ++OtherIdx)
2076 if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
2077 // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
2078 SmallVector<const SCEV *, 4> AddRecOps(AddRec->op_begin(),
2079 AddRec->op_end());
2080 for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
2081 ++OtherIdx)
Dan Gohman028c1812010-08-29 14:53:34 +00002082 if (const SCEVAddRecExpr *OtherAddRec =
Dan Gohmanc866bf42010-08-27 20:45:56 +00002083 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]))
Dan Gohman028c1812010-08-29 14:53:34 +00002084 if (OtherAddRec->getLoop() == AddRecLoop) {
2085 for (unsigned i = 0, e = OtherAddRec->getNumOperands();
2086 i != e; ++i) {
Dan Gohmanc866bf42010-08-27 20:45:56 +00002087 if (i >= AddRecOps.size()) {
Dan Gohman028c1812010-08-29 14:53:34 +00002088 AddRecOps.append(OtherAddRec->op_begin()+i,
2089 OtherAddRec->op_end());
Dan Gohmanc866bf42010-08-27 20:45:56 +00002090 break;
2091 }
Dan Gohman028c1812010-08-29 14:53:34 +00002092 AddRecOps[i] = getAddExpr(AddRecOps[i],
2093 OtherAddRec->getOperand(i));
Dan Gohmanc866bf42010-08-27 20:45:56 +00002094 }
2095 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
Chris Lattnerd934c702004-04-02 20:23:17 +00002096 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002097 // Step size has changed, so we cannot guarantee no self-wraparound.
2098 Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
Dan Gohmanc866bf42010-08-27 20:45:56 +00002099 return getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002100 }
2101
2102 // Otherwise couldn't fold anything into this recurrence. Move onto the
2103 // next one.
2104 }
2105
2106 // Okay, it looks like we really DO need an add expr. Check to see if we
2107 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002108 FoldingSetNodeID ID;
2109 ID.AddInteger(scAddExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002110 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2111 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002112 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002113 SCEVAddExpr *S =
2114 static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2115 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002116 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2117 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002118 S = new (SCEVAllocator) SCEVAddExpr(ID.Intern(SCEVAllocator),
2119 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002120 UniqueSCEVs.InsertNode(S, IP);
2121 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002122 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002123 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002124}
2125
Nick Lewycky287682e2011-10-04 06:51:26 +00002126static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
2127 uint64_t k = i*j;
2128 if (j > 1 && k / j != i) Overflow = true;
2129 return k;
2130}
2131
2132/// Compute the result of "n choose k", the binomial coefficient. If an
2133/// intermediate computation overflows, Overflow will be set and the return will
Benjamin Kramerbde91762012-06-02 10:20:22 +00002134/// be garbage. Overflow is not cleared on absence of overflow.
Nick Lewycky287682e2011-10-04 06:51:26 +00002135static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
2136 // We use the multiplicative formula:
2137 // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
2138 // At each iteration, we take the n-th term of the numeral and divide by the
2139 // (k-n)th term of the denominator. This division will always produce an
2140 // integral result, and helps reduce the chance of overflow in the
2141 // intermediate computations. However, we can still overflow even when the
2142 // final result would fit.
2143
2144 if (n == 0 || n == k) return 1;
2145 if (k > n) return 0;
2146
2147 if (k > n/2)
2148 k = n-k;
2149
2150 uint64_t r = 1;
2151 for (uint64_t i = 1; i <= k; ++i) {
2152 r = umul_ov(r, n-(i-1), Overflow);
2153 r /= i;
2154 }
2155 return r;
2156}
2157
Dan Gohman4d5435d2009-05-24 23:45:28 +00002158/// getMulExpr - Get a canonical multiply expression, or something simpler if
2159/// possible.
Dan Gohman816fe0a2009-10-09 00:10:36 +00002160const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
Andrew Trick8b55b732011-03-14 16:50:06 +00002161 SCEV::NoWrapFlags Flags) {
2162 assert(Flags == maskFlags(Flags, SCEV::FlagNUW | SCEV::FlagNSW) &&
2163 "only nuw or nsw allowed");
Chris Lattnerd934c702004-04-02 20:23:17 +00002164 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohman51ad99d2010-01-21 02:09:26 +00002165 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002166#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002167 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002168 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002169 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002170 "SCEVMulExpr operand types don't match!");
2171#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002172
Andrew Trick8b55b732011-03-14 16:50:06 +00002173 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002174 // And vice-versa.
2175 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2176 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2177 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002178 bool All = true;
Dan Gohman74c61502010-08-16 16:27:53 +00002179 for (SmallVectorImpl<const SCEV *>::const_iterator I = Ops.begin(),
2180 E = Ops.end(); I != E; ++I)
2181 if (!isKnownNonNegative(*I)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002182 All = false;
2183 break;
2184 }
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002185 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002186 }
2187
Chris Lattnerd934c702004-04-02 20:23:17 +00002188 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002189 GroupByComplexity(Ops, LI);
Chris Lattnerd934c702004-04-02 20:23:17 +00002190
2191 // If there are any constants, fold them together.
2192 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002193 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002194
2195 // C1*(C2+V) -> C1*C2 + C1*V
2196 if (Ops.size() == 2)
Dan Gohmana30370b2009-05-04 22:02:23 +00002197 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Chris Lattnerd934c702004-04-02 20:23:17 +00002198 if (Add->getNumOperands() == 2 &&
2199 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohmana37eaf22007-10-22 18:31:58 +00002200 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
2201 getMulExpr(LHSC, Add->getOperand(1)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002202
Chris Lattnerd934c702004-04-02 20:23:17 +00002203 ++Idx;
Dan Gohmana30370b2009-05-04 22:02:23 +00002204 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002205 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002206 ConstantInt *Fold = ConstantInt::get(getContext(),
2207 LHSC->getValue()->getValue() *
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002208 RHSC->getValue()->getValue());
2209 Ops[0] = getConstant(Fold);
2210 Ops.erase(Ops.begin()+1); // Erase the folded element
2211 if (Ops.size() == 1) return Ops[0];
2212 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattnerd934c702004-04-02 20:23:17 +00002213 }
2214
2215 // If we are left with a constant one being multiplied, strip it off.
2216 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
2217 Ops.erase(Ops.begin());
2218 --Idx;
Reid Spencer2e54a152007-03-02 00:28:52 +00002219 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002220 // If we have a multiply of zero, it will always be zero.
2221 return Ops[0];
Dan Gohman51ad99d2010-01-21 02:09:26 +00002222 } else if (Ops[0]->isAllOnesValue()) {
2223 // If we have a mul by -1 of an add, try distributing the -1 among the
2224 // add operands.
Andrew Trick8b55b732011-03-14 16:50:06 +00002225 if (Ops.size() == 2) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002226 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
2227 SmallVector<const SCEV *, 4> NewOps;
2228 bool AnyFolded = false;
Andrew Trick8b55b732011-03-14 16:50:06 +00002229 for (SCEVAddRecExpr::op_iterator I = Add->op_begin(),
2230 E = Add->op_end(); I != E; ++I) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002231 const SCEV *Mul = getMulExpr(Ops[0], *I);
2232 if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
2233 NewOps.push_back(Mul);
2234 }
2235 if (AnyFolded)
2236 return getAddExpr(NewOps);
2237 }
Andrew Tricke92dcce2011-03-14 17:38:54 +00002238 else if (const SCEVAddRecExpr *
2239 AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
2240 // Negation preserves a recurrence's no self-wrap property.
2241 SmallVector<const SCEV *, 4> Operands;
2242 for (SCEVAddRecExpr::op_iterator I = AddRec->op_begin(),
2243 E = AddRec->op_end(); I != E; ++I) {
2244 Operands.push_back(getMulExpr(Ops[0], *I));
2245 }
2246 return getAddRecExpr(Operands, AddRec->getLoop(),
2247 AddRec->getNoWrapFlags(SCEV::FlagNW));
2248 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002249 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002250 }
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002251
2252 if (Ops.size() == 1)
2253 return Ops[0];
Chris Lattnerd934c702004-04-02 20:23:17 +00002254 }
2255
2256 // Skip over the add expression until we get to a multiply.
2257 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
2258 ++Idx;
2259
Chris Lattnerd934c702004-04-02 20:23:17 +00002260 // If there are mul operands inline them all into this expression.
2261 if (Idx < Ops.size()) {
2262 bool DeletedMul = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002263 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002264 // If we have an mul, expand the mul operands onto the end of the operands
2265 // list.
Chris Lattnerd934c702004-04-02 20:23:17 +00002266 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002267 Ops.append(Mul->op_begin(), Mul->op_end());
Chris Lattnerd934c702004-04-02 20:23:17 +00002268 DeletedMul = true;
2269 }
2270
2271 // If we deleted at least one mul, we added operands to the end of the list,
2272 // and they are not necessarily sorted. Recurse to resort and resimplify
Dan Gohman8b0a4192010-03-01 17:49:51 +00002273 // any operands we just acquired.
Chris Lattnerd934c702004-04-02 20:23:17 +00002274 if (DeletedMul)
Dan Gohmana37eaf22007-10-22 18:31:58 +00002275 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002276 }
2277
2278 // If there are any add recurrences in the operands list, see if any other
2279 // added values are loop invariant. If so, we can fold them into the
2280 // recurrence.
2281 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
2282 ++Idx;
2283
2284 // Scan over all recurrences, trying to fold loop invariants into them.
2285 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
2286 // Scan all of the other operands to this mul and add them to the vector if
2287 // they are loop invariant w.r.t. the recurrence.
Dan Gohmanaf752342009-07-07 17:06:11 +00002288 SmallVector<const SCEV *, 8> LIOps;
Dan Gohman48f82222009-05-04 22:30:44 +00002289 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohman0f2de012010-08-29 14:55:19 +00002290 const Loop *AddRecLoop = AddRec->getLoop();
Chris Lattnerd934c702004-04-02 20:23:17 +00002291 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002292 if (isLoopInvariant(Ops[i], AddRecLoop)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002293 LIOps.push_back(Ops[i]);
2294 Ops.erase(Ops.begin()+i);
2295 --i; --e;
2296 }
2297
2298 // If we found some loop invariants, fold them into the recurrence.
2299 if (!LIOps.empty()) {
Dan Gohman81313fd2008-09-14 17:21:12 +00002300 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanaf752342009-07-07 17:06:11 +00002301 SmallVector<const SCEV *, 4> NewOps;
Chris Lattnerd934c702004-04-02 20:23:17 +00002302 NewOps.reserve(AddRec->getNumOperands());
Dan Gohman8f5954f2010-06-17 23:34:09 +00002303 const SCEV *Scale = getMulExpr(LIOps);
2304 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
2305 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Chris Lattnerd934c702004-04-02 20:23:17 +00002306
Dan Gohman16206132010-06-30 07:16:37 +00002307 // Build the new addrec. Propagate the NUW and NSW flags if both the
2308 // outer mul and the inner addrec are guaranteed to have no overflow.
Andrew Trick8b55b732011-03-14 16:50:06 +00002309 //
2310 // No self-wrap cannot be guaranteed after changing the step size, but
Chris Lattner0ab5e2c2011-04-15 05:18:47 +00002311 // will be inferred if either NUW or NSW is true.
Andrew Trick8b55b732011-03-14 16:50:06 +00002312 Flags = AddRec->getNoWrapFlags(clearFlags(Flags, SCEV::FlagNW));
2313 const SCEV *NewRec = getAddRecExpr(NewOps, AddRecLoop, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002314
2315 // If all of the other operands were loop invariant, we are done.
2316 if (Ops.size() == 1) return NewRec;
2317
Nick Lewyckydb66b822011-09-06 05:08:09 +00002318 // Otherwise, multiply the folded AddRec by the non-invariant parts.
Chris Lattnerd934c702004-04-02 20:23:17 +00002319 for (unsigned i = 0;; ++i)
2320 if (Ops[i] == AddRec) {
2321 Ops[i] = NewRec;
2322 break;
2323 }
Dan Gohmana37eaf22007-10-22 18:31:58 +00002324 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002325 }
2326
2327 // Okay, if there weren't any loop invariants to be folded, check to see if
2328 // there are multiple AddRec's with the same loop induction variable being
2329 // multiplied together. If so, we can fold them.
Nick Lewycky97756402014-09-01 05:17:15 +00002330
2331 // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
2332 // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
2333 // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
2334 // ]]],+,...up to x=2n}.
2335 // Note that the arguments to choose() are always integers with values
2336 // known at compile time, never SCEV objects.
2337 //
2338 // The implementation avoids pointless extra computations when the two
2339 // addrec's are of different length (mathematically, it's equivalent to
2340 // an infinite stream of zeros on the right).
2341 bool OpsModified = false;
Chris Lattnerd934c702004-04-02 20:23:17 +00002342 for (unsigned OtherIdx = Idx+1;
Nick Lewycky97756402014-09-01 05:17:15 +00002343 OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002344 ++OtherIdx) {
Nick Lewycky97756402014-09-01 05:17:15 +00002345 const SCEVAddRecExpr *OtherAddRec =
2346 dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
2347 if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
Andrew Trick946f76b2012-05-30 03:35:17 +00002348 continue;
2349
Nick Lewycky97756402014-09-01 05:17:15 +00002350 bool Overflow = false;
2351 Type *Ty = AddRec->getType();
2352 bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
2353 SmallVector<const SCEV*, 7> AddRecOps;
2354 for (int x = 0, xe = AddRec->getNumOperands() +
2355 OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
2356 const SCEV *Term = getConstant(Ty, 0);
2357 for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
2358 uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
2359 for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
2360 ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
2361 z < ze && !Overflow; ++z) {
2362 uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
2363 uint64_t Coeff;
2364 if (LargerThan64Bits)
2365 Coeff = umul_ov(Coeff1, Coeff2, Overflow);
2366 else
2367 Coeff = Coeff1*Coeff2;
2368 const SCEV *CoeffTerm = getConstant(Ty, Coeff);
2369 const SCEV *Term1 = AddRec->getOperand(y-z);
2370 const SCEV *Term2 = OtherAddRec->getOperand(z);
2371 Term = getAddExpr(Term, getMulExpr(CoeffTerm, Term1,Term2));
Andrew Trick946f76b2012-05-30 03:35:17 +00002372 }
Andrew Trick946f76b2012-05-30 03:35:17 +00002373 }
Nick Lewycky97756402014-09-01 05:17:15 +00002374 AddRecOps.push_back(Term);
Chris Lattnerd934c702004-04-02 20:23:17 +00002375 }
Nick Lewycky97756402014-09-01 05:17:15 +00002376 if (!Overflow) {
2377 const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRec->getLoop(),
2378 SCEV::FlagAnyWrap);
2379 if (Ops.size() == 2) return NewAddRec;
2380 Ops[Idx] = NewAddRec;
2381 Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
2382 OpsModified = true;
2383 AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
2384 if (!AddRec)
2385 break;
2386 }
Nick Lewyckye0aa54b2011-09-06 21:42:18 +00002387 }
Nick Lewycky97756402014-09-01 05:17:15 +00002388 if (OpsModified)
2389 return getMulExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00002390
2391 // Otherwise couldn't fold anything into this recurrence. Move onto the
2392 // next one.
2393 }
2394
2395 // Okay, it looks like we really DO need an mul expr. Check to see if we
2396 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002397 FoldingSetNodeID ID;
2398 ID.AddInteger(scMulExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002399 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2400 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002401 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002402 SCEVMulExpr *S =
2403 static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2404 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002405 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2406 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002407 S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
2408 O, Ops.size());
Dan Gohman51ad99d2010-01-21 02:09:26 +00002409 UniqueSCEVs.InsertNode(S, IP);
2410 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002411 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002412 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002413}
2414
Andreas Bolka7a5c8db2009-08-07 22:55:26 +00002415/// getUDivExpr - Get a canonical unsigned division expression, or something
2416/// simpler if possible.
Dan Gohmanabd17092009-06-24 14:49:00 +00002417const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
2418 const SCEV *RHS) {
Dan Gohmand33f36e2009-05-18 15:44:58 +00002419 assert(getEffectiveSCEVType(LHS->getType()) ==
2420 getEffectiveSCEVType(RHS->getType()) &&
2421 "SCEVUDivExpr operand types don't match!");
2422
Dan Gohmana30370b2009-05-04 22:02:23 +00002423 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002424 if (RHSC->getValue()->equalsInt(1))
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00002425 return LHS; // X udiv 1 --> x
Dan Gohmanacd700a2010-04-22 01:35:11 +00002426 // If the denominator is zero, the result of the udiv is undefined. Don't
2427 // try to analyze it, because the resolution chosen here may differ from
2428 // the resolution chosen in other parts of the compiler.
2429 if (!RHSC->getValue()->isZero()) {
2430 // Determine if the division can be folded into the operands of
2431 // its operands.
2432 // TODO: Generalize this to non-constants by using known-bits information.
Chris Lattner229907c2011-07-18 04:54:35 +00002433 Type *Ty = LHS->getType();
Dan Gohmanacd700a2010-04-22 01:35:11 +00002434 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
Dan Gohmandb764c62010-08-04 19:52:50 +00002435 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
Dan Gohmanacd700a2010-04-22 01:35:11 +00002436 // For non-power-of-two values, effectively round the value up to the
2437 // nearest power of two.
2438 if (!RHSC->getValue()->getValue().isPowerOf2())
2439 ++MaxShiftAmt;
Chris Lattner229907c2011-07-18 04:54:35 +00002440 IntegerType *ExtTy =
Dan Gohmanacd700a2010-04-22 01:35:11 +00002441 IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
Dan Gohmanacd700a2010-04-22 01:35:11 +00002442 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
2443 if (const SCEVConstant *Step =
Andrew Trick6d45a012011-08-06 07:00:37 +00002444 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
2445 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
2446 const APInt &StepInt = Step->getValue()->getValue();
2447 const APInt &DivInt = RHSC->getValue()->getValue();
2448 if (!StepInt.urem(DivInt) &&
Dan Gohmanacd700a2010-04-22 01:35:11 +00002449 getZeroExtendExpr(AR, ExtTy) ==
2450 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2451 getZeroExtendExpr(Step, ExtTy),
Andrew Trick8b55b732011-03-14 16:50:06 +00002452 AR->getLoop(), SCEV::FlagAnyWrap)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002453 SmallVector<const SCEV *, 4> Operands;
2454 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
2455 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
Andrew Trick8b55b732011-03-14 16:50:06 +00002456 return getAddRecExpr(Operands, AR->getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002457 SCEV::FlagNW);
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002458 }
Andrew Trick6d45a012011-08-06 07:00:37 +00002459 /// Get a canonical UDivExpr for a recurrence.
2460 /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
2461 // We can currently only fold X%N if X is constant.
2462 const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
2463 if (StartC && !DivInt.urem(StepInt) &&
2464 getZeroExtendExpr(AR, ExtTy) ==
2465 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
2466 getZeroExtendExpr(Step, ExtTy),
2467 AR->getLoop(), SCEV::FlagAnyWrap)) {
2468 const APInt &StartInt = StartC->getValue()->getValue();
2469 const APInt &StartRem = StartInt.urem(StepInt);
2470 if (StartRem != 0)
2471 LHS = getAddRecExpr(getConstant(StartInt - StartRem), Step,
2472 AR->getLoop(), SCEV::FlagNW);
2473 }
2474 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002475 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
2476 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
2477 SmallVector<const SCEV *, 4> Operands;
2478 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
2479 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
2480 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
2481 // Find an operand that's safely divisible.
2482 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
2483 const SCEV *Op = M->getOperand(i);
2484 const SCEV *Div = getUDivExpr(Op, RHSC);
2485 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
2486 Operands = SmallVector<const SCEV *, 4>(M->op_begin(),
2487 M->op_end());
2488 Operands[i] = Div;
2489 return getMulExpr(Operands);
2490 }
2491 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002492 }
Dan Gohmanacd700a2010-04-22 01:35:11 +00002493 // (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 +00002494 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00002495 SmallVector<const SCEV *, 4> Operands;
2496 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
2497 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
2498 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
2499 Operands.clear();
2500 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
2501 const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
2502 if (isa<SCEVUDivExpr>(Op) ||
2503 getMulExpr(Op, RHS) != A->getOperand(i))
2504 break;
2505 Operands.push_back(Op);
2506 }
2507 if (Operands.size() == A->getNumOperands())
2508 return getAddExpr(Operands);
2509 }
2510 }
Dan Gohmanc3a3cb42009-05-08 20:18:49 +00002511
Dan Gohmanacd700a2010-04-22 01:35:11 +00002512 // Fold if both operands are constant.
2513 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
2514 Constant *LHSCV = LHSC->getValue();
2515 Constant *RHSCV = RHSC->getValue();
2516 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
2517 RHSCV)));
2518 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002519 }
2520 }
2521
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002522 FoldingSetNodeID ID;
2523 ID.AddInteger(scUDivExpr);
2524 ID.AddPointer(LHS);
2525 ID.AddPointer(RHS);
Craig Topper9f008862014-04-15 04:59:12 +00002526 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002527 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman01c65a22010-03-18 18:49:47 +00002528 SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
2529 LHS, RHS);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002530 UniqueSCEVs.InsertNode(S, IP);
2531 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002532}
2533
Nick Lewycky31eaca52014-01-27 10:04:03 +00002534static const APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
2535 APInt A = C1->getValue()->getValue().abs();
2536 APInt B = C2->getValue()->getValue().abs();
2537 uint32_t ABW = A.getBitWidth();
2538 uint32_t BBW = B.getBitWidth();
2539
2540 if (ABW > BBW)
2541 B = B.zext(ABW);
2542 else if (ABW < BBW)
2543 A = A.zext(BBW);
2544
2545 return APIntOps::GreatestCommonDivisor(A, B);
2546}
2547
2548/// getUDivExactExpr - Get a canonical unsigned division expression, or
2549/// something simpler if possible. There is no representation for an exact udiv
2550/// in SCEV IR, but we can attempt to remove factors from the LHS and RHS.
2551/// We can't do this when it's not exact because the udiv may be clearing bits.
2552const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
2553 const SCEV *RHS) {
2554 // TODO: we could try to find factors in all sorts of things, but for now we
2555 // just deal with u/exact (multiply, constant). See SCEVDivision towards the
2556 // end of this file for inspiration.
2557
2558 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
2559 if (!Mul)
2560 return getUDivExpr(LHS, RHS);
2561
2562 if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
2563 // If the mulexpr multiplies by a constant, then that constant must be the
2564 // first element of the mulexpr.
2565 if (const SCEVConstant *LHSCst =
2566 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
2567 if (LHSCst == RHSCst) {
2568 SmallVector<const SCEV *, 2> Operands;
2569 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2570 return getMulExpr(Operands);
2571 }
2572
2573 // We can't just assume that LHSCst divides RHSCst cleanly, it could be
2574 // that there's a factor provided by one of the other terms. We need to
2575 // check.
2576 APInt Factor = gcd(LHSCst, RHSCst);
2577 if (!Factor.isIntN(1)) {
2578 LHSCst = cast<SCEVConstant>(
2579 getConstant(LHSCst->getValue()->getValue().udiv(Factor)));
2580 RHSCst = cast<SCEVConstant>(
2581 getConstant(RHSCst->getValue()->getValue().udiv(Factor)));
2582 SmallVector<const SCEV *, 2> Operands;
2583 Operands.push_back(LHSCst);
2584 Operands.append(Mul->op_begin() + 1, Mul->op_end());
2585 LHS = getMulExpr(Operands);
2586 RHS = RHSCst;
Nick Lewycky629199c2014-01-27 10:47:44 +00002587 Mul = dyn_cast<SCEVMulExpr>(LHS);
2588 if (!Mul)
2589 return getUDivExactExpr(LHS, RHS);
Nick Lewycky31eaca52014-01-27 10:04:03 +00002590 }
2591 }
2592 }
2593
2594 for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
2595 if (Mul->getOperand(i) == RHS) {
2596 SmallVector<const SCEV *, 2> Operands;
2597 Operands.append(Mul->op_begin(), Mul->op_begin() + i);
2598 Operands.append(Mul->op_begin() + i + 1, Mul->op_end());
2599 return getMulExpr(Operands);
2600 }
2601 }
2602
2603 return getUDivExpr(LHS, RHS);
2604}
Chris Lattnerd934c702004-04-02 20:23:17 +00002605
Dan Gohman4d5435d2009-05-24 23:45:28 +00002606/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2607/// Simplify the expression as much as possible.
Andrew Trick8b55b732011-03-14 16:50:06 +00002608const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
2609 const Loop *L,
2610 SCEV::NoWrapFlags Flags) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002611 SmallVector<const SCEV *, 4> Operands;
Chris Lattnerd934c702004-04-02 20:23:17 +00002612 Operands.push_back(Start);
Dan Gohmana30370b2009-05-04 22:02:23 +00002613 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Chris Lattnerd934c702004-04-02 20:23:17 +00002614 if (StepChrec->getLoop() == L) {
Dan Gohmandd41bba2010-06-21 19:47:52 +00002615 Operands.append(StepChrec->op_begin(), StepChrec->op_end());
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002616 return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
Chris Lattnerd934c702004-04-02 20:23:17 +00002617 }
2618
2619 Operands.push_back(Step);
Andrew Trick8b55b732011-03-14 16:50:06 +00002620 return getAddRecExpr(Operands, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00002621}
2622
Dan Gohman4d5435d2009-05-24 23:45:28 +00002623/// getAddRecExpr - Get an add recurrence expression for the specified loop.
2624/// Simplify the expression as much as possible.
Dan Gohmance973df2009-06-24 04:48:43 +00002625const SCEV *
Dan Gohmanaf752342009-07-07 17:06:11 +00002626ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
Andrew Trick8b55b732011-03-14 16:50:06 +00002627 const Loop *L, SCEV::NoWrapFlags Flags) {
Chris Lattnerd934c702004-04-02 20:23:17 +00002628 if (Operands.size() == 1) return Operands[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002629#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002630 Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002631 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002632 assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002633 "SCEVAddRecExpr operand types don't match!");
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002634 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002635 assert(isLoopInvariant(Operands[i], L) &&
Dan Gohmand3a32ae2010-11-17 20:48:38 +00002636 "SCEVAddRecExpr operand is not loop-invariant!");
Dan Gohmand33f36e2009-05-18 15:44:58 +00002637#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00002638
Dan Gohmanbe928e32008-06-18 16:23:07 +00002639 if (Operands.back()->isZero()) {
2640 Operands.pop_back();
Andrew Trick8b55b732011-03-14 16:50:06 +00002641 return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
Dan Gohmanbe928e32008-06-18 16:23:07 +00002642 }
Chris Lattnerd934c702004-04-02 20:23:17 +00002643
Dan Gohmancf9c64e2010-02-19 18:49:22 +00002644 // It's tempting to want to call getMaxBackedgeTakenCount count here and
2645 // use that information to infer NUW and NSW flags. However, computing a
2646 // BE count requires calling getAddRecExpr, so we may not yet have a
2647 // meaningful BE count at this point (and if we don't, we'd be stuck
2648 // with a SCEVCouldNotCompute as the cached BE count).
2649
Andrew Trick8b55b732011-03-14 16:50:06 +00002650 // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002651 // And vice-versa.
2652 int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
2653 SCEV::NoWrapFlags SignOrUnsignWrap = maskFlags(Flags, SignOrUnsignMask);
2654 if (SignOrUnsignWrap && (SignOrUnsignWrap != SignOrUnsignMask)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002655 bool All = true;
Dan Gohman74c61502010-08-16 16:27:53 +00002656 for (SmallVectorImpl<const SCEV *>::const_iterator I = Operands.begin(),
2657 E = Operands.end(); I != E; ++I)
2658 if (!isKnownNonNegative(*I)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00002659 All = false;
2660 break;
2661 }
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002662 if (All) Flags = setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002663 }
2664
Dan Gohman223a5d22008-08-08 18:33:12 +00002665 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmana30370b2009-05-04 22:02:23 +00002666 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00002667 const Loop *NestedLoop = NestedAR->getLoop();
Dan Gohman63c020a2010-08-13 20:23:25 +00002668 if (L->contains(NestedLoop) ?
Dan Gohman51ad99d2010-01-21 02:09:26 +00002669 (L->getLoopDepth() < NestedLoop->getLoopDepth()) :
Dan Gohman63c020a2010-08-13 20:23:25 +00002670 (!NestedLoop->contains(L) &&
Dan Gohman51ad99d2010-01-21 02:09:26 +00002671 DT->dominates(L->getHeader(), NestedLoop->getHeader()))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002672 SmallVector<const SCEV *, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohmancb0efec2009-12-18 01:14:11 +00002673 NestedAR->op_end());
Dan Gohman223a5d22008-08-08 18:33:12 +00002674 Operands[0] = NestedAR->getStart();
Dan Gohmancc030b72009-06-26 22:36:20 +00002675 // AddRecs require their operands be loop-invariant with respect to their
2676 // loops. Don't perform this transformation if it would break this
2677 // requirement.
2678 bool AllInvariant = true;
2679 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002680 if (!isLoopInvariant(Operands[i], L)) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002681 AllInvariant = false;
2682 break;
2683 }
2684 if (AllInvariant) {
Andrew Trick8b55b732011-03-14 16:50:06 +00002685 // Create a recurrence for the outer loop with the same step size.
2686 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002687 // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
2688 // inner recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002689 SCEV::NoWrapFlags OuterFlags =
2690 maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
Andrew Trick8b55b732011-03-14 16:50:06 +00002691
2692 NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
Dan Gohmancc030b72009-06-26 22:36:20 +00002693 AllInvariant = true;
2694 for (unsigned i = 0, e = NestedOperands.size(); i != e; ++i)
Dan Gohmanafd6db92010-11-17 21:23:15 +00002695 if (!isLoopInvariant(NestedOperands[i], NestedLoop)) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002696 AllInvariant = false;
2697 break;
2698 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002699 if (AllInvariant) {
Dan Gohmancc030b72009-06-26 22:36:20 +00002700 // Ok, both add recurrences are valid after the transformation.
Andrew Trick8b55b732011-03-14 16:50:06 +00002701 //
Andrew Trick8b55b732011-03-14 16:50:06 +00002702 // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
2703 // the outer recurrence has the same property.
Andrew Trickf6b01ff2011-03-15 00:37:00 +00002704 SCEV::NoWrapFlags InnerFlags =
2705 maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
Andrew Trick8b55b732011-03-14 16:50:06 +00002706 return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
2707 }
Dan Gohmancc030b72009-06-26 22:36:20 +00002708 }
2709 // Reset Operands to its original state.
2710 Operands[0] = NestedAR;
Dan Gohman223a5d22008-08-08 18:33:12 +00002711 }
2712 }
2713
Dan Gohman8d67d2f2010-01-19 22:27:22 +00002714 // Okay, it looks like we really DO need an addrec expr. Check to see if we
2715 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002716 FoldingSetNodeID ID;
2717 ID.AddInteger(scAddRecExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002718 for (unsigned i = 0, e = Operands.size(); i != e; ++i)
2719 ID.AddPointer(Operands[i]);
2720 ID.AddPointer(L);
Craig Topper9f008862014-04-15 04:59:12 +00002721 void *IP = nullptr;
Dan Gohman51ad99d2010-01-21 02:09:26 +00002722 SCEVAddRecExpr *S =
2723 static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
2724 if (!S) {
Dan Gohman00524492010-03-18 01:17:13 +00002725 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Operands.size());
2726 std::uninitialized_copy(Operands.begin(), Operands.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002727 S = new (SCEVAllocator) SCEVAddRecExpr(ID.Intern(SCEVAllocator),
2728 O, Operands.size(), L);
Dan Gohman51ad99d2010-01-21 02:09:26 +00002729 UniqueSCEVs.InsertNode(S, IP);
2730 }
Andrew Trick8b55b732011-03-14 16:50:06 +00002731 S->setNoWrapFlags(Flags);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002732 return S;
Chris Lattnerd934c702004-04-02 20:23:17 +00002733}
2734
Dan Gohmanabd17092009-06-24 14:49:00 +00002735const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS,
2736 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002737 SmallVector<const SCEV *, 2> Ops;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002738 Ops.push_back(LHS);
2739 Ops.push_back(RHS);
2740 return getSMaxExpr(Ops);
2741}
2742
Dan Gohmanaf752342009-07-07 17:06:11 +00002743const SCEV *
2744ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002745 assert(!Ops.empty() && "Cannot get empty smax!");
2746 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002747#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002748 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002749 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002750 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002751 "SCEVSMaxExpr operand types don't match!");
2752#endif
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002753
2754 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002755 GroupByComplexity(Ops, LI);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002756
2757 // If there are any constants, fold them together.
2758 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002759 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002760 ++Idx;
2761 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002762 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002763 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002764 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002765 APIntOps::smax(LHSC->getValue()->getValue(),
2766 RHSC->getValue()->getValue()));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002767 Ops[0] = getConstant(Fold);
2768 Ops.erase(Ops.begin()+1); // Erase the folded element
2769 if (Ops.size() == 1) return Ops[0];
2770 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002771 }
2772
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002773 // If we are left with a constant minimum-int, strip it off.
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002774 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
2775 Ops.erase(Ops.begin());
2776 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002777 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(true)) {
2778 // If we have an smax with a constant maximum-int, it will always be
2779 // maximum-int.
2780 return Ops[0];
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002781 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002782
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002783 if (Ops.size() == 1) return Ops[0];
2784 }
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002785
2786 // Find the first SMax
2787 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
2788 ++Idx;
2789
2790 // Check to see if one of the operands is an SMax. If so, expand its operands
2791 // onto our operand list, and recurse to simplify.
2792 if (Idx < Ops.size()) {
2793 bool DeletedSMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002794 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002795 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002796 Ops.append(SMax->op_begin(), SMax->op_end());
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002797 DeletedSMax = true;
2798 }
2799
2800 if (DeletedSMax)
2801 return getSMaxExpr(Ops);
2802 }
2803
2804 // Okay, check to see if the same value occurs in the operand list twice. If
2805 // so, delete one. Since we sorted the list, these values are required to
2806 // be adjacent.
2807 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00002808 // X smax Y smax Y --> X smax Y
2809 // X smax Y --> X, if X is always greater than Y
2810 if (Ops[i] == Ops[i+1] ||
2811 isKnownPredicate(ICmpInst::ICMP_SGE, Ops[i], Ops[i+1])) {
2812 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2813 --i; --e;
2814 } else if (isKnownPredicate(ICmpInst::ICMP_SLE, Ops[i], Ops[i+1])) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002815 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2816 --i; --e;
2817 }
2818
2819 if (Ops.size() == 1) return Ops[0];
2820
2821 assert(!Ops.empty() && "Reduced smax down to nothing!");
2822
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002823 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002824 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002825 FoldingSetNodeID ID;
2826 ID.AddInteger(scSMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002827 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2828 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002829 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002830 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00002831 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2832 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002833 SCEV *S = new (SCEVAllocator) SCEVSMaxExpr(ID.Intern(SCEVAllocator),
2834 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002835 UniqueSCEVs.InsertNode(S, IP);
2836 return S;
Nick Lewyckycdb7e542007-11-25 22:41:31 +00002837}
2838
Dan Gohmanabd17092009-06-24 14:49:00 +00002839const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS,
2840 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00002841 SmallVector<const SCEV *, 2> Ops;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002842 Ops.push_back(LHS);
2843 Ops.push_back(RHS);
2844 return getUMaxExpr(Ops);
2845}
2846
Dan Gohmanaf752342009-07-07 17:06:11 +00002847const SCEV *
2848ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002849 assert(!Ops.empty() && "Cannot get empty umax!");
2850 if (Ops.size() == 1) return Ops[0];
Dan Gohmand33f36e2009-05-18 15:44:58 +00002851#ifndef NDEBUG
Chris Lattner229907c2011-07-18 04:54:35 +00002852 Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
Dan Gohmand33f36e2009-05-18 15:44:58 +00002853 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Dan Gohmanb6c773e2010-08-16 16:13:54 +00002854 assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
Dan Gohmand33f36e2009-05-18 15:44:58 +00002855 "SCEVUMaxExpr operand types don't match!");
2856#endif
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002857
2858 // Sort by complexity, this groups all similar expression types together.
Dan Gohman9ba542c2009-05-07 14:39:04 +00002859 GroupByComplexity(Ops, LI);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002860
2861 // If there are any constants, fold them together.
2862 unsigned Idx = 0;
Dan Gohmana30370b2009-05-04 22:02:23 +00002863 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002864 ++Idx;
2865 assert(Idx < Ops.size());
Dan Gohmana30370b2009-05-04 22:02:23 +00002866 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002867 // We found two constants, fold them together!
Owen Andersonedb4a702009-07-24 23:12:02 +00002868 ConstantInt *Fold = ConstantInt::get(getContext(),
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002869 APIntOps::umax(LHSC->getValue()->getValue(),
2870 RHSC->getValue()->getValue()));
2871 Ops[0] = getConstant(Fold);
2872 Ops.erase(Ops.begin()+1); // Erase the folded element
2873 if (Ops.size() == 1) return Ops[0];
2874 LHSC = cast<SCEVConstant>(Ops[0]);
2875 }
2876
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002877 // If we are left with a constant minimum-int, strip it off.
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002878 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
2879 Ops.erase(Ops.begin());
2880 --Idx;
Dan Gohmanf57bdb72009-06-24 14:46:22 +00002881 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isMaxValue(false)) {
2882 // If we have an umax with a constant maximum-int, it will always be
2883 // maximum-int.
2884 return Ops[0];
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002885 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002886
Dan Gohmanfe4b2912010-04-13 16:49:23 +00002887 if (Ops.size() == 1) return Ops[0];
2888 }
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002889
2890 // Find the first UMax
2891 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
2892 ++Idx;
2893
2894 // Check to see if one of the operands is a UMax. If so, expand its operands
2895 // onto our operand list, and recurse to simplify.
2896 if (Idx < Ops.size()) {
2897 bool DeletedUMax = false;
Dan Gohmana30370b2009-05-04 22:02:23 +00002898 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002899 Ops.erase(Ops.begin()+Idx);
Dan Gohmandd41bba2010-06-21 19:47:52 +00002900 Ops.append(UMax->op_begin(), UMax->op_end());
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002901 DeletedUMax = true;
2902 }
2903
2904 if (DeletedUMax)
2905 return getUMaxExpr(Ops);
2906 }
2907
2908 // Okay, check to see if the same value occurs in the operand list twice. If
2909 // so, delete one. Since we sorted the list, these values are required to
2910 // be adjacent.
2911 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
Dan Gohman7ef0dc22010-04-13 16:51:03 +00002912 // X umax Y umax Y --> X umax Y
2913 // X umax Y --> X, if X is always greater than Y
2914 if (Ops[i] == Ops[i+1] ||
2915 isKnownPredicate(ICmpInst::ICMP_UGE, Ops[i], Ops[i+1])) {
2916 Ops.erase(Ops.begin()+i+1, Ops.begin()+i+2);
2917 --i; --e;
2918 } else if (isKnownPredicate(ICmpInst::ICMP_ULE, Ops[i], Ops[i+1])) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002919 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
2920 --i; --e;
2921 }
2922
2923 if (Ops.size() == 1) return Ops[0];
2924
2925 assert(!Ops.empty() && "Reduced umax down to nothing!");
2926
2927 // Okay, it looks like we really DO need a umax expr. Check to see if we
2928 // already have one, otherwise create a new one.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002929 FoldingSetNodeID ID;
2930 ID.AddInteger(scUMaxExpr);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002931 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2932 ID.AddPointer(Ops[i]);
Craig Topper9f008862014-04-15 04:59:12 +00002933 void *IP = nullptr;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002934 if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
Dan Gohman00524492010-03-18 01:17:13 +00002935 const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
2936 std::uninitialized_copy(Ops.begin(), Ops.end(), O);
Dan Gohman01c65a22010-03-18 18:49:47 +00002937 SCEV *S = new (SCEVAllocator) SCEVUMaxExpr(ID.Intern(SCEVAllocator),
2938 O, Ops.size());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002939 UniqueSCEVs.InsertNode(S, IP);
2940 return S;
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00002941}
2942
Dan Gohmanabd17092009-06-24 14:49:00 +00002943const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
2944 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00002945 // ~smax(~x, ~y) == smin(x, y).
2946 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2947}
2948
Dan Gohmanabd17092009-06-24 14:49:00 +00002949const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS,
2950 const SCEV *RHS) {
Dan Gohman692b4682009-06-22 03:18:45 +00002951 // ~umax(~x, ~y) == umin(x, y)
2952 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
2953}
2954
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002955const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002956 // If we have DataLayout, we can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00002957 // constant expression and then folding it back into a ConstantInt.
2958 // This is just a compile-time optimization.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002959 if (DL)
2960 return getConstant(IntTy, DL->getTypeAllocSize(AllocTy));
Dan Gohman11862a62010-04-12 23:03:26 +00002961
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002962 Constant *C = ConstantExpr::getSizeOf(AllocTy);
2963 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002964 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmana3b6c4b2010-05-28 16:12:08 +00002965 C = Folded;
Chris Lattner229907c2011-07-18 04:54:35 +00002966 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(AllocTy));
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002967 assert(Ty == IntTy && "Effective SCEV type doesn't match");
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002968 return getTruncateOrZeroExtend(getSCEV(C), Ty);
2969}
2970
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002971const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
2972 StructType *STy,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00002973 unsigned FieldNo) {
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002974 // If we have DataLayout, we can bypass creating a target-independent
Dan Gohman11862a62010-04-12 23:03:26 +00002975 // constant expression and then folding it back into a ConstantInt.
2976 // This is just a compile-time optimization.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002977 if (DL) {
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002978 return getConstant(IntTy,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002979 DL->getStructLayout(STy)->getElementOffset(FieldNo));
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00002980 }
Dan Gohman11862a62010-04-12 23:03:26 +00002981
Dan Gohmancf913832010-01-28 02:15:55 +00002982 Constant *C = ConstantExpr::getOffsetOf(STy, FieldNo);
2983 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
Rafael Espindola7c68beb2014-02-18 15:33:12 +00002984 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmana3b6c4b2010-05-28 16:12:08 +00002985 C = Folded;
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00002986
Matt Arsenault4ed49b52013-10-21 18:08:09 +00002987 Type *Ty = getEffectiveSCEVType(PointerType::getUnqual(STy));
Dan Gohmancf913832010-01-28 02:15:55 +00002988 return getTruncateOrZeroExtend(getSCEV(C), Ty);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00002989}
2990
Dan Gohmanaf752342009-07-07 17:06:11 +00002991const SCEV *ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf436bac2009-06-24 00:54:57 +00002992 // Don't attempt to do anything other than create a SCEVUnknown object
2993 // here. createSCEV only calls getUnknown after checking for all other
2994 // interesting possibilities, and any other code that calls getUnknown
2995 // is doing so in order to hide a value from SCEV canonicalization.
2996
Dan Gohmanc5c85c02009-06-27 21:21:31 +00002997 FoldingSetNodeID ID;
2998 ID.AddInteger(scUnknown);
2999 ID.AddPointer(V);
Craig Topper9f008862014-04-15 04:59:12 +00003000 void *IP = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00003001 if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
3002 assert(cast<SCEVUnknown>(S)->getValue() == V &&
3003 "Stale SCEVUnknown in uniquing map!");
3004 return S;
3005 }
3006 SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
3007 FirstUnknown);
3008 FirstUnknown = cast<SCEVUnknown>(S);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003009 UniqueSCEVs.InsertNode(S, IP);
3010 return S;
Chris Lattnerb4f681b2004-04-15 15:07:24 +00003011}
3012
Chris Lattnerd934c702004-04-02 20:23:17 +00003013//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00003014// Basic SCEV Analysis and PHI Idiom Recognition Code
3015//
3016
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003017/// isSCEVable - Test if values of the given type are analyzable within
3018/// the SCEV framework. This primarily includes integer types, and it
3019/// can optionally include pointer types if the ScalarEvolution class
3020/// has access to target-specific information.
Chris Lattner229907c2011-07-18 04:54:35 +00003021bool ScalarEvolution::isSCEVable(Type *Ty) const {
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003022 // Integers and pointers are always SCEVable.
Duncan Sands19d0b472010-02-16 11:11:14 +00003023 return Ty->isIntegerTy() || Ty->isPointerTy();
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003024}
3025
3026/// getTypeSizeInBits - Return the size in bits of the specified type,
3027/// for which isSCEVable must return true.
Chris Lattner229907c2011-07-18 04:54:35 +00003028uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003029 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3030
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003031 // If we have a DataLayout, use it!
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003032 if (DL)
3033 return DL->getTypeSizeInBits(Ty);
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003034
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003035 // Integer types have fixed sizes.
Duncan Sands9dff9be2010-02-15 16:12:20 +00003036 if (Ty->isIntegerTy())
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003037 return Ty->getPrimitiveSizeInBits();
3038
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003039 // The only other support type is pointer. Without DataLayout, conservatively
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003040 // assume pointers are 64-bit.
Duncan Sands19d0b472010-02-16 11:11:14 +00003041 assert(Ty->isPointerTy() && "isSCEVable permitted a non-SCEVable type!");
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003042 return 64;
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003043}
3044
3045/// getEffectiveSCEVType - Return a type with the same bitwidth as
3046/// the given type and which represents how SCEV will treat the given
3047/// type, for which isSCEVable must return true. For pointer types,
3048/// this is the pointer-sized integer type.
Chris Lattner229907c2011-07-18 04:54:35 +00003049Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003050 assert(isSCEVable(Ty) && "Type is not SCEVable!");
3051
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003052 if (Ty->isIntegerTy()) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003053 return Ty;
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003054 }
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003055
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003056 // The only other support type is pointer.
Duncan Sands19d0b472010-02-16 11:11:14 +00003057 assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003058
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003059 if (DL)
3060 return DL->getIntPtrType(Ty);
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003061
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003062 // Without DataLayout, conservatively assume pointers are 64-bit.
Dan Gohmanbf2a9ae2009-08-18 16:46:41 +00003063 return Type::getInt64Ty(getContext());
Dan Gohman0a40ad92009-04-16 03:18:22 +00003064}
Chris Lattnerd934c702004-04-02 20:23:17 +00003065
Dan Gohmanaf752342009-07-07 17:06:11 +00003066const SCEV *ScalarEvolution::getCouldNotCompute() {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00003067 return &CouldNotCompute;
Dan Gohman31efa302009-04-18 17:58:19 +00003068}
3069
Shuxin Yangefc4c012013-07-08 17:33:13 +00003070namespace {
3071 // Helper class working with SCEVTraversal to figure out if a SCEV contains
3072 // a SCEVUnknown with null value-pointer. FindInvalidSCEVUnknown::FindOne
3073 // is set iff if find such SCEVUnknown.
3074 //
3075 struct FindInvalidSCEVUnknown {
3076 bool FindOne;
3077 FindInvalidSCEVUnknown() { FindOne = false; }
3078 bool follow(const SCEV *S) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00003079 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Shuxin Yangefc4c012013-07-08 17:33:13 +00003080 case scConstant:
3081 return false;
3082 case scUnknown:
Shuxin Yang23773b32013-07-12 07:25:38 +00003083 if (!cast<SCEVUnknown>(S)->getValue())
Shuxin Yangefc4c012013-07-08 17:33:13 +00003084 FindOne = true;
3085 return false;
3086 default:
3087 return true;
3088 }
3089 }
3090 bool isDone() const { return FindOne; }
3091 };
3092}
3093
3094bool ScalarEvolution::checkValidity(const SCEV *S) const {
3095 FindInvalidSCEVUnknown F;
3096 SCEVTraversal<FindInvalidSCEVUnknown> ST(F);
3097 ST.visitAll(S);
3098
3099 return !F.FindOne;
3100}
3101
Chris Lattnerd934c702004-04-02 20:23:17 +00003102/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
3103/// expression and create a new one.
Dan Gohmanaf752342009-07-07 17:06:11 +00003104const SCEV *ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003105 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Chris Lattnerd934c702004-04-02 20:23:17 +00003106
Shuxin Yangefc4c012013-07-08 17:33:13 +00003107 ValueExprMapType::iterator I = ValueExprMap.find_as(V);
3108 if (I != ValueExprMap.end()) {
3109 const SCEV *S = I->second;
Shuxin Yang23773b32013-07-12 07:25:38 +00003110 if (checkValidity(S))
Shuxin Yangefc4c012013-07-08 17:33:13 +00003111 return S;
3112 else
3113 ValueExprMap.erase(I);
3114 }
Dan Gohmanaf752342009-07-07 17:06:11 +00003115 const SCEV *S = createSCEV(V);
Dan Gohmanc29eeae2010-08-16 16:31:39 +00003116
3117 // The process of creating a SCEV for V may have caused other SCEVs
3118 // to have been created, so it's necessary to insert the new entry
3119 // from scratch, rather than trying to remember the insert position
3120 // above.
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003121 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Chris Lattnerd934c702004-04-02 20:23:17 +00003122 return S;
3123}
3124
Dan Gohman0a40ad92009-04-16 03:18:22 +00003125/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
3126///
Dan Gohmanaf752342009-07-07 17:06:11 +00003127const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003128 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson53a52212009-07-13 04:09:18 +00003129 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003130 cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003131
Chris Lattner229907c2011-07-18 04:54:35 +00003132 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003133 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003134 return getMulExpr(V,
Owen Anderson5a1acd92009-07-31 20:28:14 +00003135 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty))));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003136}
3137
3138/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanaf752342009-07-07 17:06:11 +00003139const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003140 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Owen Anderson542619e2009-07-13 20:58:05 +00003141 return getConstant(
Owen Anderson487375e2009-07-29 18:55:55 +00003142 cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003143
Chris Lattner229907c2011-07-18 04:54:35 +00003144 Type *Ty = V->getType();
Dan Gohmanc8e23622009-04-21 23:15:49 +00003145 Ty = getEffectiveSCEVType(Ty);
Owen Anderson542619e2009-07-13 20:58:05 +00003146 const SCEV *AllOnes =
Owen Anderson5a1acd92009-07-31 20:28:14 +00003147 getConstant(cast<ConstantInt>(Constant::getAllOnesValue(Ty)));
Dan Gohman0a40ad92009-04-16 03:18:22 +00003148 return getMinusSCEV(AllOnes, V);
3149}
3150
Andrew Trick8b55b732011-03-14 16:50:06 +00003151/// getMinusSCEV - Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
Chris Lattnerfc877522011-01-09 22:26:35 +00003152const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00003153 SCEV::NoWrapFlags Flags) {
Andrew Tricka34f1b12011-03-15 01:16:14 +00003154 assert(!maskFlags(Flags, SCEV::FlagNUW) && "subtraction does not have NUW");
3155
Dan Gohman46f00a22010-07-20 16:53:00 +00003156 // Fast path: X - X --> 0.
3157 if (LHS == RHS)
3158 return getConstant(LHS->getType(), 0);
3159
Dan Gohman0a40ad92009-04-16 03:18:22 +00003160 // X - Y --> X + -Y
Andrew Trick8b55b732011-03-14 16:50:06 +00003161 return getAddExpr(LHS, getNegativeSCEV(RHS), Flags);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003162}
3163
3164/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
3165/// input value to the specified type. If the type must be extended, it is zero
3166/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003167const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003168ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty) {
3169 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003170 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3171 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003172 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003173 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003174 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003175 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003176 return getTruncateExpr(V, Ty);
3177 return getZeroExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003178}
3179
3180/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
3181/// input value to the specified type. If the type must be extended, it is sign
3182/// extended.
Dan Gohmanaf752342009-07-07 17:06:11 +00003183const SCEV *
3184ScalarEvolution::getTruncateOrSignExtend(const SCEV *V,
Chris Lattner229907c2011-07-18 04:54:35 +00003185 Type *Ty) {
3186 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003187 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3188 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman0a40ad92009-04-16 03:18:22 +00003189 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003190 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman0a40ad92009-04-16 03:18:22 +00003191 return V; // No conversion
Dan Gohmanb397e1a2009-04-21 01:07:12 +00003192 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanc8e23622009-04-21 23:15:49 +00003193 return getTruncateExpr(V, Ty);
3194 return getSignExtendExpr(V, Ty);
Dan Gohman0a40ad92009-04-16 03:18:22 +00003195}
3196
Dan Gohmane712a2f2009-05-13 03:46:30 +00003197/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
3198/// input value to the specified type. If the type must be extended, it is zero
3199/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003200const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003201ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
3202 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003203 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3204 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003205 "Cannot noop or zero extend with non-integer arguments!");
3206 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3207 "getNoopOrZeroExtend cannot truncate!");
3208 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3209 return V; // No conversion
3210 return getZeroExtendExpr(V, Ty);
3211}
3212
3213/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
3214/// input value to the specified type. If the type must be extended, it is sign
3215/// extended. The conversion must not be narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003216const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003217ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
3218 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003219 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3220 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003221 "Cannot noop or sign extend with non-integer arguments!");
3222 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3223 "getNoopOrSignExtend cannot truncate!");
3224 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3225 return V; // No conversion
3226 return getSignExtendExpr(V, Ty);
3227}
3228
Dan Gohman8db2edc2009-06-13 15:56:47 +00003229/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
3230/// the input value to the specified type. If the type must be extended,
3231/// it is extended with unspecified bits. The conversion must not be
3232/// narrowing.
Dan Gohmanaf752342009-07-07 17:06:11 +00003233const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003234ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
3235 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003236 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3237 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohman8db2edc2009-06-13 15:56:47 +00003238 "Cannot noop or any extend with non-integer arguments!");
3239 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
3240 "getNoopOrAnyExtend cannot truncate!");
3241 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3242 return V; // No conversion
3243 return getAnyExtendExpr(V, Ty);
3244}
3245
Dan Gohmane712a2f2009-05-13 03:46:30 +00003246/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
3247/// input value to the specified type. The conversion must not be widening.
Dan Gohmanaf752342009-07-07 17:06:11 +00003248const SCEV *
Chris Lattner229907c2011-07-18 04:54:35 +00003249ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
3250 Type *SrcTy = V->getType();
Duncan Sands19d0b472010-02-16 11:11:14 +00003251 assert((SrcTy->isIntegerTy() || SrcTy->isPointerTy()) &&
3252 (Ty->isIntegerTy() || Ty->isPointerTy()) &&
Dan Gohmane712a2f2009-05-13 03:46:30 +00003253 "Cannot truncate or noop with non-integer arguments!");
3254 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
3255 "getTruncateOrNoop cannot extend!");
3256 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
3257 return V; // No conversion
3258 return getTruncateExpr(V, Ty);
3259}
3260
Dan Gohman96212b62009-06-22 00:31:57 +00003261/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
3262/// the types using zero-extension, and then perform a umax operation
3263/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003264const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
3265 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003266 const SCEV *PromotedLHS = LHS;
3267 const SCEV *PromotedRHS = RHS;
Dan Gohman96212b62009-06-22 00:31:57 +00003268
3269 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3270 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3271 else
3272 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3273
3274 return getUMaxExpr(PromotedLHS, PromotedRHS);
3275}
3276
Dan Gohman2bc22302009-06-22 15:03:27 +00003277/// getUMinFromMismatchedTypes - Promote the operands to the wider of
3278/// the types using zero-extension, and then perform a umin operation
3279/// with them.
Dan Gohmanabd17092009-06-24 14:49:00 +00003280const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
3281 const SCEV *RHS) {
Dan Gohmanaf752342009-07-07 17:06:11 +00003282 const SCEV *PromotedLHS = LHS;
3283 const SCEV *PromotedRHS = RHS;
Dan Gohman2bc22302009-06-22 15:03:27 +00003284
3285 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
3286 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
3287 else
3288 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
3289
3290 return getUMinExpr(PromotedLHS, PromotedRHS);
3291}
3292
Andrew Trick87716c92011-03-17 23:51:11 +00003293/// getPointerBase - Transitively follow the chain of pointer-type operands
3294/// until reaching a SCEV that does not have a single pointer operand. This
3295/// returns a SCEVUnknown pointer for well-formed pointer-type expressions,
3296/// but corner cases do exist.
3297const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
3298 // A pointer operand may evaluate to a nonpointer expression, such as null.
3299 if (!V->getType()->isPointerTy())
3300 return V;
3301
3302 if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(V)) {
3303 return getPointerBase(Cast->getOperand());
3304 }
3305 else if (const SCEVNAryExpr *NAry = dyn_cast<SCEVNAryExpr>(V)) {
Craig Topper9f008862014-04-15 04:59:12 +00003306 const SCEV *PtrOp = nullptr;
Andrew Trick87716c92011-03-17 23:51:11 +00003307 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
3308 I != E; ++I) {
3309 if ((*I)->getType()->isPointerTy()) {
3310 // Cannot find the base of an expression with multiple pointer operands.
3311 if (PtrOp)
3312 return V;
3313 PtrOp = *I;
3314 }
3315 }
3316 if (!PtrOp)
3317 return V;
3318 return getPointerBase(PtrOp);
3319 }
3320 return V;
3321}
3322
Dan Gohman0b89dff2009-07-25 01:13:03 +00003323/// PushDefUseChildren - Push users of the given Instruction
3324/// onto the given Worklist.
3325static void
3326PushDefUseChildren(Instruction *I,
3327 SmallVectorImpl<Instruction *> &Worklist) {
3328 // Push the def-use children onto the Worklist stack.
Chandler Carruthcdf47882014-03-09 03:16:01 +00003329 for (User *U : I->users())
3330 Worklist.push_back(cast<Instruction>(U));
Dan Gohman0b89dff2009-07-25 01:13:03 +00003331}
3332
3333/// ForgetSymbolicValue - This looks up computed SCEV values for all
3334/// instructions that depend on the given instruction and removes them from
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003335/// the ValueExprMapType map if they reference SymName. This is used during PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003336/// resolution.
Dan Gohmance973df2009-06-24 04:48:43 +00003337void
Dan Gohmana9c205c2010-02-25 06:57:05 +00003338ScalarEvolution::ForgetSymbolicName(Instruction *PN, const SCEV *SymName) {
Dan Gohman0b89dff2009-07-25 01:13:03 +00003339 SmallVector<Instruction *, 16> Worklist;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003340 PushDefUseChildren(PN, Worklist);
Chris Lattnerd934c702004-04-02 20:23:17 +00003341
Dan Gohman0b89dff2009-07-25 01:13:03 +00003342 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohmana9c205c2010-02-25 06:57:05 +00003343 Visited.insert(PN);
Dan Gohman0b89dff2009-07-25 01:13:03 +00003344 while (!Worklist.empty()) {
Dan Gohmana9c205c2010-02-25 06:57:05 +00003345 Instruction *I = Worklist.pop_back_val();
Dan Gohman0b89dff2009-07-25 01:13:03 +00003346 if (!Visited.insert(I)) continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003347
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003348 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00003349 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003350 if (It != ValueExprMap.end()) {
Dan Gohman761065e2010-11-17 02:44:44 +00003351 const SCEV *Old = It->second;
3352
Dan Gohman0b89dff2009-07-25 01:13:03 +00003353 // Short-circuit the def-use traversal if the symbolic name
3354 // ceases to appear in expressions.
Dan Gohman534749b2010-11-17 22:27:42 +00003355 if (Old != SymName && !hasOperand(Old, SymName))
Dan Gohman0b89dff2009-07-25 01:13:03 +00003356 continue;
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003357
Dan Gohman0b89dff2009-07-25 01:13:03 +00003358 // SCEVUnknown for a PHI either means that it has an unrecognized
Dan Gohmana9c205c2010-02-25 06:57:05 +00003359 // structure, it's a PHI that's in the progress of being computed
3360 // by createNodeForPHI, or it's a single-value PHI. In the first case,
3361 // additional loop trip count information isn't going to change anything.
3362 // In the second case, createNodeForPHI will perform the necessary
3363 // updates on its own when it gets to that point. In the third, we do
3364 // want to forget the SCEVUnknown.
3365 if (!isa<PHINode>(I) ||
Dan Gohman761065e2010-11-17 02:44:44 +00003366 !isa<SCEVUnknown>(Old) ||
3367 (I != PN && Old == SymName)) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00003368 forgetMemoizedResults(Old);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003369 ValueExprMap.erase(It);
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00003370 }
Dan Gohman0b89dff2009-07-25 01:13:03 +00003371 }
3372
3373 PushDefUseChildren(I, Worklist);
3374 }
Chris Lattner7b0fbe72005-02-13 04:37:18 +00003375}
Chris Lattnerd934c702004-04-02 20:23:17 +00003376
3377/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
3378/// a loop header, making it a potential recurrence, or it doesn't.
3379///
Dan Gohmanaf752342009-07-07 17:06:11 +00003380const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohman6635bb22010-04-12 07:49:36 +00003381 if (const Loop *L = LI->getLoopFor(PN->getParent()))
3382 if (L->getHeader() == PN->getParent()) {
3383 // The loop may have multiple entrances or multiple exits; we can analyze
3384 // this phi as an addrec if it has a unique entry value and a unique
3385 // backedge value.
Craig Topper9f008862014-04-15 04:59:12 +00003386 Value *BEValueV = nullptr, *StartValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003387 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3388 Value *V = PN->getIncomingValue(i);
3389 if (L->contains(PN->getIncomingBlock(i))) {
3390 if (!BEValueV) {
3391 BEValueV = V;
3392 } else if (BEValueV != V) {
Craig Topper9f008862014-04-15 04:59:12 +00003393 BEValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003394 break;
3395 }
3396 } else if (!StartValueV) {
3397 StartValueV = V;
3398 } else if (StartValueV != V) {
Craig Topper9f008862014-04-15 04:59:12 +00003399 StartValueV = nullptr;
Dan Gohman6635bb22010-04-12 07:49:36 +00003400 break;
3401 }
3402 }
3403 if (BEValueV && StartValueV) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003404 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanaf752342009-07-07 17:06:11 +00003405 const SCEV *SymbolicName = getUnknown(PN);
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00003406 assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
Chris Lattnerd934c702004-04-02 20:23:17 +00003407 "PHI node already processed?");
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003408 ValueExprMap.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Chris Lattnerd934c702004-04-02 20:23:17 +00003409
3410 // Using this symbolic name for the PHI, analyze the value coming around
3411 // the back-edge.
Dan Gohman0b89dff2009-07-25 01:13:03 +00003412 const SCEV *BEValue = getSCEV(BEValueV);
Chris Lattnerd934c702004-04-02 20:23:17 +00003413
3414 // NOTE: If BEValue is loop invariant, we know that the PHI node just
3415 // has a special value for the first iteration of the loop.
3416
3417 // If the value coming around the backedge is an add with the symbolic
3418 // value we just inserted, then we found a simple induction variable!
Dan Gohmana30370b2009-05-04 22:02:23 +00003419 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00003420 // If there is a single occurrence of the symbolic value, replace it
3421 // with a recurrence.
3422 unsigned FoundIndex = Add->getNumOperands();
3423 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3424 if (Add->getOperand(i) == SymbolicName)
3425 if (FoundIndex == e) {
3426 FoundIndex = i;
3427 break;
3428 }
3429
3430 if (FoundIndex != Add->getNumOperands()) {
3431 // Create an add with everything but the specified operand.
Dan Gohmanaf752342009-07-07 17:06:11 +00003432 SmallVector<const SCEV *, 8> Ops;
Chris Lattnerd934c702004-04-02 20:23:17 +00003433 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
3434 if (i != FoundIndex)
3435 Ops.push_back(Add->getOperand(i));
Dan Gohmanaf752342009-07-07 17:06:11 +00003436 const SCEV *Accum = getAddExpr(Ops);
Chris Lattnerd934c702004-04-02 20:23:17 +00003437
3438 // This is not a valid addrec if the step amount is varying each
3439 // loop iteration, but is not itself an addrec in this loop.
Dan Gohmanafd6db92010-11-17 21:23:15 +00003440 if (isLoopInvariant(Accum, L) ||
Chris Lattnerd934c702004-04-02 20:23:17 +00003441 (isa<SCEVAddRecExpr>(Accum) &&
3442 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003443 SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
Dan Gohman51ad99d2010-01-21 02:09:26 +00003444
3445 // If the increment doesn't overflow, then neither the addrec nor
3446 // the post-increment will overflow.
3447 if (const AddOperator *OBO = dyn_cast<AddOperator>(BEValueV)) {
3448 if (OBO->hasNoUnsignedWrap())
Andrew Trick8b55b732011-03-14 16:50:06 +00003449 Flags = setFlags(Flags, SCEV::FlagNUW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003450 if (OBO->hasNoSignedWrap())
Andrew Trick8b55b732011-03-14 16:50:06 +00003451 Flags = setFlags(Flags, SCEV::FlagNSW);
Benjamin Kramer6094f302013-10-28 07:30:06 +00003452 } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003453 // If the increment is an inbounds GEP, then we know the address
3454 // space cannot be wrapped around. We cannot make any guarantee
3455 // about signed or unsigned overflow because pointers are
3456 // unsigned but we may have a negative index from the base
Benjamin Kramer6094f302013-10-28 07:30:06 +00003457 // pointer. We can guarantee that no unsigned wrap occurs if the
3458 // indices form a positive value.
3459 if (GEP->isInBounds()) {
Andrew Trickf6b01ff2011-03-15 00:37:00 +00003460 Flags = setFlags(Flags, SCEV::FlagNW);
Benjamin Kramer6094f302013-10-28 07:30:06 +00003461
3462 const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
3463 if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
3464 Flags = setFlags(Flags, SCEV::FlagNUW);
3465 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00003466 } else if (const SubOperator *OBO =
3467 dyn_cast<SubOperator>(BEValueV)) {
3468 if (OBO->hasNoUnsignedWrap())
3469 Flags = setFlags(Flags, SCEV::FlagNUW);
3470 if (OBO->hasNoSignedWrap())
3471 Flags = setFlags(Flags, SCEV::FlagNSW);
Dan Gohman51ad99d2010-01-21 02:09:26 +00003472 }
3473
Dan Gohman6635bb22010-04-12 07:49:36 +00003474 const SCEV *StartVal = getSCEV(StartValueV);
Andrew Trick8b55b732011-03-14 16:50:06 +00003475 const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
Dan Gohman62ef6a72009-07-25 01:22:26 +00003476
Dan Gohman51ad99d2010-01-21 02:09:26 +00003477 // Since the no-wrap flags are on the increment, they apply to the
3478 // post-incremented value as well.
Dan Gohmanafd6db92010-11-17 21:23:15 +00003479 if (isLoopInvariant(Accum, L))
Dan Gohman51ad99d2010-01-21 02:09:26 +00003480 (void)getAddRecExpr(getAddExpr(StartVal, Accum),
Andrew Trick8b55b732011-03-14 16:50:06 +00003481 Accum, L, Flags);
Chris Lattnerd934c702004-04-02 20:23:17 +00003482
3483 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003484 // to be symbolic. We now need to go back and purge all of the
3485 // entries for the scalars that use the symbolic expression.
3486 ForgetSymbolicName(PN, SymbolicName);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003487 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattnerd934c702004-04-02 20:23:17 +00003488 return PHISCEV;
3489 }
3490 }
Dan Gohmana30370b2009-05-04 22:02:23 +00003491 } else if (const SCEVAddRecExpr *AddRec =
3492 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003493 // Otherwise, this could be a loop like this:
3494 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
3495 // In this case, j = {1,+,1} and BEValue is j.
3496 // Because the other in-value of i (0) fits the evolution of BEValue
3497 // i really is an addrec evolution.
3498 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Dan Gohman6635bb22010-04-12 07:49:36 +00003499 const SCEV *StartVal = getSCEV(StartValueV);
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003500
3501 // If StartVal = j.start - j.stride, we can use StartVal as the
3502 // initial step of the addrec evolution.
Dan Gohmanc8e23622009-04-21 23:15:49 +00003503 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman068b7932010-04-11 23:44:58 +00003504 AddRec->getOperand(1))) {
Andrew Trick8b55b732011-03-14 16:50:06 +00003505 // FIXME: For constant StartVal, we should be able to infer
3506 // no-wrap flags.
Dan Gohmanaf752342009-07-07 17:06:11 +00003507 const SCEV *PHISCEV =
Andrew Trick8b55b732011-03-14 16:50:06 +00003508 getAddRecExpr(StartVal, AddRec->getOperand(1), L,
3509 SCEV::FlagAnyWrap);
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003510
3511 // Okay, for the entire analysis of this edge we assumed the PHI
Dan Gohman0b89dff2009-07-25 01:13:03 +00003512 // to be symbolic. We now need to go back and purge all of the
3513 // entries for the scalars that use the symbolic expression.
3514 ForgetSymbolicName(PN, SymbolicName);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00003515 ValueExprMap[SCEVCallbackVH(PN, this)] = PHISCEV;
Chris Lattnere8cbdbf2006-04-26 18:34:07 +00003516 return PHISCEV;
3517 }
3518 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003519 }
Chris Lattnerd934c702004-04-02 20:23:17 +00003520 }
Dan Gohman6635bb22010-04-12 07:49:36 +00003521 }
Misha Brukman01808ca2005-04-21 21:13:18 +00003522
Dan Gohmana9c205c2010-02-25 06:57:05 +00003523 // If the PHI has a single incoming value, follow that value, unless the
3524 // PHI's incoming blocks are in a different loop, in which case doing so
3525 // risks breaking LCSSA form. Instcombine would normally zap these, but
3526 // it doesn't have DominatorTree information, so it may miss cases.
Hal Finkel60db0582014-09-07 18:57:58 +00003527 if (Value *V = SimplifyInstruction(PN, DL, TLI, DT, AT))
Duncan Sandsaef146b2010-11-18 19:59:41 +00003528 if (LI->replacementPreservesLCSSAForm(PN, V))
Dan Gohmana9c205c2010-02-25 06:57:05 +00003529 return getSCEV(V);
Duncan Sands39d771312010-11-17 20:49:12 +00003530
Chris Lattnerd934c702004-04-02 20:23:17 +00003531 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanc8e23622009-04-21 23:15:49 +00003532 return getUnknown(PN);
Chris Lattnerd934c702004-04-02 20:23:17 +00003533}
3534
Dan Gohmanee750d12009-05-08 20:26:55 +00003535/// createNodeForGEP - Expand GEP instructions into add and multiply
3536/// operations. This allows them to be analyzed by regular SCEV code.
3537///
Dan Gohmanb256ccf2009-12-18 02:09:29 +00003538const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
Chris Lattner229907c2011-07-18 04:54:35 +00003539 Type *IntPtrTy = getEffectiveSCEVType(GEP->getType());
Dan Gohman2173bd32009-05-08 20:36:47 +00003540 Value *Base = GEP->getOperand(0);
Dan Gohman30f24fe2009-05-09 00:14:52 +00003541 // Don't attempt to analyze GEPs over unsized objects.
Matt Arsenault404c60a2013-10-21 19:43:56 +00003542 if (!Base->getType()->getPointerElementType()->isSized())
Dan Gohman30f24fe2009-05-09 00:14:52 +00003543 return getUnknown(GEP);
Matt Arsenault4c265902013-09-27 22:38:23 +00003544
3545 // Don't blindly transfer the inbounds flag from the GEP instruction to the
3546 // Add expression, because the Instruction may be guarded by control flow
3547 // and the no-overflow bits may not be valid for the expression in any
3548 // context.
3549 SCEV::NoWrapFlags Wrap = GEP->isInBounds() ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
3550
Dan Gohman1d2ded72010-05-03 22:09:21 +00003551 const SCEV *TotalOffset = getConstant(IntPtrTy, 0);
Dan Gohman2173bd32009-05-08 20:36:47 +00003552 gep_type_iterator GTI = gep_type_begin(GEP);
Benjamin Kramerb6d0bd42014-03-02 12:27:27 +00003553 for (GetElementPtrInst::op_iterator I = std::next(GEP->op_begin()),
Dan Gohman2173bd32009-05-08 20:36:47 +00003554 E = GEP->op_end();
Dan Gohmanee750d12009-05-08 20:26:55 +00003555 I != E; ++I) {
3556 Value *Index = *I;
3557 // Compute the (potentially symbolic) offset in bytes for this index.
Chris Lattner229907c2011-07-18 04:54:35 +00003558 if (StructType *STy = dyn_cast<StructType>(*GTI++)) {
Dan Gohmanee750d12009-05-08 20:26:55 +00003559 // For a struct, add the member offset.
Dan Gohmanee750d12009-05-08 20:26:55 +00003560 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003561 const SCEV *FieldOffset = getOffsetOfExpr(IntPtrTy, STy, FieldNo);
Dan Gohman16206132010-06-30 07:16:37 +00003562
Dan Gohman16206132010-06-30 07:16:37 +00003563 // Add the field offset to the running total offset.
Dan Gohmanc0cca7f2010-06-30 17:27:11 +00003564 TotalOffset = getAddExpr(TotalOffset, FieldOffset);
Dan Gohmanee750d12009-05-08 20:26:55 +00003565 } else {
3566 // For an array, add the element offset, explicitly scaled.
Matt Arsenaulta90a18e2013-09-10 19:55:24 +00003567 const SCEV *ElementSize = getSizeOfExpr(IntPtrTy, *GTI);
Dan Gohman16206132010-06-30 07:16:37 +00003568 const SCEV *IndexS = getSCEV(Index);
Dan Gohman8b0a4192010-03-01 17:49:51 +00003569 // Getelementptr indices are signed.
Dan Gohman16206132010-06-30 07:16:37 +00003570 IndexS = getTruncateOrSignExtend(IndexS, IntPtrTy);
3571
Dan Gohman16206132010-06-30 07:16:37 +00003572 // Multiply the index by the element size to compute the element offset.
Matt Arsenault4c265902013-09-27 22:38:23 +00003573 const SCEV *LocalOffset = getMulExpr(IndexS, ElementSize, Wrap);
Dan Gohman16206132010-06-30 07:16:37 +00003574
3575 // Add the element offset to the running total offset.
Dan Gohmanc0cca7f2010-06-30 17:27:11 +00003576 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohmanee750d12009-05-08 20:26:55 +00003577 }
3578 }
Dan Gohman16206132010-06-30 07:16:37 +00003579
3580 // Get the SCEV for the GEP base.
3581 const SCEV *BaseS = getSCEV(Base);
3582
Dan Gohman16206132010-06-30 07:16:37 +00003583 // Add the total offset from all the GEP indices to the base.
Matt Arsenault4c265902013-09-27 22:38:23 +00003584 return getAddExpr(BaseS, TotalOffset, Wrap);
Dan Gohmanee750d12009-05-08 20:26:55 +00003585}
3586
Nick Lewycky3783b462007-11-22 07:59:40 +00003587/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
3588/// guaranteed to end in (at every loop iteration). It is, at the same time,
3589/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
3590/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003591uint32_t
Dan Gohmanaf752342009-07-07 17:06:11 +00003592ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
Dan Gohmana30370b2009-05-04 22:02:23 +00003593 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner69ec1ec2007-11-23 22:36:49 +00003594 return C->getValue()->getValue().countTrailingZeros();
Chris Lattner49b090e2006-12-12 02:26:09 +00003595
Dan Gohmana30370b2009-05-04 22:02:23 +00003596 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanc702fc02009-06-19 23:29:04 +00003597 return std::min(GetMinTrailingZeros(T->getOperand()),
3598 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky3783b462007-11-22 07:59:40 +00003599
Dan Gohmana30370b2009-05-04 22:02:23 +00003600 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00003601 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3602 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3603 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00003604 }
3605
Dan Gohmana30370b2009-05-04 22:02:23 +00003606 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanc702fc02009-06-19 23:29:04 +00003607 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
3608 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
3609 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky3783b462007-11-22 07:59:40 +00003610 }
3611
Dan Gohmana30370b2009-05-04 22:02:23 +00003612 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003613 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003614 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00003615 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003616 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00003617 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003618 }
3619
Dan Gohmana30370b2009-05-04 22:02:23 +00003620 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003621 // The result is the sum of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003622 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
3623 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky3783b462007-11-22 07:59:40 +00003624 for (unsigned i = 1, e = M->getNumOperands();
3625 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003626 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky3783b462007-11-22 07:59:40 +00003627 BitWidth);
3628 return SumOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003629 }
Nick Lewycky3783b462007-11-22 07:59:40 +00003630
Dan Gohmana30370b2009-05-04 22:02:23 +00003631 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky3783b462007-11-22 07:59:40 +00003632 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003633 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky3783b462007-11-22 07:59:40 +00003634 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003635 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky3783b462007-11-22 07:59:40 +00003636 return MinOpRes;
Chris Lattner49b090e2006-12-12 02:26:09 +00003637 }
Nick Lewycky3783b462007-11-22 07:59:40 +00003638
Dan Gohmana30370b2009-05-04 22:02:23 +00003639 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003640 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003641 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003642 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003643 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckycdb7e542007-11-25 22:41:31 +00003644 return MinOpRes;
3645 }
3646
Dan Gohmana30370b2009-05-04 22:02:23 +00003647 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003648 // The result is the min of all operands results.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003649 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003650 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanc702fc02009-06-19 23:29:04 +00003651 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00003652 return MinOpRes;
3653 }
3654
Dan Gohmanc702fc02009-06-19 23:29:04 +00003655 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
3656 // For a SCEVUnknown, ask ValueTracking.
3657 unsigned BitWidth = getTypeSizeInBits(U->getType());
Dan Gohmanc702fc02009-06-19 23:29:04 +00003658 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003659 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003660 return Zeros.countTrailingOnes();
3661 }
3662
3663 // SCEVUDivExpr
Nick Lewycky3783b462007-11-22 07:59:40 +00003664 return 0;
Chris Lattner49b090e2006-12-12 02:26:09 +00003665}
Chris Lattnerd934c702004-04-02 20:23:17 +00003666
Sanjoy Das1f05c512014-10-10 21:22:34 +00003667/// GetRangeFromMetadata - Helper method to assign a range to V from
3668/// metadata present in the IR.
3669static Optional<ConstantRange> GetRangeFromMetadata(Value *V) {
3670 if (Instruction *I = dyn_cast<Instruction>(V)) {
3671 if (MDNode *MD = I->getMetadata(LLVMContext::MD_range)) {
3672 ConstantRange TotalRange(
3673 cast<IntegerType>(I->getType())->getBitWidth(), false);
3674
3675 unsigned NumRanges = MD->getNumOperands() / 2;
3676 assert(NumRanges >= 1);
3677
3678 for (unsigned i = 0; i < NumRanges; ++i) {
3679 ConstantInt *Lower = cast<ConstantInt>(MD->getOperand(2*i + 0));
3680 ConstantInt *Upper = cast<ConstantInt>(MD->getOperand(2*i + 1));
3681 ConstantRange Range(Lower->getValue(), Upper->getValue());
3682 TotalRange = TotalRange.unionWith(Range);
3683 }
3684
3685 return TotalRange;
3686 }
3687 }
3688
3689 return None;
3690}
3691
Dan Gohmane65c9172009-07-13 21:35:55 +00003692/// getUnsignedRange - Determine the unsigned range for a particular SCEV.
3693///
3694ConstantRange
3695ScalarEvolution::getUnsignedRange(const SCEV *S) {
Dan Gohman761065e2010-11-17 02:44:44 +00003696 // See if we've computed this range already.
3697 DenseMap<const SCEV *, ConstantRange>::iterator I = UnsignedRanges.find(S);
3698 if (I != UnsignedRanges.end())
3699 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00003700
3701 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohmaned756312010-11-17 20:23:08 +00003702 return setUnsignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003703
Dan Gohman85be4332010-01-26 19:19:05 +00003704 unsigned BitWidth = getTypeSizeInBits(S->getType());
3705 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3706
3707 // If the value has known zeros, the maximum unsigned value will have those
3708 // known zeros as well.
3709 uint32_t TZ = GetMinTrailingZeros(S);
3710 if (TZ != 0)
3711 ConservativeResult =
3712 ConstantRange(APInt::getMinValue(BitWidth),
3713 APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
3714
Dan Gohmane65c9172009-07-13 21:35:55 +00003715 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3716 ConstantRange X = getUnsignedRange(Add->getOperand(0));
3717 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3718 X = X.add(getUnsignedRange(Add->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003719 return setUnsignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003720 }
3721
3722 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3723 ConstantRange X = getUnsignedRange(Mul->getOperand(0));
3724 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3725 X = X.multiply(getUnsignedRange(Mul->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003726 return setUnsignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003727 }
3728
3729 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3730 ConstantRange X = getUnsignedRange(SMax->getOperand(0));
3731 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3732 X = X.smax(getUnsignedRange(SMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003733 return setUnsignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003734 }
3735
3736 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3737 ConstantRange X = getUnsignedRange(UMax->getOperand(0));
3738 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3739 X = X.umax(getUnsignedRange(UMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003740 return setUnsignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003741 }
3742
3743 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3744 ConstantRange X = getUnsignedRange(UDiv->getLHS());
3745 ConstantRange Y = getUnsignedRange(UDiv->getRHS());
Dan Gohmaned756312010-11-17 20:23:08 +00003746 return setUnsignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003747 }
3748
3749 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3750 ConstantRange X = getUnsignedRange(ZExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003751 return setUnsignedRange(ZExt,
3752 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003753 }
3754
3755 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3756 ConstantRange X = getUnsignedRange(SExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003757 return setUnsignedRange(SExt,
3758 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003759 }
3760
3761 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3762 ConstantRange X = getUnsignedRange(Trunc->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003763 return setUnsignedRange(Trunc,
3764 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003765 }
3766
Dan Gohmane65c9172009-07-13 21:35:55 +00003767 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00003768 // If there's no unsigned wrap, the value will never be less than its
3769 // initial value.
Andrew Trick8b55b732011-03-14 16:50:06 +00003770 if (AddRec->getNoWrapFlags(SCEV::FlagNUW))
Dan Gohman51ad99d2010-01-21 02:09:26 +00003771 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(AddRec->getStart()))
Dan Gohmanebbd05f2010-04-12 23:08:18 +00003772 if (!C->getValue()->isZero())
Dan Gohmanae4a4142010-04-11 22:12:18 +00003773 ConservativeResult =
Dan Gohman9396b422010-06-30 06:58:35 +00003774 ConservativeResult.intersectWith(
3775 ConstantRange(C->getValue()->getValue(), APInt(BitWidth, 0)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003776
3777 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00003778 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003779 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00003780 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00003781 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3782 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohmane65c9172009-07-13 21:35:55 +00003783 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3784
3785 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00003786 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmane65c9172009-07-13 21:35:55 +00003787
3788 ConstantRange StartRange = getUnsignedRange(Start);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003789 ConstantRange StepRange = getSignedRange(Step);
3790 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3791 ConstantRange EndRange =
3792 StartRange.add(MaxBECountRange.multiply(StepRange));
3793
3794 // Check for overflow. This must be done with ConstantRange arithmetic
3795 // because we could be called from within the ScalarEvolution overflow
3796 // checking code.
3797 ConstantRange ExtStartRange = StartRange.zextOrTrunc(BitWidth*2+1);
3798 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3799 ConstantRange ExtMaxBECountRange =
3800 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3801 ConstantRange ExtEndRange = EndRange.zextOrTrunc(BitWidth*2+1);
3802 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3803 ExtEndRange)
Dan Gohmaned756312010-11-17 20:23:08 +00003804 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003805
Dan Gohmane65c9172009-07-13 21:35:55 +00003806 APInt Min = APIntOps::umin(StartRange.getUnsignedMin(),
3807 EndRange.getUnsignedMin());
3808 APInt Max = APIntOps::umax(StartRange.getUnsignedMax(),
3809 EndRange.getUnsignedMax());
3810 if (Min.isMinValue() && Max.isMaxValue())
Dan Gohmaned756312010-11-17 20:23:08 +00003811 return setUnsignedRange(AddRec, ConservativeResult);
3812 return setUnsignedRange(AddRec,
3813 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003814 }
3815 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00003816
Dan Gohmaned756312010-11-17 20:23:08 +00003817 return setUnsignedRange(AddRec, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003818 }
3819
3820 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00003821 // Check if the IR explicitly contains !range metadata.
3822 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3823 if (MDRange.hasValue())
3824 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3825
Dan Gohmanc702fc02009-06-19 23:29:04 +00003826 // For a SCEVUnknown, ask ValueTracking.
Dan Gohmanc702fc02009-06-19 23:29:04 +00003827 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00003828 computeKnownBits(U->getValue(), Zeros, Ones, DL, 0, AT, nullptr, DT);
Dan Gohman1a7ab942009-07-20 22:34:18 +00003829 if (Ones == ~Zeros + 1)
Dan Gohmaned756312010-11-17 20:23:08 +00003830 return setUnsignedRange(U, ConservativeResult);
3831 return setUnsignedRange(U,
3832 ConservativeResult.intersectWith(ConstantRange(Ones, ~Zeros + 1)));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003833 }
3834
Dan Gohmaned756312010-11-17 20:23:08 +00003835 return setUnsignedRange(S, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003836}
3837
Dan Gohmane65c9172009-07-13 21:35:55 +00003838/// getSignedRange - Determine the signed range for a particular SCEV.
3839///
3840ConstantRange
3841ScalarEvolution::getSignedRange(const SCEV *S) {
Dan Gohman3ac8cd62011-01-24 17:54:18 +00003842 // See if we've computed this range already.
Dan Gohman761065e2010-11-17 02:44:44 +00003843 DenseMap<const SCEV *, ConstantRange>::iterator I = SignedRanges.find(S);
3844 if (I != SignedRanges.end())
3845 return I->second;
Dan Gohmanc702fc02009-06-19 23:29:04 +00003846
Dan Gohmane65c9172009-07-13 21:35:55 +00003847 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Dan Gohmaned756312010-11-17 20:23:08 +00003848 return setSignedRange(C, ConstantRange(C->getValue()->getValue()));
Dan Gohmane65c9172009-07-13 21:35:55 +00003849
Dan Gohman51aaf022010-01-26 04:40:18 +00003850 unsigned BitWidth = getTypeSizeInBits(S->getType());
3851 ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
3852
3853 // If the value has known zeros, the maximum signed value will have those
3854 // known zeros as well.
3855 uint32_t TZ = GetMinTrailingZeros(S);
3856 if (TZ != 0)
3857 ConservativeResult =
3858 ConstantRange(APInt::getSignedMinValue(BitWidth),
3859 APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
3860
Dan Gohmane65c9172009-07-13 21:35:55 +00003861 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
3862 ConstantRange X = getSignedRange(Add->getOperand(0));
3863 for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
3864 X = X.add(getSignedRange(Add->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003865 return setSignedRange(Add, ConservativeResult.intersectWith(X));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003866 }
3867
Dan Gohmane65c9172009-07-13 21:35:55 +00003868 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3869 ConstantRange X = getSignedRange(Mul->getOperand(0));
3870 for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
3871 X = X.multiply(getSignedRange(Mul->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003872 return setSignedRange(Mul, ConservativeResult.intersectWith(X));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003873 }
3874
Dan Gohmane65c9172009-07-13 21:35:55 +00003875 if (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(S)) {
3876 ConstantRange X = getSignedRange(SMax->getOperand(0));
3877 for (unsigned i = 1, e = SMax->getNumOperands(); i != e; ++i)
3878 X = X.smax(getSignedRange(SMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003879 return setSignedRange(SMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003880 }
Dan Gohmand261d272009-06-24 01:05:09 +00003881
Dan Gohmane65c9172009-07-13 21:35:55 +00003882 if (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(S)) {
3883 ConstantRange X = getSignedRange(UMax->getOperand(0));
3884 for (unsigned i = 1, e = UMax->getNumOperands(); i != e; ++i)
3885 X = X.umax(getSignedRange(UMax->getOperand(i)));
Dan Gohmaned756312010-11-17 20:23:08 +00003886 return setSignedRange(UMax, ConservativeResult.intersectWith(X));
Dan Gohmane65c9172009-07-13 21:35:55 +00003887 }
Dan Gohmand261d272009-06-24 01:05:09 +00003888
Dan Gohmane65c9172009-07-13 21:35:55 +00003889 if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
3890 ConstantRange X = getSignedRange(UDiv->getLHS());
3891 ConstantRange Y = getSignedRange(UDiv->getRHS());
Dan Gohmaned756312010-11-17 20:23:08 +00003892 return setSignedRange(UDiv, ConservativeResult.intersectWith(X.udiv(Y)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003893 }
Dan Gohmand261d272009-06-24 01:05:09 +00003894
Dan Gohmane65c9172009-07-13 21:35:55 +00003895 if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S)) {
3896 ConstantRange X = getSignedRange(ZExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003897 return setSignedRange(ZExt,
3898 ConservativeResult.intersectWith(X.zeroExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003899 }
3900
3901 if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S)) {
3902 ConstantRange X = getSignedRange(SExt->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003903 return setSignedRange(SExt,
3904 ConservativeResult.intersectWith(X.signExtend(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003905 }
3906
3907 if (const SCEVTruncateExpr *Trunc = dyn_cast<SCEVTruncateExpr>(S)) {
3908 ConstantRange X = getSignedRange(Trunc->getOperand());
Dan Gohmaned756312010-11-17 20:23:08 +00003909 return setSignedRange(Trunc,
3910 ConservativeResult.intersectWith(X.truncate(BitWidth)));
Dan Gohmane65c9172009-07-13 21:35:55 +00003911 }
3912
Dan Gohmane65c9172009-07-13 21:35:55 +00003913 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(S)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00003914 // If there's no signed wrap, and all the operands have the same sign or
3915 // zero, the value won't ever change sign.
Andrew Trick8b55b732011-03-14 16:50:06 +00003916 if (AddRec->getNoWrapFlags(SCEV::FlagNSW)) {
Dan Gohman51ad99d2010-01-21 02:09:26 +00003917 bool AllNonNeg = true;
3918 bool AllNonPos = true;
3919 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
3920 if (!isKnownNonNegative(AddRec->getOperand(i))) AllNonNeg = false;
3921 if (!isKnownNonPositive(AddRec->getOperand(i))) AllNonPos = false;
3922 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00003923 if (AllNonNeg)
Dan Gohman51aaf022010-01-26 04:40:18 +00003924 ConservativeResult = ConservativeResult.intersectWith(
3925 ConstantRange(APInt(BitWidth, 0),
3926 APInt::getSignedMinValue(BitWidth)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00003927 else if (AllNonPos)
Dan Gohman51aaf022010-01-26 04:40:18 +00003928 ConservativeResult = ConservativeResult.intersectWith(
3929 ConstantRange(APInt::getSignedMinValue(BitWidth),
3930 APInt(BitWidth, 1)));
Dan Gohman51ad99d2010-01-21 02:09:26 +00003931 }
Dan Gohmane65c9172009-07-13 21:35:55 +00003932
3933 // TODO: non-affine addrec
Dan Gohman85be4332010-01-26 19:19:05 +00003934 if (AddRec->isAffine()) {
Chris Lattner229907c2011-07-18 04:54:35 +00003935 Type *Ty = AddRec->getType();
Dan Gohmane65c9172009-07-13 21:35:55 +00003936 const SCEV *MaxBECount = getMaxBackedgeTakenCount(AddRec->getLoop());
Dan Gohman85be4332010-01-26 19:19:05 +00003937 if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
3938 getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
Dan Gohmane65c9172009-07-13 21:35:55 +00003939 MaxBECount = getNoopOrZeroExtend(MaxBECount, Ty);
3940
3941 const SCEV *Start = AddRec->getStart();
Dan Gohmanf76210e2010-04-12 07:39:33 +00003942 const SCEV *Step = AddRec->getStepRecurrence(*this);
Dan Gohmane65c9172009-07-13 21:35:55 +00003943
3944 ConstantRange StartRange = getSignedRange(Start);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003945 ConstantRange StepRange = getSignedRange(Step);
3946 ConstantRange MaxBECountRange = getUnsignedRange(MaxBECount);
3947 ConstantRange EndRange =
3948 StartRange.add(MaxBECountRange.multiply(StepRange));
3949
3950 // Check for overflow. This must be done with ConstantRange arithmetic
3951 // because we could be called from within the ScalarEvolution overflow
3952 // checking code.
3953 ConstantRange ExtStartRange = StartRange.sextOrTrunc(BitWidth*2+1);
3954 ConstantRange ExtStepRange = StepRange.sextOrTrunc(BitWidth*2+1);
3955 ConstantRange ExtMaxBECountRange =
3956 MaxBECountRange.zextOrTrunc(BitWidth*2+1);
3957 ConstantRange ExtEndRange = EndRange.sextOrTrunc(BitWidth*2+1);
3958 if (ExtStartRange.add(ExtMaxBECountRange.multiply(ExtStepRange)) !=
3959 ExtEndRange)
Dan Gohmaned756312010-11-17 20:23:08 +00003960 return setSignedRange(AddRec, ConservativeResult);
Dan Gohmanf76210e2010-04-12 07:39:33 +00003961
Dan Gohmane65c9172009-07-13 21:35:55 +00003962 APInt Min = APIntOps::smin(StartRange.getSignedMin(),
3963 EndRange.getSignedMin());
3964 APInt Max = APIntOps::smax(StartRange.getSignedMax(),
3965 EndRange.getSignedMax());
3966 if (Min.isMinSignedValue() && Max.isMaxSignedValue())
Dan Gohmaned756312010-11-17 20:23:08 +00003967 return setSignedRange(AddRec, ConservativeResult);
3968 return setSignedRange(AddRec,
3969 ConservativeResult.intersectWith(ConstantRange(Min, Max+1)));
Dan Gohmand261d272009-06-24 01:05:09 +00003970 }
Dan Gohmand261d272009-06-24 01:05:09 +00003971 }
Dan Gohman51ad99d2010-01-21 02:09:26 +00003972
Dan Gohmaned756312010-11-17 20:23:08 +00003973 return setSignedRange(AddRec, ConservativeResult);
Dan Gohmand261d272009-06-24 01:05:09 +00003974 }
3975
Dan Gohmanc702fc02009-06-19 23:29:04 +00003976 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
Sanjoy Das1f05c512014-10-10 21:22:34 +00003977 // Check if the IR explicitly contains !range metadata.
3978 Optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
3979 if (MDRange.hasValue())
3980 ConservativeResult = ConservativeResult.intersectWith(MDRange.getValue());
3981
Dan Gohmanc702fc02009-06-19 23:29:04 +00003982 // For a SCEVUnknown, ask ValueTracking.
Rafael Espindola7c68beb2014-02-18 15:33:12 +00003983 if (!U->getValue()->getType()->isIntegerTy() && !DL)
Dan Gohmaned756312010-11-17 20:23:08 +00003984 return setSignedRange(U, ConservativeResult);
Hal Finkel60db0582014-09-07 18:57:58 +00003985 unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, AT, nullptr, DT);
Hal Finkelff666bd2013-07-09 18:16:16 +00003986 if (NS <= 1)
Dan Gohmaned756312010-11-17 20:23:08 +00003987 return setSignedRange(U, ConservativeResult);
3988 return setSignedRange(U, ConservativeResult.intersectWith(
Dan Gohmane65c9172009-07-13 21:35:55 +00003989 ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
Dan Gohmaned756312010-11-17 20:23:08 +00003990 APInt::getSignedMaxValue(BitWidth).ashr(NS - 1)+1)));
Dan Gohmanc702fc02009-06-19 23:29:04 +00003991 }
3992
Dan Gohmaned756312010-11-17 20:23:08 +00003993 return setSignedRange(S, ConservativeResult);
Dan Gohmanc702fc02009-06-19 23:29:04 +00003994}
3995
Chris Lattnerd934c702004-04-02 20:23:17 +00003996/// createSCEV - We know that there is no SCEV for the specified value.
3997/// Analyze the expression.
3998///
Dan Gohmanaf752342009-07-07 17:06:11 +00003999const SCEV *ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004000 if (!isSCEVable(V->getType()))
Dan Gohmanc8e23622009-04-21 23:15:49 +00004001 return getUnknown(V);
Dan Gohman0a40ad92009-04-16 03:18:22 +00004002
Dan Gohman05e89732008-06-22 19:56:46 +00004003 unsigned Opcode = Instruction::UserOp1;
Dan Gohman69451a02010-03-09 23:46:50 +00004004 if (Instruction *I = dyn_cast<Instruction>(V)) {
Dan Gohman05e89732008-06-22 19:56:46 +00004005 Opcode = I->getOpcode();
Dan Gohman69451a02010-03-09 23:46:50 +00004006
4007 // Don't attempt to analyze instructions in blocks that aren't
4008 // reachable. Such instructions don't matter, and they aren't required
4009 // to obey basic rules for definitions dominating uses which this
4010 // analysis depends on.
4011 if (!DT->isReachableFromEntry(I->getParent()))
4012 return getUnknown(V);
4013 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman05e89732008-06-22 19:56:46 +00004014 Opcode = CE->getOpcode();
Dan Gohmanf436bac2009-06-24 00:54:57 +00004015 else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
4016 return getConstant(CI);
4017 else if (isa<ConstantPointerNull>(V))
Dan Gohman1d2ded72010-05-03 22:09:21 +00004018 return getConstant(V->getType(), 0);
Dan Gohmanf161e06e2009-08-25 17:49:57 +00004019 else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
4020 return GA->mayBeOverridden() ? getUnknown(V) : getSCEV(GA->getAliasee());
Dan Gohman05e89732008-06-22 19:56:46 +00004021 else
Dan Gohmanc8e23622009-04-21 23:15:49 +00004022 return getUnknown(V);
Chris Lattnera3e0bb42007-04-02 05:41:38 +00004023
Dan Gohman80ca01c2009-07-17 20:47:02 +00004024 Operator *U = cast<Operator>(V);
Dan Gohman05e89732008-06-22 19:56:46 +00004025 switch (Opcode) {
Dan Gohmane5fb1032010-08-16 16:03:49 +00004026 case Instruction::Add: {
4027 // The simple thing to do would be to just call getSCEV on both operands
4028 // and call getAddExpr with the result. However if we're looking at a
4029 // bunch of things all added together, this can be quite inefficient,
4030 // because it leads to N-1 getAddExpr calls for N ultimate operands.
4031 // Instead, gather up all the operands and make a single getAddExpr call.
4032 // LLVM IR canonical form means we need only traverse the left operands.
Andrew Trickd25089f2011-11-29 02:16:38 +00004033 //
4034 // Don't apply this instruction's NSW or NUW flags to the new
4035 // expression. The instruction may be guarded by control flow that the
4036 // no-wrap behavior depends on. Non-control-equivalent instructions can be
4037 // mapped to the same SCEV expression, and it would be incorrect to transfer
4038 // NSW/NUW semantics to those operations.
Dan Gohmane5fb1032010-08-16 16:03:49 +00004039 SmallVector<const SCEV *, 4> AddOps;
4040 AddOps.push_back(getSCEV(U->getOperand(1)));
Dan Gohman47308d52010-08-31 22:53:17 +00004041 for (Value *Op = U->getOperand(0); ; Op = U->getOperand(0)) {
4042 unsigned Opcode = Op->getValueID() - Value::InstructionVal;
4043 if (Opcode != Instruction::Add && Opcode != Instruction::Sub)
4044 break;
Dan Gohmane5fb1032010-08-16 16:03:49 +00004045 U = cast<Operator>(Op);
Dan Gohman47308d52010-08-31 22:53:17 +00004046 const SCEV *Op1 = getSCEV(U->getOperand(1));
4047 if (Opcode == Instruction::Sub)
4048 AddOps.push_back(getNegativeSCEV(Op1));
4049 else
4050 AddOps.push_back(Op1);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004051 }
4052 AddOps.push_back(getSCEV(U->getOperand(0)));
Andrew Trickd25089f2011-11-29 02:16:38 +00004053 return getAddExpr(AddOps);
Dan Gohmane5fb1032010-08-16 16:03:49 +00004054 }
4055 case Instruction::Mul: {
Andrew Trickd25089f2011-11-29 02:16:38 +00004056 // Don't transfer NSW/NUW for the same reason as AddExpr.
Dan Gohmane5fb1032010-08-16 16:03:49 +00004057 SmallVector<const SCEV *, 4> MulOps;
4058 MulOps.push_back(getSCEV(U->getOperand(1)));
4059 for (Value *Op = U->getOperand(0);
Andrew Trick2a3b7162011-03-09 17:23:39 +00004060 Op->getValueID() == Instruction::Mul + Value::InstructionVal;
Dan Gohmane5fb1032010-08-16 16:03:49 +00004061 Op = U->getOperand(0)) {
4062 U = cast<Operator>(Op);
4063 MulOps.push_back(getSCEV(U->getOperand(1)));
4064 }
4065 MulOps.push_back(getSCEV(U->getOperand(0)));
4066 return getMulExpr(MulOps);
4067 }
Dan Gohman05e89732008-06-22 19:56:46 +00004068 case Instruction::UDiv:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004069 return getUDivExpr(getSCEV(U->getOperand(0)),
4070 getSCEV(U->getOperand(1)));
Dan Gohman05e89732008-06-22 19:56:46 +00004071 case Instruction::Sub:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004072 return getMinusSCEV(getSCEV(U->getOperand(0)),
4073 getSCEV(U->getOperand(1)));
Dan Gohman0ec05372009-04-21 02:26:00 +00004074 case Instruction::And:
4075 // For an expression like x&255 that merely masks off the high bits,
4076 // use zext(trunc(x)) as the SCEV expression.
4077 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmandf199482009-04-25 17:05:40 +00004078 if (CI->isNullValue())
4079 return getSCEV(U->getOperand(1));
Dan Gohman05c1d372009-04-27 01:41:10 +00004080 if (CI->isAllOnesValue())
4081 return getSCEV(U->getOperand(0));
Dan Gohman0ec05372009-04-21 02:26:00 +00004082 const APInt &A = CI->getValue();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004083
4084 // Instcombine's ShrinkDemandedConstant may strip bits out of
4085 // constants, obscuring what would otherwise be a low-bits mask.
Jay Foada0653a32014-05-14 21:14:37 +00004086 // Use computeKnownBits to compute what ShrinkDemandedConstant
Dan Gohman1ee696d2009-06-16 19:52:01 +00004087 // knew about to reconstruct a low-bits mask value.
4088 unsigned LZ = A.countLeadingZeros();
Nick Lewycky31eaca52014-01-27 10:04:03 +00004089 unsigned TZ = A.countTrailingZeros();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004090 unsigned BitWidth = A.getBitWidth();
Dan Gohman1ee696d2009-06-16 19:52:01 +00004091 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00004092 computeKnownBits(U->getOperand(0), KnownZero, KnownOne, DL,
4093 0, AT, nullptr, DT);
Dan Gohman1ee696d2009-06-16 19:52:01 +00004094
Nick Lewycky31eaca52014-01-27 10:04:03 +00004095 APInt EffectiveMask =
4096 APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
4097 if ((LZ != 0 || TZ != 0) && !((~A & ~KnownZero) & EffectiveMask)) {
4098 const SCEV *MulCount = getConstant(
4099 ConstantInt::get(getContext(), APInt::getOneBitSet(BitWidth, TZ)));
4100 return getMulExpr(
4101 getZeroExtendExpr(
4102 getTruncateExpr(
4103 getUDivExactExpr(getSCEV(U->getOperand(0)), MulCount),
4104 IntegerType::get(getContext(), BitWidth - LZ - TZ)),
4105 U->getType()),
4106 MulCount);
4107 }
Dan Gohman0ec05372009-04-21 02:26:00 +00004108 }
4109 break;
Dan Gohman1ee696d2009-06-16 19:52:01 +00004110
Dan Gohman05e89732008-06-22 19:56:46 +00004111 case Instruction::Or:
4112 // If the RHS of the Or is a constant, we may have something like:
4113 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
4114 // optimizations will transparently handle this case.
4115 //
4116 // In order for this transformation to be safe, the LHS must be of the
4117 // form X*(2^n) and the Or constant must be less than 2^n.
4118 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmanaf752342009-07-07 17:06:11 +00004119 const SCEV *LHS = getSCEV(U->getOperand(0));
Dan Gohman05e89732008-06-22 19:56:46 +00004120 const APInt &CIVal = CI->getValue();
Dan Gohmanc702fc02009-06-19 23:29:04 +00004121 if (GetMinTrailingZeros(LHS) >=
Dan Gohman36bad002009-09-17 18:05:20 +00004122 (CIVal.getBitWidth() - CIVal.countLeadingZeros())) {
4123 // Build a plain add SCEV.
4124 const SCEV *S = getAddExpr(LHS, getSCEV(CI));
4125 // If the LHS of the add was an addrec and it has no-wrap flags,
4126 // transfer the no-wrap flags, since an or won't introduce a wrap.
4127 if (const SCEVAddRecExpr *NewAR = dyn_cast<SCEVAddRecExpr>(S)) {
4128 const SCEVAddRecExpr *OldAR = cast<SCEVAddRecExpr>(LHS);
Andrew Trick8b55b732011-03-14 16:50:06 +00004129 const_cast<SCEVAddRecExpr *>(NewAR)->setNoWrapFlags(
4130 OldAR->getNoWrapFlags());
Dan Gohman36bad002009-09-17 18:05:20 +00004131 }
4132 return S;
4133 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004134 }
Dan Gohman05e89732008-06-22 19:56:46 +00004135 break;
4136 case Instruction::Xor:
Dan Gohman05e89732008-06-22 19:56:46 +00004137 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004138 // If the RHS of the xor is a signbit, then this is just an add.
4139 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman05e89732008-06-22 19:56:46 +00004140 if (CI->getValue().isSignBit())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004141 return getAddExpr(getSCEV(U->getOperand(0)),
4142 getSCEV(U->getOperand(1)));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004143
4144 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmand277a1e2009-05-18 16:17:44 +00004145 if (CI->isAllOnesValue())
Dan Gohmanc8e23622009-04-21 23:15:49 +00004146 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman6350296e2009-05-18 16:29:04 +00004147
4148 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
4149 // This is a variant of the check for xor with -1, and it handles
4150 // the case where instcombine has trimmed non-demanded bits out
4151 // of an xor with -1.
4152 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
4153 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
4154 if (BO->getOpcode() == Instruction::And &&
4155 LCI->getValue() == CI->getValue())
4156 if (const SCEVZeroExtendExpr *Z =
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004157 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Chris Lattner229907c2011-07-18 04:54:35 +00004158 Type *UTy = U->getType();
Dan Gohmanaf752342009-07-07 17:06:11 +00004159 const SCEV *Z0 = Z->getOperand();
Chris Lattner229907c2011-07-18 04:54:35 +00004160 Type *Z0Ty = Z0->getType();
Dan Gohmaneddf7712009-06-18 00:00:20 +00004161 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
4162
Dan Gohman8b0a4192010-03-01 17:49:51 +00004163 // If C is a low-bits mask, the zero extend is serving to
Dan Gohmaneddf7712009-06-18 00:00:20 +00004164 // mask off the high bits. Complement the operand and
4165 // re-apply the zext.
4166 if (APIntOps::isMask(Z0TySize, CI->getValue()))
4167 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
4168
4169 // If C is a single bit, it may be in the sign-bit position
4170 // before the zero-extend. In this case, represent the xor
4171 // using an add, which is equivalent, and re-apply the zext.
Jay Foad583abbc2010-12-07 08:25:19 +00004172 APInt Trunc = CI->getValue().trunc(Z0TySize);
4173 if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
Dan Gohmaneddf7712009-06-18 00:00:20 +00004174 Trunc.isSignBit())
4175 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
4176 UTy);
Dan Gohmanb50f5a42009-06-17 01:22:39 +00004177 }
Dan Gohman05e89732008-06-22 19:56:46 +00004178 }
4179 break;
4180
4181 case Instruction::Shl:
4182 // Turn shift left of a constant amount into a multiply.
4183 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004184 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004185
4186 // If the shift count is not less than the bitwidth, the result of
4187 // the shift is undefined. Don't try to analyze it, because the
4188 // resolution chosen here may differ from the resolution chosen in
4189 // other parts of the compiler.
4190 if (SA->getValue().uge(BitWidth))
4191 break;
4192
Owen Andersonedb4a702009-07-24 23:12:02 +00004193 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004194 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004195 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman05e89732008-06-22 19:56:46 +00004196 }
4197 break;
4198
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004199 case Instruction::LShr:
Nick Lewycky52348302009-01-13 09:18:58 +00004200 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004201 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004202 uint32_t BitWidth = cast<IntegerType>(U->getType())->getBitWidth();
Dan Gohmanacd700a2010-04-22 01:35:11 +00004203
4204 // If the shift count is not less than the bitwidth, the result of
4205 // the shift is undefined. Don't try to analyze it, because the
4206 // resolution chosen here may differ from the resolution chosen in
4207 // other parts of the compiler.
4208 if (SA->getValue().uge(BitWidth))
4209 break;
4210
Owen Andersonedb4a702009-07-24 23:12:02 +00004211 Constant *X = ConstantInt::get(getContext(),
Benjamin Kramerfc3ea6f2013-07-11 16:05:50 +00004212 APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
Dan Gohmanc8e23622009-04-21 23:15:49 +00004213 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewyckyf5c547d2008-07-07 06:15:49 +00004214 }
4215 break;
4216
Dan Gohman0ec05372009-04-21 02:26:00 +00004217 case Instruction::AShr:
4218 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
4219 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
Dan Gohmanacd700a2010-04-22 01:35:11 +00004220 if (Operator *L = dyn_cast<Operator>(U->getOperand(0)))
Dan Gohman0ec05372009-04-21 02:26:00 +00004221 if (L->getOpcode() == Instruction::Shl &&
4222 L->getOperand(1) == U->getOperand(1)) {
Dan Gohmanacd700a2010-04-22 01:35:11 +00004223 uint64_t BitWidth = getTypeSizeInBits(U->getType());
4224
4225 // If the shift count is not less than the bitwidth, the result of
4226 // the shift is undefined. Don't try to analyze it, because the
4227 // resolution chosen here may differ from the resolution chosen in
4228 // other parts of the compiler.
4229 if (CI->getValue().uge(BitWidth))
4230 break;
4231
Dan Gohmandf199482009-04-25 17:05:40 +00004232 uint64_t Amt = BitWidth - CI->getZExtValue();
4233 if (Amt == BitWidth)
4234 return getSCEV(L->getOperand(0)); // shift by zero --> noop
Dan Gohman0ec05372009-04-21 02:26:00 +00004235 return
Dan Gohmanc8e23622009-04-21 23:15:49 +00004236 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohmanacd700a2010-04-22 01:35:11 +00004237 IntegerType::get(getContext(),
4238 Amt)),
4239 U->getType());
Dan Gohman0ec05372009-04-21 02:26:00 +00004240 }
4241 break;
4242
Dan Gohman05e89732008-06-22 19:56:46 +00004243 case Instruction::Trunc:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004244 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004245
4246 case Instruction::ZExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004247 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004248
4249 case Instruction::SExt:
Dan Gohmanc8e23622009-04-21 23:15:49 +00004250 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman05e89732008-06-22 19:56:46 +00004251
4252 case Instruction::BitCast:
4253 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00004254 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman05e89732008-06-22 19:56:46 +00004255 return getSCEV(U->getOperand(0));
4256 break;
4257
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00004258 // It's tempting to handle inttoptr and ptrtoint as no-ops, however this can
4259 // lead to pointer expressions which cannot safely be expanded to GEPs,
4260 // because ScalarEvolution doesn't respect the GEP aliasing rules when
4261 // simplifying integer expressions.
Dan Gohman0a40ad92009-04-16 03:18:22 +00004262
Dan Gohmanee750d12009-05-08 20:26:55 +00004263 case Instruction::GetElementPtr:
Dan Gohmanb256ccf2009-12-18 02:09:29 +00004264 return createNodeForGEP(cast<GEPOperator>(U));
Dan Gohman0a40ad92009-04-16 03:18:22 +00004265
Dan Gohman05e89732008-06-22 19:56:46 +00004266 case Instruction::PHI:
4267 return createNodeForPHI(cast<PHINode>(U));
4268
4269 case Instruction::Select:
4270 // This could be a smax or umax that was lowered earlier.
4271 // Try to recover it.
4272 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
4273 Value *LHS = ICI->getOperand(0);
4274 Value *RHS = ICI->getOperand(1);
4275 switch (ICI->getPredicate()) {
4276 case ICmpInst::ICMP_SLT:
4277 case ICmpInst::ICMP_SLE:
4278 std::swap(LHS, RHS);
4279 // fall through
4280 case ICmpInst::ICMP_SGT:
4281 case ICmpInst::ICMP_SGE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004282 // a >s b ? a+x : b+x -> smax(a, b)+x
4283 // a >s b ? b+x : a+x -> smin(a, b)+x
4284 if (LHS->getType() == U->getType()) {
4285 const SCEV *LS = getSCEV(LHS);
4286 const SCEV *RS = getSCEV(RHS);
4287 const SCEV *LA = getSCEV(U->getOperand(1));
4288 const SCEV *RA = getSCEV(U->getOperand(2));
4289 const SCEV *LDiff = getMinusSCEV(LA, LS);
4290 const SCEV *RDiff = getMinusSCEV(RA, RS);
4291 if (LDiff == RDiff)
4292 return getAddExpr(getSMaxExpr(LS, RS), LDiff);
4293 LDiff = getMinusSCEV(LA, RS);
4294 RDiff = getMinusSCEV(RA, LS);
4295 if (LDiff == RDiff)
4296 return getAddExpr(getSMinExpr(LS, RS), LDiff);
4297 }
Dan Gohman05e89732008-06-22 19:56:46 +00004298 break;
4299 case ICmpInst::ICMP_ULT:
4300 case ICmpInst::ICMP_ULE:
4301 std::swap(LHS, RHS);
4302 // fall through
4303 case ICmpInst::ICMP_UGT:
4304 case ICmpInst::ICMP_UGE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004305 // a >u b ? a+x : b+x -> umax(a, b)+x
4306 // a >u b ? b+x : a+x -> umin(a, b)+x
4307 if (LHS->getType() == U->getType()) {
4308 const SCEV *LS = getSCEV(LHS);
4309 const SCEV *RS = getSCEV(RHS);
4310 const SCEV *LA = getSCEV(U->getOperand(1));
4311 const SCEV *RA = getSCEV(U->getOperand(2));
4312 const SCEV *LDiff = getMinusSCEV(LA, LS);
4313 const SCEV *RDiff = getMinusSCEV(RA, RS);
4314 if (LDiff == RDiff)
4315 return getAddExpr(getUMaxExpr(LS, RS), LDiff);
4316 LDiff = getMinusSCEV(LA, RS);
4317 RDiff = getMinusSCEV(RA, LS);
4318 if (LDiff == RDiff)
4319 return getAddExpr(getUMinExpr(LS, RS), LDiff);
4320 }
Dan Gohman05e89732008-06-22 19:56:46 +00004321 break;
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004322 case ICmpInst::ICMP_NE:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004323 // n != 0 ? n+x : 1+x -> umax(n, 1)+x
4324 if (LHS->getType() == U->getType() &&
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004325 isa<ConstantInt>(RHS) &&
Dan Gohmanf33bac32010-04-24 03:09:42 +00004326 cast<ConstantInt>(RHS)->isZero()) {
4327 const SCEV *One = getConstant(LHS->getType(), 1);
4328 const SCEV *LS = getSCEV(LHS);
4329 const SCEV *LA = getSCEV(U->getOperand(1));
4330 const SCEV *RA = getSCEV(U->getOperand(2));
4331 const SCEV *LDiff = getMinusSCEV(LA, LS);
4332 const SCEV *RDiff = getMinusSCEV(RA, One);
4333 if (LDiff == RDiff)
Dan Gohmancf32f2b2010-08-13 20:17:14 +00004334 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohmanf33bac32010-04-24 03:09:42 +00004335 }
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004336 break;
4337 case ICmpInst::ICMP_EQ:
Dan Gohmanf33bac32010-04-24 03:09:42 +00004338 // n == 0 ? 1+x : n+x -> umax(n, 1)+x
4339 if (LHS->getType() == U->getType() &&
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004340 isa<ConstantInt>(RHS) &&
Dan Gohmanf33bac32010-04-24 03:09:42 +00004341 cast<ConstantInt>(RHS)->isZero()) {
4342 const SCEV *One = getConstant(LHS->getType(), 1);
4343 const SCEV *LS = getSCEV(LHS);
4344 const SCEV *LA = getSCEV(U->getOperand(1));
4345 const SCEV *RA = getSCEV(U->getOperand(2));
4346 const SCEV *LDiff = getMinusSCEV(LA, One);
4347 const SCEV *RDiff = getMinusSCEV(RA, LS);
4348 if (LDiff == RDiff)
Dan Gohmancf32f2b2010-08-13 20:17:14 +00004349 return getAddExpr(getUMaxExpr(One, LS), LDiff);
Dan Gohmanf33bac32010-04-24 03:09:42 +00004350 }
Dan Gohman4d3c3cf2009-06-18 20:21:07 +00004351 break;
Dan Gohman05e89732008-06-22 19:56:46 +00004352 default:
4353 break;
4354 }
4355 }
4356
4357 default: // We cannot analyze this expression.
4358 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00004359 }
4360
Dan Gohmanc8e23622009-04-21 23:15:49 +00004361 return getUnknown(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00004362}
4363
4364
4365
4366//===----------------------------------------------------------------------===//
4367// Iteration Count Computation Code
4368//
4369
Andrew Trick2b6860f2011-08-11 23:36:16 +00004370/// getSmallConstantTripCount - Returns the maximum trip count of this loop as a
Andrew Tricke81211f2012-01-11 06:52:55 +00004371/// normal unsigned value. Returns 0 if the trip count is unknown or not
4372/// constant. Will also return 0 if the maximum trip count is very large (>=
4373/// 2^32).
4374///
4375/// This "trip count" assumes that control exits via ExitingBlock. More
4376/// precisely, it is the number of times that control may reach ExitingBlock
4377/// before taking the branch. For loops with multiple exits, it may not be the
4378/// number times that the loop header executes because the loop may exit
4379/// prematurely via another branch.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004380unsigned ScalarEvolution::getSmallConstantTripCount(Loop *L,
4381 BasicBlock *ExitingBlock) {
Andrew Trick2b6860f2011-08-11 23:36:16 +00004382 const SCEVConstant *ExitCount =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004383 dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
Andrew Trick2b6860f2011-08-11 23:36:16 +00004384 if (!ExitCount)
4385 return 0;
4386
4387 ConstantInt *ExitConst = ExitCount->getValue();
4388
4389 // Guard against huge trip counts.
4390 if (ExitConst->getValue().getActiveBits() > 32)
4391 return 0;
4392
4393 // In case of integer overflow, this returns 0, which is correct.
4394 return ((unsigned)ExitConst->getZExtValue()) + 1;
4395}
4396
4397/// getSmallConstantTripMultiple - Returns the largest constant divisor of the
4398/// trip count of this loop as a normal unsigned value, if possible. This
4399/// means that the actual trip count is always a multiple of the returned
4400/// value (don't forget the trip count could very well be zero as well!).
4401///
4402/// Returns 1 if the trip count is unknown or not guaranteed to be the
4403/// multiple of a constant (which is also the case if the trip count is simply
4404/// constant, use getSmallConstantTripCount for that case), Will also return 1
4405/// if the trip count is very large (>= 2^32).
Andrew Tricke81211f2012-01-11 06:52:55 +00004406///
4407/// As explained in the comments for getSmallConstantTripCount, this assumes
4408/// that control exits the loop via ExitingBlock.
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004409unsigned
4410ScalarEvolution::getSmallConstantTripMultiple(Loop *L,
4411 BasicBlock *ExitingBlock) {
4412 const SCEV *ExitCount = getExitCount(L, ExitingBlock);
Andrew Trick2b6860f2011-08-11 23:36:16 +00004413 if (ExitCount == getCouldNotCompute())
4414 return 1;
4415
4416 // Get the trip count from the BE count by adding 1.
4417 const SCEV *TCMul = getAddExpr(ExitCount,
4418 getConstant(ExitCount->getType(), 1));
4419 // FIXME: SCEV distributes multiplication as V1*C1 + V2*C1. We could attempt
4420 // to factor simple cases.
4421 if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(TCMul))
4422 TCMul = Mul->getOperand(0);
4423
4424 const SCEVConstant *MulC = dyn_cast<SCEVConstant>(TCMul);
4425 if (!MulC)
4426 return 1;
4427
4428 ConstantInt *Result = MulC->getValue();
4429
Hal Finkel30bd9342012-10-24 19:46:44 +00004430 // Guard against huge trip counts (this requires checking
4431 // for zero to handle the case where the trip count == -1 and the
4432 // addition wraps).
4433 if (!Result || Result->getValue().getActiveBits() > 32 ||
4434 Result->getValue().getActiveBits() == 0)
Andrew Trick2b6860f2011-08-11 23:36:16 +00004435 return 1;
4436
4437 return (unsigned)Result->getZExtValue();
4438}
4439
Andrew Trick3ca3f982011-07-26 17:19:55 +00004440// getExitCount - Get the expression for the number of loop iterations for which
Andrew Trickee9143a2013-05-31 23:34:46 +00004441// this loop is guaranteed not to exit via ExitingBlock. Otherwise return
Andrew Trick3ca3f982011-07-26 17:19:55 +00004442// SCEVCouldNotCompute.
Andrew Trick77c55422011-08-02 04:23:35 +00004443const SCEV *ScalarEvolution::getExitCount(Loop *L, BasicBlock *ExitingBlock) {
4444 return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
Andrew Trick3ca3f982011-07-26 17:19:55 +00004445}
4446
Dan Gohman0bddac12009-02-24 18:55:53 +00004447/// getBackedgeTakenCount - If the specified loop has a predictable
4448/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
4449/// object. The backedge-taken count is the number of times the loop header
4450/// will be branched to from within the loop. This is one less than the
4451/// trip count of the loop, since it doesn't count the first iteration,
4452/// when the header is branched to from outside the loop.
4453///
4454/// Note that it is not valid to call this method on a loop without a
4455/// loop-invariant backedge-taken count (see
4456/// hasLoopInvariantBackedgeTakenCount).
4457///
Dan Gohmanaf752342009-07-07 17:06:11 +00004458const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004459 return getBackedgeTakenInfo(L).getExact(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004460}
4461
4462/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
4463/// return the least SCEV value that is known never to be less than the
4464/// actual backedge taken count.
Dan Gohmanaf752342009-07-07 17:06:11 +00004465const SCEV *ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004466 return getBackedgeTakenInfo(L).getMax(this);
Dan Gohman2b8da352009-04-30 20:47:05 +00004467}
4468
Dan Gohmandc191042009-07-08 19:23:34 +00004469/// PushLoopPHIs - Push PHI nodes in the header of the given loop
4470/// onto the given Worklist.
4471static void
4472PushLoopPHIs(const Loop *L, SmallVectorImpl<Instruction *> &Worklist) {
4473 BasicBlock *Header = L->getHeader();
4474
4475 // Push all Loop-header PHIs onto the Worklist stack.
4476 for (BasicBlock::iterator I = Header->begin();
4477 PHINode *PN = dyn_cast<PHINode>(I); ++I)
4478 Worklist.push_back(PN);
4479}
4480
Dan Gohman2b8da352009-04-30 20:47:05 +00004481const ScalarEvolution::BackedgeTakenInfo &
4482ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004483 // Initially insert an invalid entry for this loop. If the insertion
Dan Gohman8b0a4192010-03-01 17:49:51 +00004484 // succeeds, proceed to actually compute a backedge-taken count and
Dan Gohman76466372009-04-27 20:16:15 +00004485 // update the value. The temporary CouldNotCompute value tells SCEV
4486 // code elsewhere that it shouldn't attempt to request a new
4487 // backedge-taken count, which could result in infinite recursion.
Dan Gohman0daf6872011-05-09 18:44:09 +00004488 std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
Andrew Trick3ca3f982011-07-26 17:19:55 +00004489 BackedgeTakenCounts.insert(std::make_pair(L, BackedgeTakenInfo()));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004490 if (!Pair.second)
4491 return Pair.first->second;
Dan Gohman76466372009-04-27 20:16:15 +00004492
Andrew Trick3ca3f982011-07-26 17:19:55 +00004493 // ComputeBackedgeTakenCount may allocate memory for its result. Inserting it
4494 // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
4495 // must be cleared in this scope.
4496 BackedgeTakenInfo Result = ComputeBackedgeTakenCount(L);
4497
4498 if (Result.getExact(this) != getCouldNotCompute()) {
4499 assert(isLoopInvariant(Result.getExact(this), L) &&
4500 isLoopInvariant(Result.getMax(this), L) &&
Chris Lattnera337f5e2011-01-09 02:16:18 +00004501 "Computed backedge-taken count isn't loop invariant for loop!");
4502 ++NumTripCountsComputed;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004503 }
4504 else if (Result.getMax(this) == getCouldNotCompute() &&
4505 isa<PHINode>(L->getHeader()->begin())) {
4506 // Only count loops that have phi nodes as not being computable.
4507 ++NumTripCountsNotComputed;
Chris Lattnera337f5e2011-01-09 02:16:18 +00004508 }
Dan Gohman2b8da352009-04-30 20:47:05 +00004509
Chris Lattnera337f5e2011-01-09 02:16:18 +00004510 // Now that we know more about the trip count for this loop, forget any
4511 // existing SCEV values for PHI nodes in this loop since they are only
4512 // conservative estimates made without the benefit of trip count
4513 // information. This is similar to the code in forgetLoop, except that
4514 // it handles SCEVUnknown PHI nodes specially.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004515 if (Result.hasAnyInfo()) {
Chris Lattnera337f5e2011-01-09 02:16:18 +00004516 SmallVector<Instruction *, 16> Worklist;
4517 PushLoopPHIs(L, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004518
Chris Lattnera337f5e2011-01-09 02:16:18 +00004519 SmallPtrSet<Instruction *, 8> Visited;
4520 while (!Worklist.empty()) {
4521 Instruction *I = Worklist.pop_back_val();
4522 if (!Visited.insert(I)) continue;
Dan Gohmandc191042009-07-08 19:23:34 +00004523
Chris Lattnera337f5e2011-01-09 02:16:18 +00004524 ValueExprMapType::iterator It =
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004525 ValueExprMap.find_as(static_cast<Value *>(I));
Chris Lattnera337f5e2011-01-09 02:16:18 +00004526 if (It != ValueExprMap.end()) {
4527 const SCEV *Old = It->second;
Dan Gohman761065e2010-11-17 02:44:44 +00004528
Chris Lattnera337f5e2011-01-09 02:16:18 +00004529 // SCEVUnknown for a PHI either means that it has an unrecognized
4530 // structure, or it's a PHI that's in the progress of being computed
4531 // by createNodeForPHI. In the former case, additional loop trip
4532 // count information isn't going to change anything. In the later
4533 // case, createNodeForPHI will perform the necessary updates on its
4534 // own when it gets to that point.
4535 if (!isa<PHINode>(I) || !isa<SCEVUnknown>(Old)) {
4536 forgetMemoizedResults(Old);
4537 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00004538 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004539 if (PHINode *PN = dyn_cast<PHINode>(I))
4540 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmandc191042009-07-08 19:23:34 +00004541 }
Chris Lattnera337f5e2011-01-09 02:16:18 +00004542
4543 PushDefUseChildren(I, Worklist);
Dan Gohmandc191042009-07-08 19:23:34 +00004544 }
Chris Lattnerd934c702004-04-02 20:23:17 +00004545 }
Dan Gohman6acd95b2011-04-25 22:48:29 +00004546
4547 // Re-lookup the insert position, since the call to
4548 // ComputeBackedgeTakenCount above could result in a
4549 // recusive call to getBackedgeTakenInfo (on a different
4550 // loop), which would invalidate the iterator computed
4551 // earlier.
4552 return BackedgeTakenCounts.find(L)->second = Result;
Chris Lattnerd934c702004-04-02 20:23:17 +00004553}
4554
Dan Gohman880c92a2009-10-31 15:04:55 +00004555/// forgetLoop - This method should be called by the client when it has
4556/// changed a loop in a way that may effect ScalarEvolution's ability to
4557/// compute a trip count, or if the loop is deleted.
4558void ScalarEvolution::forgetLoop(const Loop *L) {
4559 // Drop any stored trip count value.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004560 DenseMap<const Loop*, BackedgeTakenInfo>::iterator BTCPos =
4561 BackedgeTakenCounts.find(L);
4562 if (BTCPos != BackedgeTakenCounts.end()) {
4563 BTCPos->second.clear();
4564 BackedgeTakenCounts.erase(BTCPos);
4565 }
Dan Gohmanf1505722009-05-02 17:43:35 +00004566
Dan Gohman880c92a2009-10-31 15:04:55 +00004567 // Drop information about expressions based on loop-header PHIs.
Dan Gohman48f82222009-05-04 22:30:44 +00004568 SmallVector<Instruction *, 16> Worklist;
Dan Gohmandc191042009-07-08 19:23:34 +00004569 PushLoopPHIs(L, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00004570
Dan Gohmandc191042009-07-08 19:23:34 +00004571 SmallPtrSet<Instruction *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00004572 while (!Worklist.empty()) {
4573 Instruction *I = Worklist.pop_back_val();
Dan Gohmandc191042009-07-08 19:23:34 +00004574 if (!Visited.insert(I)) continue;
4575
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004576 ValueExprMapType::iterator It =
4577 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004578 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00004579 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004580 ValueExprMap.erase(It);
Dan Gohmandc191042009-07-08 19:23:34 +00004581 if (PHINode *PN = dyn_cast<PHINode>(I))
4582 ConstantEvolutionLoopExitValue.erase(PN);
4583 }
4584
4585 PushDefUseChildren(I, Worklist);
Dan Gohman48f82222009-05-04 22:30:44 +00004586 }
Dan Gohmandcb354b2010-10-29 20:16:10 +00004587
4588 // Forget all contained loops too, to avoid dangling entries in the
4589 // ValuesAtScopes map.
4590 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4591 forgetLoop(*I);
Dan Gohman43300342009-02-17 20:49:49 +00004592}
4593
Eric Christopheref6d5932010-07-29 01:25:38 +00004594/// forgetValue - This method should be called by the client when it has
4595/// changed a value in a way that may effect its value, or which may
4596/// disconnect it from a def-use chain linking it to a loop.
4597void ScalarEvolution::forgetValue(Value *V) {
Dale Johannesen1d6827a2010-02-19 07:14:22 +00004598 Instruction *I = dyn_cast<Instruction>(V);
4599 if (!I) return;
4600
4601 // Drop information about expressions based on loop-header PHIs.
4602 SmallVector<Instruction *, 16> Worklist;
4603 Worklist.push_back(I);
4604
4605 SmallPtrSet<Instruction *, 8> Visited;
4606 while (!Worklist.empty()) {
4607 I = Worklist.pop_back_val();
4608 if (!Visited.insert(I)) continue;
4609
Benjamin Kramere2ef47c2012-06-30 22:37:15 +00004610 ValueExprMapType::iterator It =
4611 ValueExprMap.find_as(static_cast<Value *>(I));
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004612 if (It != ValueExprMap.end()) {
Dan Gohman7e6b3932010-11-17 23:28:48 +00004613 forgetMemoizedResults(It->second);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00004614 ValueExprMap.erase(It);
Dale Johannesen1d6827a2010-02-19 07:14:22 +00004615 if (PHINode *PN = dyn_cast<PHINode>(I))
4616 ConstantEvolutionLoopExitValue.erase(PN);
4617 }
4618
4619 PushDefUseChildren(I, Worklist);
4620 }
4621}
4622
Andrew Trick3ca3f982011-07-26 17:19:55 +00004623/// getExact - Get the exact loop backedge taken count considering all loop
Andrew Trick90c7a102011-11-16 00:52:40 +00004624/// exits. A computable result can only be return for loops with a single exit.
4625/// Returning the minimum taken count among all exits is incorrect because one
4626/// of the loop's exit limit's may have been skipped. HowFarToZero assumes that
4627/// the limit of each loop test is never skipped. This is a valid assumption as
4628/// long as the loop exits via that test. For precise results, it is the
4629/// caller's responsibility to specify the relevant loop exit using
4630/// getExact(ExitingBlock, SE).
Andrew Trick3ca3f982011-07-26 17:19:55 +00004631const SCEV *
4632ScalarEvolution::BackedgeTakenInfo::getExact(ScalarEvolution *SE) const {
4633 // If any exits were not computable, the loop is not computable.
4634 if (!ExitNotTaken.isCompleteList()) return SE->getCouldNotCompute();
4635
Andrew Trick90c7a102011-11-16 00:52:40 +00004636 // We need exactly one computable exit.
Andrew Trick77c55422011-08-02 04:23:35 +00004637 if (!ExitNotTaken.ExitingBlock) return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00004638 assert(ExitNotTaken.ExactNotTaken && "uninitialized not-taken info");
4639
Craig Topper9f008862014-04-15 04:59:12 +00004640 const SCEV *BECount = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004641 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004642 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004643
4644 assert(ENT->ExactNotTaken != SE->getCouldNotCompute() && "bad exit SCEV");
4645
4646 if (!BECount)
4647 BECount = ENT->ExactNotTaken;
Andrew Trick90c7a102011-11-16 00:52:40 +00004648 else if (BECount != ENT->ExactNotTaken)
4649 return SE->getCouldNotCompute();
Andrew Trick3ca3f982011-07-26 17:19:55 +00004650 }
Andrew Trickbbb226a2011-09-02 21:20:46 +00004651 assert(BECount && "Invalid not taken count for loop exit");
Andrew Trick3ca3f982011-07-26 17:19:55 +00004652 return BECount;
4653}
4654
4655/// getExact - Get the exact not taken count for this loop exit.
4656const SCEV *
Andrew Trick77c55422011-08-02 04:23:35 +00004657ScalarEvolution::BackedgeTakenInfo::getExact(BasicBlock *ExitingBlock,
Andrew Trick3ca3f982011-07-26 17:19:55 +00004658 ScalarEvolution *SE) const {
4659 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004660 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004661
Andrew Trick77c55422011-08-02 04:23:35 +00004662 if (ENT->ExitingBlock == ExitingBlock)
Andrew Trick3ca3f982011-07-26 17:19:55 +00004663 return ENT->ExactNotTaken;
4664 }
4665 return SE->getCouldNotCompute();
4666}
4667
4668/// getMax - Get the max backedge taken count for the loop.
4669const SCEV *
4670ScalarEvolution::BackedgeTakenInfo::getMax(ScalarEvolution *SE) const {
4671 return Max ? Max : SE->getCouldNotCompute();
4672}
4673
Andrew Trick9093e152013-03-26 03:14:53 +00004674bool ScalarEvolution::BackedgeTakenInfo::hasOperand(const SCEV *S,
4675 ScalarEvolution *SE) const {
4676 if (Max && Max != SE->getCouldNotCompute() && SE->hasOperand(Max, S))
4677 return true;
4678
4679 if (!ExitNotTaken.ExitingBlock)
4680 return false;
4681
4682 for (const ExitNotTakenInfo *ENT = &ExitNotTaken;
Craig Topper9f008862014-04-15 04:59:12 +00004683 ENT != nullptr; ENT = ENT->getNextExit()) {
Andrew Trick9093e152013-03-26 03:14:53 +00004684
4685 if (ENT->ExactNotTaken != SE->getCouldNotCompute()
4686 && SE->hasOperand(ENT->ExactNotTaken, S)) {
4687 return true;
4688 }
4689 }
4690 return false;
4691}
4692
Andrew Trick3ca3f982011-07-26 17:19:55 +00004693/// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
4694/// computable exit into a persistent ExitNotTakenInfo array.
4695ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
4696 SmallVectorImpl< std::pair<BasicBlock *, const SCEV *> > &ExitCounts,
4697 bool Complete, const SCEV *MaxCount) : Max(MaxCount) {
4698
4699 if (!Complete)
4700 ExitNotTaken.setIncomplete();
4701
4702 unsigned NumExits = ExitCounts.size();
4703 if (NumExits == 0) return;
4704
Andrew Trick77c55422011-08-02 04:23:35 +00004705 ExitNotTaken.ExitingBlock = ExitCounts[0].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004706 ExitNotTaken.ExactNotTaken = ExitCounts[0].second;
4707 if (NumExits == 1) return;
4708
4709 // Handle the rare case of multiple computable exits.
4710 ExitNotTakenInfo *ENT = new ExitNotTakenInfo[NumExits-1];
4711
4712 ExitNotTakenInfo *PrevENT = &ExitNotTaken;
4713 for (unsigned i = 1; i < NumExits; ++i, PrevENT = ENT, ++ENT) {
4714 PrevENT->setNextExit(ENT);
Andrew Trick77c55422011-08-02 04:23:35 +00004715 ENT->ExitingBlock = ExitCounts[i].first;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004716 ENT->ExactNotTaken = ExitCounts[i].second;
4717 }
4718}
4719
4720/// clear - Invalidate this result and free the ExitNotTakenInfo array.
4721void ScalarEvolution::BackedgeTakenInfo::clear() {
Craig Topper9f008862014-04-15 04:59:12 +00004722 ExitNotTaken.ExitingBlock = nullptr;
4723 ExitNotTaken.ExactNotTaken = nullptr;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004724 delete[] ExitNotTaken.getNextExit();
4725}
4726
Dan Gohman0bddac12009-02-24 18:55:53 +00004727/// ComputeBackedgeTakenCount - Compute the number of times the backedge
4728/// of the specified loop will execute.
Dan Gohman2b8da352009-04-30 20:47:05 +00004729ScalarEvolution::BackedgeTakenInfo
4730ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmancb0efec2009-12-18 01:14:11 +00004731 SmallVector<BasicBlock *, 8> ExitingBlocks;
Dan Gohman96212b62009-06-22 00:31:57 +00004732 L->getExitingBlocks(ExitingBlocks);
Chris Lattnerd934c702004-04-02 20:23:17 +00004733
Andrew Trick839e30b2014-05-23 19:47:13 +00004734 SmallVector<std::pair<BasicBlock *, const SCEV *>, 4> ExitCounts;
Andrew Trick3ca3f982011-07-26 17:19:55 +00004735 bool CouldComputeBECount = true;
Andrew Trickee5aa7f2014-01-15 06:42:11 +00004736 BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
Andrew Trick839e30b2014-05-23 19:47:13 +00004737 const SCEV *MustExitMaxBECount = nullptr;
4738 const SCEV *MayExitMaxBECount = nullptr;
4739
4740 // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
4741 // and compute maxBECount.
Dan Gohman96212b62009-06-22 00:31:57 +00004742 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
Andrew Trick839e30b2014-05-23 19:47:13 +00004743 BasicBlock *ExitBB = ExitingBlocks[i];
4744 ExitLimit EL = ComputeExitLimit(L, ExitBB);
4745
4746 // 1. For each exit that can be computed, add an entry to ExitCounts.
4747 // CouldComputeBECount is true only if all exits can be computed.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004748 if (EL.Exact == getCouldNotCompute())
Dan Gohman96212b62009-06-22 00:31:57 +00004749 // We couldn't compute an exact value for this exit, so
Dan Gohman8885b372009-06-22 21:10:22 +00004750 // we won't be able to compute an exact value for the loop.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004751 CouldComputeBECount = false;
4752 else
Andrew Trick839e30b2014-05-23 19:47:13 +00004753 ExitCounts.push_back(std::make_pair(ExitBB, EL.Exact));
Andrew Trick3ca3f982011-07-26 17:19:55 +00004754
Andrew Trick839e30b2014-05-23 19:47:13 +00004755 // 2. Derive the loop's MaxBECount from each exit's max number of
4756 // non-exiting iterations. Partition the loop exits into two kinds:
4757 // LoopMustExits and LoopMayExits.
4758 //
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004759 // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
4760 // is a LoopMayExit. If any computable LoopMustExit is found, then
4761 // MaxBECount is the minimum EL.Max of computable LoopMustExits. Otherwise,
4762 // MaxBECount is conservatively the maximum EL.Max, where CouldNotCompute is
4763 // considered greater than any computable EL.Max.
4764 if (EL.Max != getCouldNotCompute() && Latch &&
Andrew Trick839e30b2014-05-23 19:47:13 +00004765 DT->dominates(ExitBB, Latch)) {
4766 if (!MustExitMaxBECount)
4767 MustExitMaxBECount = EL.Max;
4768 else {
4769 MustExitMaxBECount =
4770 getUMinFromMismatchedTypes(MustExitMaxBECount, EL.Max);
Andrew Tricke2553592014-05-22 00:37:03 +00004771 }
Andrew Trick839e30b2014-05-23 19:47:13 +00004772 } else if (MayExitMaxBECount != getCouldNotCompute()) {
4773 if (!MayExitMaxBECount || EL.Max == getCouldNotCompute())
4774 MayExitMaxBECount = EL.Max;
4775 else {
4776 MayExitMaxBECount =
4777 getUMaxFromMismatchedTypes(MayExitMaxBECount, EL.Max);
4778 }
Andrew Trick90c7a102011-11-16 00:52:40 +00004779 }
Dan Gohman96212b62009-06-22 00:31:57 +00004780 }
Andrew Trick839e30b2014-05-23 19:47:13 +00004781 const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
4782 (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
Andrew Trick3ca3f982011-07-26 17:19:55 +00004783 return BackedgeTakenInfo(ExitCounts, CouldComputeBECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00004784}
4785
Andrew Trick3ca3f982011-07-26 17:19:55 +00004786/// ComputeExitLimit - Compute the number of times the backedge of the specified
4787/// loop will execute if it exits via the specified block.
4788ScalarEvolution::ExitLimit
4789ScalarEvolution::ComputeExitLimit(const Loop *L, BasicBlock *ExitingBlock) {
Dan Gohman96212b62009-06-22 00:31:57 +00004790
4791 // Okay, we've chosen an exiting block. See what condition causes us to
Benjamin Kramer5a188542014-02-11 15:44:32 +00004792 // exit at this block and remember the exit block and whether all other targets
4793 // lead to the loop header.
4794 bool MustExecuteLoopHeader = true;
Craig Topper9f008862014-04-15 04:59:12 +00004795 BasicBlock *Exit = nullptr;
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004796 for (succ_iterator SI = succ_begin(ExitingBlock), SE = succ_end(ExitingBlock);
4797 SI != SE; ++SI)
4798 if (!L->contains(*SI)) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00004799 if (Exit) // Multiple exit successors.
4800 return getCouldNotCompute();
Duncan P. N. Exon Smith6c990152014-07-21 17:06:51 +00004801 Exit = *SI;
4802 } else if (*SI != L->getHeader()) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00004803 MustExecuteLoopHeader = false;
4804 }
Dan Gohmance973df2009-06-24 04:48:43 +00004805
Chris Lattner18954852007-01-07 02:24:26 +00004806 // At this point, we know we have a conditional branch that determines whether
4807 // the loop is exited. However, we don't know if the branch is executed each
4808 // time through the loop. If not, then the execution count of the branch will
4809 // not be equal to the trip count of the loop.
4810 //
4811 // Currently we check for this by checking to see if the Exit branch goes to
4812 // the loop header. If so, we know it will always execute the same number of
Chris Lattner5a554762007-01-14 01:24:47 +00004813 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman96212b62009-06-22 00:31:57 +00004814 // loop header. This is common for un-rotated loops.
4815 //
4816 // If both of those tests fail, walk up the unique predecessor chain to the
4817 // header, stopping if there is an edge that doesn't exit the loop. If the
4818 // header is reached, the execution count of the branch will be equal to the
4819 // trip count of the loop.
4820 //
4821 // More extensive analysis could be done to handle more cases here.
4822 //
Benjamin Kramer5a188542014-02-11 15:44:32 +00004823 if (!MustExecuteLoopHeader && ExitingBlock != L->getHeader()) {
Dan Gohman96212b62009-06-22 00:31:57 +00004824 // The simple checks failed, try climbing the unique predecessor chain
4825 // up to the header.
4826 bool Ok = false;
Benjamin Kramer5a188542014-02-11 15:44:32 +00004827 for (BasicBlock *BB = ExitingBlock; BB; ) {
Dan Gohman96212b62009-06-22 00:31:57 +00004828 BasicBlock *Pred = BB->getUniquePredecessor();
4829 if (!Pred)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004830 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004831 TerminatorInst *PredTerm = Pred->getTerminator();
4832 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
4833 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
4834 if (PredSucc == BB)
4835 continue;
4836 // If the predecessor has a successor that isn't BB and isn't
4837 // outside the loop, assume the worst.
4838 if (L->contains(PredSucc))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004839 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004840 }
4841 if (Pred == L->getHeader()) {
4842 Ok = true;
4843 break;
4844 }
4845 BB = Pred;
4846 }
4847 if (!Ok)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004848 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004849 }
4850
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004851 bool IsOnlyExit = (L->getExitingBlock() != nullptr);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004852 TerminatorInst *Term = ExitingBlock->getTerminator();
4853 if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
4854 assert(BI->isConditional() && "If unconditional, it can't be in loop!");
4855 // Proceed to the next level to examine the exit condition expression.
4856 return ComputeExitLimitFromCond(L, BI->getCondition(), BI->getSuccessor(0),
4857 BI->getSuccessor(1),
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004858 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004859 }
4860
4861 if (SwitchInst *SI = dyn_cast<SwitchInst>(Term))
4862 return ComputeExitLimitFromSingleExitSwitch(L, SI, Exit,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004863 /*ControlsExit=*/IsOnlyExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00004864
4865 return getCouldNotCompute();
Dan Gohman96212b62009-06-22 00:31:57 +00004866}
4867
Andrew Trick3ca3f982011-07-26 17:19:55 +00004868/// ComputeExitLimitFromCond - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00004869/// backedge of the specified loop will execute if its exit condition
4870/// were a conditional branch of ExitCond, TBB, and FBB.
Andrew Trick5b245a12013-05-31 06:43:25 +00004871///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004872/// @param ControlsExit is true if ExitCond directly controls the exit
4873/// branch. In this case, we can assume that the loop exits only if the
4874/// condition is true and can infer that failing to meet the condition prior to
4875/// integer wraparound results in undefined behavior.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004876ScalarEvolution::ExitLimit
4877ScalarEvolution::ComputeExitLimitFromCond(const Loop *L,
4878 Value *ExitCond,
4879 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00004880 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004881 bool ControlsExit) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00004882 // Check if the controlling expression for this loop is an And or Or.
Dan Gohman96212b62009-06-22 00:31:57 +00004883 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
4884 if (BO->getOpcode() == Instruction::And) {
4885 // Recurse on the operands of the and.
Andrew Trick5b245a12013-05-31 06:43:25 +00004886 bool EitherMayExit = L->contains(TBB);
4887 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004888 ControlsExit && !EitherMayExit);
Andrew Trick5b245a12013-05-31 06:43:25 +00004889 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004890 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00004891 const SCEV *BECount = getCouldNotCompute();
4892 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00004893 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00004894 // Both conditions must be true for the loop to continue executing.
4895 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004896 if (EL0.Exact == getCouldNotCompute() ||
4897 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004898 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00004899 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004900 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4901 if (EL0.Max == getCouldNotCompute())
4902 MaxBECount = EL1.Max;
4903 else if (EL1.Max == getCouldNotCompute())
4904 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00004905 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004906 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00004907 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00004908 // Both conditions must be true at the same time for the loop to exit.
4909 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00004910 assert(L->contains(FBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00004911 if (EL0.Max == EL1.Max)
4912 MaxBECount = EL0.Max;
4913 if (EL0.Exact == EL1.Exact)
4914 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00004915 }
4916
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004917 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00004918 }
4919 if (BO->getOpcode() == Instruction::Or) {
4920 // Recurse on the operands of the or.
Andrew Trick5b245a12013-05-31 06:43:25 +00004921 bool EitherMayExit = L->contains(FBB);
4922 ExitLimit EL0 = ComputeExitLimitFromCond(L, BO->getOperand(0), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004923 ControlsExit && !EitherMayExit);
Andrew Trick5b245a12013-05-31 06:43:25 +00004924 ExitLimit EL1 = ComputeExitLimitFromCond(L, BO->getOperand(1), TBB, FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004925 ControlsExit && !EitherMayExit);
Dan Gohmanaf752342009-07-07 17:06:11 +00004926 const SCEV *BECount = getCouldNotCompute();
4927 const SCEV *MaxBECount = getCouldNotCompute();
Andrew Trick5b245a12013-05-31 06:43:25 +00004928 if (EitherMayExit) {
Dan Gohman96212b62009-06-22 00:31:57 +00004929 // Both conditions must be false for the loop to continue executing.
4930 // Choose the less conservative count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004931 if (EL0.Exact == getCouldNotCompute() ||
4932 EL1.Exact == getCouldNotCompute())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00004933 BECount = getCouldNotCompute();
Dan Gohmaned627382009-06-22 15:09:28 +00004934 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004935 BECount = getUMinFromMismatchedTypes(EL0.Exact, EL1.Exact);
4936 if (EL0.Max == getCouldNotCompute())
4937 MaxBECount = EL1.Max;
4938 else if (EL1.Max == getCouldNotCompute())
4939 MaxBECount = EL0.Max;
Dan Gohmaned627382009-06-22 15:09:28 +00004940 else
Andrew Trick3ca3f982011-07-26 17:19:55 +00004941 MaxBECount = getUMinFromMismatchedTypes(EL0.Max, EL1.Max);
Dan Gohman96212b62009-06-22 00:31:57 +00004942 } else {
Dan Gohmanf7495f22010-08-11 00:12:36 +00004943 // Both conditions must be false at the same time for the loop to exit.
4944 // For now, be conservative.
Dan Gohman96212b62009-06-22 00:31:57 +00004945 assert(L->contains(TBB) && "Loop block has no successor in loop!");
Andrew Trick3ca3f982011-07-26 17:19:55 +00004946 if (EL0.Max == EL1.Max)
4947 MaxBECount = EL0.Max;
4948 if (EL0.Exact == EL1.Exact)
4949 BECount = EL0.Exact;
Dan Gohman96212b62009-06-22 00:31:57 +00004950 }
4951
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004952 return ExitLimit(BECount, MaxBECount);
Dan Gohman96212b62009-06-22 00:31:57 +00004953 }
4954 }
4955
4956 // With an icmp, it may be feasible to compute an exact backedge-taken count.
Dan Gohman8b0a4192010-03-01 17:49:51 +00004957 // Proceed to the next level to examine the icmp.
Dan Gohman96212b62009-06-22 00:31:57 +00004958 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004959 return ComputeExitLimitFromICmp(L, ExitCondICmp, TBB, FBB, ControlsExit);
Reid Spencer266e42b2006-12-23 06:05:41 +00004960
Dan Gohman6b1e2a82010-02-19 18:12:07 +00004961 // Check for a constant condition. These are normally stripped out by
4962 // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
4963 // preserve the CFG and is temporarily leaving constant conditions
4964 // in place.
4965 if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
4966 if (L->contains(FBB) == !CI->getZExtValue())
4967 // The backedge is always taken.
4968 return getCouldNotCompute();
4969 else
4970 // The backedge is never taken.
Dan Gohman1d2ded72010-05-03 22:09:21 +00004971 return getConstant(CI->getType(), 0);
Dan Gohman6b1e2a82010-02-19 18:12:07 +00004972 }
4973
Eli Friedmanebf98b02009-05-09 12:32:42 +00004974 // If it's not an integer or pointer comparison then compute it the hard way.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004975 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohman96212b62009-06-22 00:31:57 +00004976}
4977
Andrew Trick3ca3f982011-07-26 17:19:55 +00004978/// ComputeExitLimitFromICmp - Compute the number of times the
Dan Gohman96212b62009-06-22 00:31:57 +00004979/// backedge of the specified loop will execute if its exit condition
4980/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
Andrew Trick3ca3f982011-07-26 17:19:55 +00004981ScalarEvolution::ExitLimit
4982ScalarEvolution::ComputeExitLimitFromICmp(const Loop *L,
4983 ICmpInst *ExitCond,
4984 BasicBlock *TBB,
Andrew Trick5b245a12013-05-31 06:43:25 +00004985 BasicBlock *FBB,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00004986 bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00004987
Reid Spencer266e42b2006-12-23 06:05:41 +00004988 // If the condition was exit on true, convert the condition to exit on false
4989 ICmpInst::Predicate Cond;
Dan Gohman96212b62009-06-22 00:31:57 +00004990 if (!L->contains(FBB))
Reid Spencer266e42b2006-12-23 06:05:41 +00004991 Cond = ExitCond->getPredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00004992 else
Reid Spencer266e42b2006-12-23 06:05:41 +00004993 Cond = ExitCond->getInversePredicate();
Chris Lattnerec901cc2004-10-12 01:49:27 +00004994
4995 // Handle common loops like: for (X = "string"; *X; ++X)
4996 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
4997 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Andrew Trick3ca3f982011-07-26 17:19:55 +00004998 ExitLimit ItCnt =
4999 ComputeLoadConstantCompareExitLimit(LI, RHS, L, Cond);
Dan Gohmanba820342010-02-24 17:31:30 +00005000 if (ItCnt.hasAnyInfo())
5001 return ItCnt;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005002 }
5003
Dan Gohmanaf752342009-07-07 17:06:11 +00005004 const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
5005 const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
Chris Lattnerd934c702004-04-02 20:23:17 +00005006
5007 // Try to evaluate any dependencies out of the loop.
Dan Gohman8ca08852009-05-24 23:25:42 +00005008 LHS = getSCEVAtScope(LHS, L);
5009 RHS = getSCEVAtScope(RHS, L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005010
Dan Gohmance973df2009-06-24 04:48:43 +00005011 // At this point, we would like to compute how many iterations of the
Reid Spencer266e42b2006-12-23 06:05:41 +00005012 // loop the predicate will return true for these inputs.
Dan Gohmanafd6db92010-11-17 21:23:15 +00005013 if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
Dan Gohmandc5f5cb2008-09-16 18:52:57 +00005014 // If there is a loop-invariant, force it into the RHS.
Chris Lattnerd934c702004-04-02 20:23:17 +00005015 std::swap(LHS, RHS);
Reid Spencer266e42b2006-12-23 06:05:41 +00005016 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattnerd934c702004-04-02 20:23:17 +00005017 }
5018
Dan Gohman81585c12010-05-03 16:35:17 +00005019 // Simplify the operands before analyzing them.
5020 (void)SimplifyICmpOperands(Cond, LHS, RHS);
5021
Chris Lattnerd934c702004-04-02 20:23:17 +00005022 // If we have a comparison of a chrec against a constant, try to use value
5023 // ranges to answer this query.
Dan Gohmana30370b2009-05-04 22:02:23 +00005024 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
5025 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Chris Lattnerd934c702004-04-02 20:23:17 +00005026 if (AddRec->getLoop() == L) {
Eli Friedmanebf98b02009-05-09 12:32:42 +00005027 // Form the constant range.
5028 ConstantRange CompRange(
5029 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Misha Brukman01808ca2005-04-21 21:13:18 +00005030
Dan Gohmanaf752342009-07-07 17:06:11 +00005031 const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedmanebf98b02009-05-09 12:32:42 +00005032 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Chris Lattnerd934c702004-04-02 20:23:17 +00005033 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005034
Chris Lattnerd934c702004-04-02 20:23:17 +00005035 switch (Cond) {
Reid Spencer266e42b2006-12-23 06:05:41 +00005036 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattnerd934c702004-04-02 20:23:17 +00005037 // Convert to: while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005038 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005039 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005040 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005041 }
Dan Gohman8a8ad7d2009-08-20 16:42:55 +00005042 case ICmpInst::ICMP_EQ: { // while (X == Y)
5043 // Convert to: while (X-Y == 0)
Andrew Trick3ca3f982011-07-26 17:19:55 +00005044 ExitLimit EL = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
5045 if (EL.hasAnyInfo()) return EL;
Chris Lattnerd934c702004-04-02 20:23:17 +00005046 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005047 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005048 case ICmpInst::ICMP_SLT:
5049 case ICmpInst::ICMP_ULT: { // while (X < Y)
5050 bool IsSigned = Cond == ICmpInst::ICMP_SLT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005051 ExitLimit EL = HowManyLessThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005052 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005053 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005054 }
Andrew Trick34e2f0c2013-11-06 02:08:26 +00005055 case ICmpInst::ICMP_SGT:
5056 case ICmpInst::ICMP_UGT: { // while (X > Y)
5057 bool IsSigned = Cond == ICmpInst::ICMP_SGT;
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005058 ExitLimit EL = HowManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit);
Andrew Trick3ca3f982011-07-26 17:19:55 +00005059 if (EL.hasAnyInfo()) return EL;
Chris Lattner587a75b2005-08-15 23:33:51 +00005060 break;
Reid Spencer266e42b2006-12-23 06:05:41 +00005061 }
Chris Lattnerd934c702004-04-02 20:23:17 +00005062 default:
Chris Lattner09169212004-04-02 20:26:46 +00005063#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005064 dbgs() << "ComputeBackedgeTakenCount ";
Chris Lattnerd934c702004-04-02 20:23:17 +00005065 if (ExitCond->getOperand(0)->getType()->isUnsigned())
David Greenedf1c4972009-12-23 22:18:14 +00005066 dbgs() << "[unsigned] ";
5067 dbgs() << *LHS << " "
Dan Gohmance973df2009-06-24 04:48:43 +00005068 << Instruction::getOpcodeName(Instruction::ICmp)
Reid Spencer266e42b2006-12-23 06:05:41 +00005069 << " " << *RHS << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00005070#endif
Chris Lattner0defaa12004-04-03 00:43:03 +00005071 break;
Chris Lattnerd934c702004-04-02 20:23:17 +00005072 }
Andrew Trick3ca3f982011-07-26 17:19:55 +00005073 return ComputeExitCountExhaustively(L, ExitCond, !L->contains(TBB));
Chris Lattner4021d1a2004-04-17 18:36:24 +00005074}
5075
Benjamin Kramer5a188542014-02-11 15:44:32 +00005076ScalarEvolution::ExitLimit
5077ScalarEvolution::ComputeExitLimitFromSingleExitSwitch(const Loop *L,
5078 SwitchInst *Switch,
5079 BasicBlock *ExitingBlock,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005080 bool ControlsExit) {
Benjamin Kramer5a188542014-02-11 15:44:32 +00005081 assert(!L->contains(ExitingBlock) && "Not an exiting block!");
5082
5083 // Give up if the exit is the default dest of a switch.
5084 if (Switch->getDefaultDest() == ExitingBlock)
5085 return getCouldNotCompute();
5086
5087 assert(L->contains(Switch->getDefaultDest()) &&
5088 "Default case must not exit the loop!");
5089 const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
5090 const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
5091
5092 // while (X != Y) --> while (X-Y != 0)
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005093 ExitLimit EL = HowFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
Benjamin Kramer5a188542014-02-11 15:44:32 +00005094 if (EL.hasAnyInfo())
5095 return EL;
5096
5097 return getCouldNotCompute();
5098}
5099
Chris Lattnerec901cc2004-10-12 01:49:27 +00005100static ConstantInt *
Dan Gohmana37eaf22007-10-22 18:31:58 +00005101EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
5102 ScalarEvolution &SE) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005103 const SCEV *InVal = SE.getConstant(C);
5104 const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005105 assert(isa<SCEVConstant>(Val) &&
5106 "Evaluation of SCEV at constant didn't fold correctly?");
5107 return cast<SCEVConstant>(Val)->getValue();
5108}
5109
Andrew Trick3ca3f982011-07-26 17:19:55 +00005110/// ComputeLoadConstantCompareExitLimit - Given an exit condition of
Dan Gohman0bddac12009-02-24 18:55:53 +00005111/// 'icmp op load X, cst', try to see if we can compute the backedge
5112/// execution count.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005113ScalarEvolution::ExitLimit
5114ScalarEvolution::ComputeLoadConstantCompareExitLimit(
5115 LoadInst *LI,
5116 Constant *RHS,
5117 const Loop *L,
5118 ICmpInst::Predicate predicate) {
5119
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005120 if (LI->isVolatile()) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005121
5122 // Check to see if the loaded pointer is a getelementptr of a global.
Dan Gohmanba820342010-02-24 17:31:30 +00005123 // TODO: Use SCEV instead of manually grubbing with GEPs.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005124 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005125 if (!GEP) return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005126
5127 // Make sure that it is really a constant global we are gepping, with an
5128 // initializer, and make sure the first IDX is really 0.
5129 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman5d5bc6d2009-08-19 18:20:44 +00005130 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005131 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
5132 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005133 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005134
5135 // Okay, we allow one non-constant index into the GEP instruction.
Craig Topper9f008862014-04-15 04:59:12 +00005136 Value *VarIdx = nullptr;
Chris Lattnere166a852012-01-24 05:49:24 +00005137 std::vector<Constant*> Indexes;
Chris Lattnerec901cc2004-10-12 01:49:27 +00005138 unsigned VarIdxNum = 0;
5139 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
5140 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5141 Indexes.push_back(CI);
5142 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005143 if (VarIdx) return getCouldNotCompute(); // Multiple non-constant idx's.
Chris Lattnerec901cc2004-10-12 01:49:27 +00005144 VarIdx = GEP->getOperand(i);
5145 VarIdxNum = i-2;
Craig Topper9f008862014-04-15 04:59:12 +00005146 Indexes.push_back(nullptr);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005147 }
5148
Andrew Trick7004e4b2012-03-26 22:33:59 +00005149 // Loop-invariant loads may be a byproduct of loop optimization. Skip them.
5150 if (!VarIdx)
5151 return getCouldNotCompute();
5152
Chris Lattnerec901cc2004-10-12 01:49:27 +00005153 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
5154 // Check to see if X is a loop variant variable value now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005155 const SCEV *Idx = getSCEV(VarIdx);
Dan Gohman8ca08852009-05-24 23:25:42 +00005156 Idx = getSCEVAtScope(Idx, L);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005157
5158 // We can only recognize very limited forms of loop index expressions, in
5159 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohman48f82222009-05-04 22:30:44 +00005160 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanafd6db92010-11-17 21:23:15 +00005161 if (!IdxExpr || !IdxExpr->isAffine() || isLoopInvariant(IdxExpr, L) ||
Chris Lattnerec901cc2004-10-12 01:49:27 +00005162 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
5163 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005164 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005165
5166 unsigned MaxSteps = MaxBruteForceIterations;
5167 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Owen Andersonedb4a702009-07-24 23:12:02 +00005168 ConstantInt *ItCst = ConstantInt::get(
Owen Andersonb6b25302009-07-14 23:09:55 +00005169 cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanc8e23622009-04-21 23:15:49 +00005170 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Chris Lattnerec901cc2004-10-12 01:49:27 +00005171
5172 // Form the GEP offset.
5173 Indexes[VarIdxNum] = Val;
5174
Chris Lattnere166a852012-01-24 05:49:24 +00005175 Constant *Result = ConstantFoldLoadThroughGEPIndices(GV->getInitializer(),
5176 Indexes);
Craig Topper9f008862014-04-15 04:59:12 +00005177 if (!Result) break; // Cannot compute!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005178
5179 // Evaluate the condition for this iteration.
Reid Spencer266e42b2006-12-23 06:05:41 +00005180 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng75b871f2007-01-11 12:24:14 +00005181 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer983e3b32007-03-01 07:25:48 +00005182 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattnerec901cc2004-10-12 01:49:27 +00005183#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005184 dbgs() << "\n***\n*** Computed loop count " << *ItCst
Dan Gohmane20f8242009-04-21 00:47:46 +00005185 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
5186 << "***\n";
Chris Lattnerec901cc2004-10-12 01:49:27 +00005187#endif
5188 ++NumArrayLenItCounts;
Dan Gohmanc8e23622009-04-21 23:15:49 +00005189 return getConstant(ItCst); // Found terminating iteration!
Chris Lattnerec901cc2004-10-12 01:49:27 +00005190 }
5191 }
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005192 return getCouldNotCompute();
Chris Lattnerec901cc2004-10-12 01:49:27 +00005193}
5194
5195
Chris Lattnerdd730472004-04-17 22:58:41 +00005196/// CanConstantFold - Return true if we can constant fold an instruction of the
5197/// specified type, assuming that all operands were constants.
5198static bool CanConstantFold(const Instruction *I) {
Reid Spencer2341c222007-02-02 02:16:23 +00005199 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Nick Lewyckya6674c72011-10-22 19:58:20 +00005200 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5201 isa<LoadInst>(I))
Chris Lattnerdd730472004-04-17 22:58:41 +00005202 return true;
Misha Brukman01808ca2005-04-21 21:13:18 +00005203
Chris Lattnerdd730472004-04-17 22:58:41 +00005204 if (const CallInst *CI = dyn_cast<CallInst>(I))
5205 if (const Function *F = CI->getCalledFunction())
Dan Gohmana65951f2008-01-31 01:05:10 +00005206 return canConstantFoldCallTo(F);
Chris Lattnerdd730472004-04-17 22:58:41 +00005207 return false;
Chris Lattner4021d1a2004-04-17 18:36:24 +00005208}
5209
Andrew Trick3a86ba72011-10-05 03:25:31 +00005210/// Determine whether this instruction can constant evolve within this loop
5211/// assuming its operands can all constant evolve.
5212static bool canConstantEvolve(Instruction *I, const Loop *L) {
5213 // An instruction outside of the loop can't be derived from a loop PHI.
5214 if (!L->contains(I)) return false;
5215
5216 if (isa<PHINode>(I)) {
5217 if (L->getHeader() == I->getParent())
5218 return true;
5219 else
5220 // We don't currently keep track of the control flow needed to evaluate
5221 // PHIs, so we cannot handle PHIs inside of loops.
5222 return false;
5223 }
5224
5225 // If we won't be able to constant fold this expression even if the operands
5226 // are constants, bail early.
5227 return CanConstantFold(I);
5228}
5229
5230/// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
5231/// recursing through each instruction operand until reaching a loop header phi.
5232static PHINode *
5233getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
Andrew Tricke9162f12011-10-05 05:58:49 +00005234 DenseMap<Instruction *, PHINode *> &PHIMap) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005235
5236 // Otherwise, we can evaluate this instruction if all of its operands are
5237 // constant or derived from a PHI node themselves.
Craig Topper9f008862014-04-15 04:59:12 +00005238 PHINode *PHI = nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005239 for (Instruction::op_iterator OpI = UseInst->op_begin(),
5240 OpE = UseInst->op_end(); OpI != OpE; ++OpI) {
5241
5242 if (isa<Constant>(*OpI)) continue;
5243
5244 Instruction *OpInst = dyn_cast<Instruction>(*OpI);
Craig Topper9f008862014-04-15 04:59:12 +00005245 if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005246
5247 PHINode *P = dyn_cast<PHINode>(OpInst);
Andrew Trick3e8a5762011-10-05 22:06:53 +00005248 if (!P)
5249 // If this operand is already visited, reuse the prior result.
5250 // We may have P != PHI if this is the deepest point at which the
5251 // inconsistent paths meet.
5252 P = PHIMap.lookup(OpInst);
5253 if (!P) {
5254 // Recurse and memoize the results, whether a phi is found or not.
5255 // This recursive call invalidates pointers into PHIMap.
5256 P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap);
5257 PHIMap[OpInst] = P;
Andrew Tricke9162f12011-10-05 05:58:49 +00005258 }
Craig Topper9f008862014-04-15 04:59:12 +00005259 if (!P)
5260 return nullptr; // Not evolving from PHI
5261 if (PHI && PHI != P)
5262 return nullptr; // Evolving from multiple different PHIs.
Andrew Tricke9162f12011-10-05 05:58:49 +00005263 PHI = P;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005264 }
5265 // This is a expression evolving from a constant PHI!
5266 return PHI;
5267}
5268
Chris Lattnerdd730472004-04-17 22:58:41 +00005269/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
5270/// in the loop that V is derived from. We allow arbitrary operations along the
5271/// way, but the operands of an operation must either be constants or a value
5272/// derived from a constant PHI. If this expression does not fit with these
5273/// constraints, return null.
5274static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005275 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005276 if (!I || !canConstantEvolve(I, L)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005277
Anton Korobeynikov579f0712008-02-20 11:08:44 +00005278 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Andrew Trick3a86ba72011-10-05 03:25:31 +00005279 return PN;
Anton Korobeynikov579f0712008-02-20 11:08:44 +00005280 }
Chris Lattnerdd730472004-04-17 22:58:41 +00005281
Andrew Trick3a86ba72011-10-05 03:25:31 +00005282 // Record non-constant instructions contained by the loop.
Andrew Tricke9162f12011-10-05 05:58:49 +00005283 DenseMap<Instruction *, PHINode *> PHIMap;
5284 return getConstantEvolvingPHIOperands(I, L, PHIMap);
Chris Lattnerdd730472004-04-17 22:58:41 +00005285}
5286
5287/// EvaluateExpression - Given an expression that passes the
5288/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
5289/// in the loop has the value PHIVal. If we can't fold this expression for some
5290/// reason, return null.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005291static Constant *EvaluateExpression(Value *V, const Loop *L,
5292 DenseMap<Instruction *, Constant *> &Vals,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005293 const DataLayout *DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005294 const TargetLibraryInfo *TLI) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005295 // Convenient constant check, but redundant for recursive calls.
Reid Spencer30d69a52004-07-18 00:18:30 +00005296 if (Constant *C = dyn_cast<Constant>(V)) return C;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005297 Instruction *I = dyn_cast<Instruction>(V);
Craig Topper9f008862014-04-15 04:59:12 +00005298 if (!I) return nullptr;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005299
Andrew Trick3a86ba72011-10-05 03:25:31 +00005300 if (Constant *C = Vals.lookup(I)) return C;
5301
Nick Lewyckya6674c72011-10-22 19:58:20 +00005302 // An instruction inside the loop depends on a value outside the loop that we
5303 // weren't given a mapping for, or a value such as a call inside the loop.
Craig Topper9f008862014-04-15 04:59:12 +00005304 if (!canConstantEvolve(I, L)) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005305
5306 // An unmapped PHI can be due to a branch or another loop inside this loop,
5307 // or due to this not being the initial iteration through a loop where we
5308 // couldn't compute the evolution of this particular PHI last time.
Craig Topper9f008862014-04-15 04:59:12 +00005309 if (isa<PHINode>(I)) return nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005310
Dan Gohmanf820bd32010-06-22 13:15:46 +00005311 std::vector<Constant*> Operands(I->getNumOperands());
Chris Lattnerdd730472004-04-17 22:58:41 +00005312
5313 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
Andrew Tricke9162f12011-10-05 05:58:49 +00005314 Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
5315 if (!Operand) {
Nick Lewyckya447e0f32011-10-14 09:38:46 +00005316 Operands[i] = dyn_cast<Constant>(I->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005317 if (!Operands[i]) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005318 continue;
5319 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005320 Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
Andrew Tricke9162f12011-10-05 05:58:49 +00005321 Vals[Operand] = C;
Craig Topper9f008862014-04-15 04:59:12 +00005322 if (!C) return nullptr;
Andrew Tricke9162f12011-10-05 05:58:49 +00005323 Operands[i] = C;
Chris Lattnerdd730472004-04-17 22:58:41 +00005324 }
5325
Nick Lewyckya6674c72011-10-22 19:58:20 +00005326 if (CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00005327 return ConstantFoldCompareInstOperands(CI->getPredicate(), Operands[0],
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005328 Operands[1], DL, TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005329 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5330 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005331 return ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005332 }
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005333 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Operands, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005334 TLI);
Chris Lattnerdd730472004-04-17 22:58:41 +00005335}
5336
5337/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
5338/// in the header of its containing loop, we know the loop executes a
5339/// constant number of times, and the PHI node is just a recurrence
5340/// involving constants, fold it.
Dan Gohmance973df2009-06-24 04:48:43 +00005341Constant *
5342ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
Dan Gohmancb0efec2009-12-18 01:14:11 +00005343 const APInt &BEs,
Dan Gohmance973df2009-06-24 04:48:43 +00005344 const Loop *L) {
Dan Gohman0daf6872011-05-09 18:44:09 +00005345 DenseMap<PHINode*, Constant*>::const_iterator I =
Chris Lattnerdd730472004-04-17 22:58:41 +00005346 ConstantEvolutionLoopExitValue.find(PN);
5347 if (I != ConstantEvolutionLoopExitValue.end())
5348 return I->second;
5349
Dan Gohman4ce1fb12010-04-08 23:03:40 +00005350 if (BEs.ugt(MaxBruteForceIterations))
Craig Topper9f008862014-04-15 04:59:12 +00005351 return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
Chris Lattnerdd730472004-04-17 22:58:41 +00005352
5353 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
5354
Andrew Trick3a86ba72011-10-05 03:25:31 +00005355 DenseMap<Instruction *, Constant *> CurrentIterVals;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005356 BasicBlock *Header = L->getHeader();
5357 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
Andrew Trick3a86ba72011-10-05 03:25:31 +00005358
Chris Lattnerdd730472004-04-17 22:58:41 +00005359 // Since the loop is canonicalized, the PHI node must have two entries. One
5360 // entry must be a constant (coming in from outside of the loop), and the
5361 // second must be derived from the same PHI.
5362 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Craig Topper9f008862014-04-15 04:59:12 +00005363 PHINode *PHI = nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005364 for (BasicBlock::iterator I = Header->begin();
5365 (PHI = dyn_cast<PHINode>(I)); ++I) {
5366 Constant *StartCST =
5367 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
Craig Topper9f008862014-04-15 04:59:12 +00005368 if (!StartCST) continue;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005369 CurrentIterVals[PHI] = StartCST;
5370 }
5371 if (!CurrentIterVals.count(PN))
Craig Topper9f008862014-04-15 04:59:12 +00005372 return RetVal = nullptr;
Chris Lattnerdd730472004-04-17 22:58:41 +00005373
5374 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
Chris Lattnerdd730472004-04-17 22:58:41 +00005375
5376 // Execute the loop symbolically to determine the exit value.
Dan Gohman0bddac12009-02-24 18:55:53 +00005377 if (BEs.getActiveBits() >= 32)
Craig Topper9f008862014-04-15 04:59:12 +00005378 return RetVal = nullptr; // More than 2^32-1 iterations?? Not doing it!
Chris Lattnerdd730472004-04-17 22:58:41 +00005379
Dan Gohman0bddac12009-02-24 18:55:53 +00005380 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Reid Spencer983e3b32007-03-01 07:25:48 +00005381 unsigned IterationNum = 0;
Andrew Trick3a86ba72011-10-05 03:25:31 +00005382 for (; ; ++IterationNum) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005383 if (IterationNum == NumIterations)
Andrew Trick3a86ba72011-10-05 03:25:31 +00005384 return RetVal = CurrentIterVals[PN]; // Got exit value!
Chris Lattnerdd730472004-04-17 22:58:41 +00005385
Nick Lewyckya6674c72011-10-22 19:58:20 +00005386 // Compute the value of the PHIs for the next iteration.
Andrew Trick3a86ba72011-10-05 03:25:31 +00005387 // EvaluateExpression adds non-phi values to the CurrentIterVals map.
Nick Lewyckya6674c72011-10-22 19:58:20 +00005388 DenseMap<Instruction *, Constant *> NextIterVals;
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005389 Constant *NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL,
Chad Rosiere6de63d2011-12-01 21:29:16 +00005390 TLI);
Craig Topper9f008862014-04-15 04:59:12 +00005391 if (!NextPHI)
5392 return nullptr; // Couldn't evaluate!
Andrew Trick3a86ba72011-10-05 03:25:31 +00005393 NextIterVals[PN] = NextPHI;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005394
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005395 bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
5396
Nick Lewyckya6674c72011-10-22 19:58:20 +00005397 // Also evaluate the other PHI nodes. However, we don't get to stop if we
5398 // cease to be able to evaluate one of them or if they stop evolving,
5399 // because that doesn't necessarily prevent us from computing PN.
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005400 SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005401 for (DenseMap<Instruction *, Constant *>::const_iterator
5402 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5403 PHINode *PHI = dyn_cast<PHINode>(I->first);
Nick Lewycky8e904de2011-10-24 05:51:01 +00005404 if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005405 PHIsToCompute.push_back(std::make_pair(PHI, I->second));
5406 }
5407 // We use two distinct loops because EvaluateExpression may invalidate any
5408 // iterators into CurrentIterVals.
5409 for (SmallVectorImpl<std::pair<PHINode *, Constant*> >::const_iterator
5410 I = PHIsToCompute.begin(), E = PHIsToCompute.end(); I != E; ++I) {
5411 PHINode *PHI = I->first;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005412 Constant *&NextPHI = NextIterVals[PHI];
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005413 if (!NextPHI) { // Not already computed.
5414 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005415 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005416 }
5417 if (NextPHI != I->second)
5418 StoppedEvolving = false;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005419 }
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005420
5421 // If all entries in CurrentIterVals == NextIterVals then we can stop
5422 // iterating, the loop can't continue to change.
5423 if (StoppedEvolving)
5424 return RetVal = CurrentIterVals[PN];
5425
Andrew Trick3a86ba72011-10-05 03:25:31 +00005426 CurrentIterVals.swap(NextIterVals);
Chris Lattnerdd730472004-04-17 22:58:41 +00005427 }
5428}
5429
Andrew Trick3ca3f982011-07-26 17:19:55 +00005430/// ComputeExitCountExhaustively - If the loop is known to execute a
Chris Lattner4021d1a2004-04-17 18:36:24 +00005431/// constant number of times (the condition evolves only from constants),
5432/// try to evaluate a few iterations of the loop until we get the exit
5433/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005434/// evaluate the trip count of the loop, return getCouldNotCompute().
Nick Lewyckya6674c72011-10-22 19:58:20 +00005435const SCEV *ScalarEvolution::ComputeExitCountExhaustively(const Loop *L,
5436 Value *Cond,
5437 bool ExitWhen) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005438 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Craig Topper9f008862014-04-15 04:59:12 +00005439 if (!PN) return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005440
Dan Gohman866971e2010-06-19 14:17:24 +00005441 // If the loop is canonicalized, the PHI will have exactly two entries.
5442 // That's the only form we support here.
5443 if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
5444
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005445 DenseMap<Instruction *, Constant *> CurrentIterVals;
5446 BasicBlock *Header = L->getHeader();
5447 assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
5448
Dan Gohman866971e2010-06-19 14:17:24 +00005449 // One entry must be a constant (coming in from outside of the loop), and the
Chris Lattner4021d1a2004-04-17 18:36:24 +00005450 // second must be derived from the same PHI.
5451 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
Craig Topper9f008862014-04-15 04:59:12 +00005452 PHINode *PHI = nullptr;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005453 for (BasicBlock::iterator I = Header->begin();
5454 (PHI = dyn_cast<PHINode>(I)); ++I) {
5455 Constant *StartCST =
5456 dyn_cast<Constant>(PHI->getIncomingValue(!SecondIsBackedge));
Craig Topper9f008862014-04-15 04:59:12 +00005457 if (!StartCST) continue;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005458 CurrentIterVals[PHI] = StartCST;
5459 }
5460 if (!CurrentIterVals.count(PN))
5461 return getCouldNotCompute();
Chris Lattner4021d1a2004-04-17 18:36:24 +00005462
5463 // Okay, we find a PHI node that defines the trip count of this loop. Execute
5464 // the loop symbolically to determine when the condition gets a value of
5465 // "ExitWhen".
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005466
Andrew Trick90c7a102011-11-16 00:52:40 +00005467 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005468 for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
Zhou Sheng75b871f2007-01-11 12:24:14 +00005469 ConstantInt *CondVal =
Chad Rosiere6de63d2011-12-01 21:29:16 +00005470 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, L, CurrentIterVals,
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005471 DL, TLI));
Chris Lattnerdd730472004-04-17 22:58:41 +00005472
Zhou Sheng75b871f2007-01-11 12:24:14 +00005473 // Couldn't symbolically evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005474 if (!CondVal) return getCouldNotCompute();
Zhou Sheng75b871f2007-01-11 12:24:14 +00005475
Reid Spencer983e3b32007-03-01 07:25:48 +00005476 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner4021d1a2004-04-17 18:36:24 +00005477 ++NumBruteForceTripCountsComputed;
Owen Anderson55f1c092009-08-13 21:58:54 +00005478 return getConstant(Type::getInt32Ty(getContext()), IterationNum);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005479 }
Misha Brukman01808ca2005-04-21 21:13:18 +00005480
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005481 // Update all the PHI nodes for the next iteration.
5482 DenseMap<Instruction *, Constant *> NextIterVals;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005483
5484 // Create a list of which PHIs we need to compute. We want to do this before
5485 // calling EvaluateExpression on them because that may invalidate iterators
5486 // into CurrentIterVals.
5487 SmallVector<PHINode *, 8> PHIsToCompute;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005488 for (DenseMap<Instruction *, Constant *>::const_iterator
5489 I = CurrentIterVals.begin(), E = CurrentIterVals.end(); I != E; ++I){
5490 PHINode *PHI = dyn_cast<PHINode>(I->first);
5491 if (!PHI || PHI->getParent() != Header) continue;
Nick Lewyckyd48ab842011-11-12 03:09:12 +00005492 PHIsToCompute.push_back(PHI);
5493 }
5494 for (SmallVectorImpl<PHINode *>::const_iterator I = PHIsToCompute.begin(),
5495 E = PHIsToCompute.end(); I != E; ++I) {
5496 PHINode *PHI = *I;
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005497 Constant *&NextPHI = NextIterVals[PHI];
5498 if (NextPHI) continue; // Already computed!
5499
5500 Value *BEValue = PHI->getIncomingValue(SecondIsBackedge);
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005501 NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, TLI);
Duncan Sandsa370f3e2011-10-25 12:28:52 +00005502 }
5503 CurrentIterVals.swap(NextIterVals);
Chris Lattner4021d1a2004-04-17 18:36:24 +00005504 }
5505
5506 // Too many iterations were needed to evaluate.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005507 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005508}
5509
Dan Gohman237d9e52009-09-03 15:00:26 +00005510/// getSCEVAtScope - Return a SCEV expression for the specified value
Dan Gohmanb81f47d2009-05-08 20:38:54 +00005511/// at the specified scope in the program. The L value specifies a loop
5512/// nest to evaluate the expression at, where null is the top-level or a
5513/// specified loop is immediately inside of the loop.
5514///
5515/// This method can be used to compute the exit value for a variable defined
5516/// in a loop by querying what the value will hold in the parent loop.
5517///
Dan Gohman8ca08852009-05-24 23:25:42 +00005518/// In the case that a relevant loop exit value cannot be computed, the
5519/// original value V is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00005520const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005521 // Check to see if we've folded this expression at this loop before.
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005522 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values = ValuesAtScopes[V];
5523 for (unsigned u = 0; u < Values.size(); u++) {
5524 if (Values[u].first == L)
5525 return Values[u].second ? Values[u].second : V;
5526 }
Craig Topper9f008862014-04-15 04:59:12 +00005527 Values.push_back(std::make_pair(L, static_cast<const SCEV *>(nullptr)));
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005528 // Otherwise compute it.
5529 const SCEV *C = computeSCEVAtScope(V, L);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00005530 SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values2 = ValuesAtScopes[V];
5531 for (unsigned u = Values2.size(); u > 0; u--) {
5532 if (Values2[u - 1].first == L) {
5533 Values2[u - 1].second = C;
5534 break;
5535 }
5536 }
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005537 return C;
5538}
5539
Nick Lewyckya6674c72011-10-22 19:58:20 +00005540/// This builds up a Constant using the ConstantExpr interface. That way, we
5541/// will return Constants for objects which aren't represented by a
5542/// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
5543/// Returns NULL if the SCEV isn't representable as a Constant.
5544static Constant *BuildConstantFromSCEV(const SCEV *V) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00005545 switch (static_cast<SCEVTypes>(V->getSCEVType())) {
Nick Lewyckya6674c72011-10-22 19:58:20 +00005546 case scCouldNotCompute:
5547 case scAddRecExpr:
5548 break;
5549 case scConstant:
5550 return cast<SCEVConstant>(V)->getValue();
5551 case scUnknown:
5552 return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
5553 case scSignExtend: {
5554 const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
5555 if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
5556 return ConstantExpr::getSExt(CastOp, SS->getType());
5557 break;
5558 }
5559 case scZeroExtend: {
5560 const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
5561 if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
5562 return ConstantExpr::getZExt(CastOp, SZ->getType());
5563 break;
5564 }
5565 case scTruncate: {
5566 const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
5567 if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
5568 return ConstantExpr::getTrunc(CastOp, ST->getType());
5569 break;
5570 }
5571 case scAddExpr: {
5572 const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
5573 if (Constant *C = BuildConstantFromSCEV(SA->getOperand(0))) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005574 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5575 unsigned AS = PTy->getAddressSpace();
5576 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
5577 C = ConstantExpr::getBitCast(C, DestPtrTy);
5578 }
Nick Lewyckya6674c72011-10-22 19:58:20 +00005579 for (unsigned i = 1, e = SA->getNumOperands(); i != e; ++i) {
5580 Constant *C2 = BuildConstantFromSCEV(SA->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005581 if (!C2) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005582
5583 // First pointer!
5584 if (!C->getType()->isPointerTy() && C2->getType()->isPointerTy()) {
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005585 unsigned AS = C2->getType()->getPointerAddressSpace();
Nick Lewyckya6674c72011-10-22 19:58:20 +00005586 std::swap(C, C2);
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005587 Type *DestPtrTy = Type::getInt8PtrTy(C->getContext(), AS);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005588 // The offsets have been converted to bytes. We can add bytes to an
5589 // i8* by GEP with the byte count in the first index.
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005590 C = ConstantExpr::getBitCast(C, DestPtrTy);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005591 }
5592
5593 // Don't bother trying to sum two pointers. We probably can't
5594 // statically compute a load that results from it anyway.
5595 if (C2->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +00005596 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005597
Matt Arsenaultbe18b8a2013-10-21 18:41:10 +00005598 if (PointerType *PTy = dyn_cast<PointerType>(C->getType())) {
5599 if (PTy->getElementType()->isStructTy())
Nick Lewyckya6674c72011-10-22 19:58:20 +00005600 C2 = ConstantExpr::getIntegerCast(
5601 C2, Type::getInt32Ty(C->getContext()), true);
5602 C = ConstantExpr::getGetElementPtr(C, C2);
5603 } else
5604 C = ConstantExpr::getAdd(C, C2);
5605 }
5606 return C;
5607 }
5608 break;
5609 }
5610 case scMulExpr: {
5611 const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
5612 if (Constant *C = BuildConstantFromSCEV(SM->getOperand(0))) {
5613 // Don't bother with pointers at all.
Craig Topper9f008862014-04-15 04:59:12 +00005614 if (C->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005615 for (unsigned i = 1, e = SM->getNumOperands(); i != e; ++i) {
5616 Constant *C2 = BuildConstantFromSCEV(SM->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00005617 if (!C2 || C2->getType()->isPointerTy()) return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005618 C = ConstantExpr::getMul(C, C2);
5619 }
5620 return C;
5621 }
5622 break;
5623 }
5624 case scUDivExpr: {
5625 const SCEVUDivExpr *SU = cast<SCEVUDivExpr>(V);
5626 if (Constant *LHS = BuildConstantFromSCEV(SU->getLHS()))
5627 if (Constant *RHS = BuildConstantFromSCEV(SU->getRHS()))
5628 if (LHS->getType() == RHS->getType())
5629 return ConstantExpr::getUDiv(LHS, RHS);
5630 break;
5631 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00005632 case scSMaxExpr:
5633 case scUMaxExpr:
5634 break; // TODO: smax, umax.
Nick Lewyckya6674c72011-10-22 19:58:20 +00005635 }
Craig Topper9f008862014-04-15 04:59:12 +00005636 return nullptr;
Nick Lewyckya6674c72011-10-22 19:58:20 +00005637}
5638
Dan Gohmancc2f1eb2009-08-31 21:15:23 +00005639const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005640 if (isa<SCEVConstant>(V)) return V;
Misha Brukman01808ca2005-04-21 21:13:18 +00005641
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00005642 // If this instruction is evolved from a constant-evolving PHI, compute the
Chris Lattnerdd730472004-04-17 22:58:41 +00005643 // exit value from the loop without using SCEVs.
Dan Gohmana30370b2009-05-04 22:02:23 +00005644 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005645 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00005646 const Loop *LI = (*this->LI)[I->getParent()];
Chris Lattnerdd730472004-04-17 22:58:41 +00005647 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
5648 if (PHINode *PN = dyn_cast<PHINode>(I))
5649 if (PN->getParent() == LI->getHeader()) {
5650 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman0bddac12009-02-24 18:55:53 +00005651 // to see if the loop that contains it has a known backedge-taken
5652 // count. If so, we may be able to force computation of the exit
5653 // value.
Dan Gohmanaf752342009-07-07 17:06:11 +00005654 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmana30370b2009-05-04 22:02:23 +00005655 if (const SCEVConstant *BTCC =
Dan Gohman0bddac12009-02-24 18:55:53 +00005656 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Chris Lattnerdd730472004-04-17 22:58:41 +00005657 // Okay, we know how many times the containing loop executes. If
5658 // this is a constant evolving PHI node, get the final value at
5659 // the specified iteration number.
5660 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman0bddac12009-02-24 18:55:53 +00005661 BTCC->getValue()->getValue(),
Chris Lattnerdd730472004-04-17 22:58:41 +00005662 LI);
Dan Gohman9d203c62009-06-29 21:31:18 +00005663 if (RV) return getSCEV(RV);
Chris Lattnerdd730472004-04-17 22:58:41 +00005664 }
5665 }
5666
Reid Spencere6328ca2006-12-04 21:33:23 +00005667 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattnerdd730472004-04-17 22:58:41 +00005668 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencere6328ca2006-12-04 21:33:23 +00005669 // the arguments into constants, and if so, try to constant propagate the
Chris Lattnerdd730472004-04-17 22:58:41 +00005670 // result. This is particularly useful for computing loop exit values.
5671 if (CanConstantFold(I)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005672 SmallVector<Constant *, 4> Operands;
5673 bool MadeImprovement = false;
Chris Lattnerdd730472004-04-17 22:58:41 +00005674 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
5675 Value *Op = I->getOperand(i);
5676 if (Constant *C = dyn_cast<Constant>(Op)) {
5677 Operands.push_back(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005678 continue;
Chris Lattnerdd730472004-04-17 22:58:41 +00005679 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005680
5681 // If any of the operands is non-constant and if they are
5682 // non-integer and non-pointer, don't even try to analyze them
5683 // with scev techniques.
5684 if (!isSCEVable(Op->getType()))
5685 return V;
5686
5687 const SCEV *OrigV = getSCEV(Op);
5688 const SCEV *OpV = getSCEVAtScope(OrigV, L);
5689 MadeImprovement |= OrigV != OpV;
5690
Nick Lewyckya6674c72011-10-22 19:58:20 +00005691 Constant *C = BuildConstantFromSCEV(OpV);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005692 if (!C) return V;
5693 if (C->getType() != Op->getType())
5694 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
5695 Op->getType(),
5696 false),
5697 C, Op->getType());
5698 Operands.push_back(C);
Chris Lattnerdd730472004-04-17 22:58:41 +00005699 }
Dan Gohmance973df2009-06-24 04:48:43 +00005700
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005701 // Check to see if getSCEVAtScope actually made an improvement.
5702 if (MadeImprovement) {
Craig Topper9f008862014-04-15 04:59:12 +00005703 Constant *C = nullptr;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005704 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
5705 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005706 Operands[0], Operands[1], DL,
Chad Rosier43a33062011-12-02 01:26:24 +00005707 TLI);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005708 else if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
5709 if (!LI->isVolatile())
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005710 C = ConstantFoldLoadFromConstPtr(Operands[0], DL);
Nick Lewyckya6674c72011-10-22 19:58:20 +00005711 } else
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005712 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
Rafael Espindola7c68beb2014-02-18 15:33:12 +00005713 Operands, DL, TLI);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005714 if (!C) return V;
Dan Gohman4aad7502010-02-24 19:31:47 +00005715 return getSCEV(C);
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005716 }
Chris Lattnerdd730472004-04-17 22:58:41 +00005717 }
5718 }
5719
5720 // This is some other type of SCEVUnknown, just return it.
5721 return V;
5722 }
5723
Dan Gohmana30370b2009-05-04 22:02:23 +00005724 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005725 // Avoid performing the look-up in the common case where the specified
5726 // expression has no loop-variant portions.
5727 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005728 const SCEV *OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005729 if (OpAtScope != Comm->getOperand(i)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005730 // Okay, at least one of these operands is loop variant but might be
5731 // foldable. Build a new instance of the folded commutative expression.
Dan Gohmance973df2009-06-24 04:48:43 +00005732 SmallVector<const SCEV *, 8> NewOps(Comm->op_begin(),
5733 Comm->op_begin()+i);
Chris Lattnerd934c702004-04-02 20:23:17 +00005734 NewOps.push_back(OpAtScope);
5735
5736 for (++i; i != e; ++i) {
5737 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Chris Lattnerd934c702004-04-02 20:23:17 +00005738 NewOps.push_back(OpAtScope);
5739 }
5740 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005741 return getAddExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00005742 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005743 return getMulExpr(NewOps);
Nick Lewyckycdb7e542007-11-25 22:41:31 +00005744 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005745 return getSMaxExpr(NewOps);
Nick Lewycky1c44ebc2008-02-20 06:48:22 +00005746 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanc8e23622009-04-21 23:15:49 +00005747 return getUMaxExpr(NewOps);
Torok Edwinfbcc6632009-07-14 16:55:14 +00005748 llvm_unreachable("Unknown commutative SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00005749 }
5750 }
5751 // If we got here, all operands are loop invariant.
5752 return Comm;
5753 }
5754
Dan Gohmana30370b2009-05-04 22:02:23 +00005755 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005756 const SCEV *LHS = getSCEVAtScope(Div->getLHS(), L);
5757 const SCEV *RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky52348302009-01-13 09:18:58 +00005758 if (LHS == Div->getLHS() && RHS == Div->getRHS())
5759 return Div; // must be loop invariant
Dan Gohmanc8e23622009-04-21 23:15:49 +00005760 return getUDivExpr(LHS, RHS);
Chris Lattnerd934c702004-04-02 20:23:17 +00005761 }
5762
5763 // If this is a loop recurrence for a loop that does not contain L, then we
5764 // are dealing with the final value computed by the loop.
Dan Gohmana30370b2009-05-04 22:02:23 +00005765 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005766 // First, attempt to evaluate each operand.
5767 // Avoid performing the look-up in the common case where the specified
5768 // expression has no loop-variant portions.
5769 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
5770 const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
5771 if (OpAtScope == AddRec->getOperand(i))
5772 continue;
5773
5774 // Okay, at least one of these operands is loop variant but might be
5775 // foldable. Build a new instance of the folded commutative expression.
5776 SmallVector<const SCEV *, 8> NewOps(AddRec->op_begin(),
5777 AddRec->op_begin()+i);
5778 NewOps.push_back(OpAtScope);
5779 for (++i; i != e; ++i)
5780 NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
5781
Andrew Trick759ba082011-04-27 01:21:25 +00005782 const SCEV *FoldedRec =
Andrew Trick8b55b732011-03-14 16:50:06 +00005783 getAddRecExpr(NewOps, AddRec->getLoop(),
Andrew Trick759ba082011-04-27 01:21:25 +00005784 AddRec->getNoWrapFlags(SCEV::FlagNW));
5785 AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
Andrew Trick01eff822011-04-27 05:42:17 +00005786 // The addrec may be folded to a nonrecurrence, for example, if the
5787 // induction variable is multiplied by zero after constant folding. Go
5788 // ahead and return the folded value.
Andrew Trick759ba082011-04-27 01:21:25 +00005789 if (!AddRec)
5790 return FoldedRec;
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005791 break;
5792 }
5793
5794 // If the scope is outside the addrec's loop, evaluate it by using the
5795 // loop exit value of the addrec.
5796 if (!AddRec->getLoop()->contains(L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005797 // To evaluate this recurrence, we need to know how many times the AddRec
5798 // loop iterates. Compute this now.
Dan Gohmanaf752342009-07-07 17:06:11 +00005799 const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005800 if (BackedgeTakenCount == getCouldNotCompute()) return AddRec;
Misha Brukman01808ca2005-04-21 21:13:18 +00005801
Eli Friedman61f67622008-08-04 23:49:06 +00005802 // Then, evaluate the AddRec.
Dan Gohmanc8e23622009-04-21 23:15:49 +00005803 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Chris Lattnerd934c702004-04-02 20:23:17 +00005804 }
Dan Gohmanae36b1e2010-06-29 23:43:06 +00005805
Dan Gohman8ca08852009-05-24 23:25:42 +00005806 return AddRec;
Chris Lattnerd934c702004-04-02 20:23:17 +00005807 }
5808
Dan Gohmana30370b2009-05-04 22:02:23 +00005809 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005810 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005811 if (Op == Cast->getOperand())
5812 return Cast; // must be loop invariant
5813 return getZeroExtendExpr(Op, Cast->getType());
5814 }
5815
Dan Gohmana30370b2009-05-04 22:02:23 +00005816 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005817 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005818 if (Op == Cast->getOperand())
5819 return Cast; // must be loop invariant
5820 return getSignExtendExpr(Op, Cast->getType());
5821 }
5822
Dan Gohmana30370b2009-05-04 22:02:23 +00005823 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohmanaf752342009-07-07 17:06:11 +00005824 const SCEV *Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman0098d012009-04-29 22:29:01 +00005825 if (Op == Cast->getOperand())
5826 return Cast; // must be loop invariant
5827 return getTruncateExpr(Op, Cast->getType());
5828 }
5829
Torok Edwinfbcc6632009-07-14 16:55:14 +00005830 llvm_unreachable("Unknown SCEV type!");
Chris Lattnerd934c702004-04-02 20:23:17 +00005831}
5832
Dan Gohmanb81f47d2009-05-08 20:38:54 +00005833/// getSCEVAtScope - This is a convenience function which does
5834/// getSCEVAtScope(getSCEV(V), L).
Dan Gohmanaf752342009-07-07 17:06:11 +00005835const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00005836 return getSCEVAtScope(getSCEV(V), L);
5837}
5838
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005839/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
5840/// following equation:
5841///
5842/// A * X = B (mod N)
5843///
5844/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
5845/// A and B isn't important.
5846///
5847/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00005848static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005849 ScalarEvolution &SE) {
5850 uint32_t BW = A.getBitWidth();
5851 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
5852 assert(A != 0 && "A must be non-zero.");
5853
5854 // 1. D = gcd(A, N)
5855 //
5856 // The gcd of A and N may have only one prime factor: 2. The number of
5857 // trailing zeros in A is its multiplicity
5858 uint32_t Mult2 = A.countTrailingZeros();
5859 // D = 2^Mult2
5860
5861 // 2. Check if B is divisible by D.
5862 //
5863 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
5864 // is not less than multiplicity of this prime factor for D.
5865 if (B.countTrailingZeros() < Mult2)
Dan Gohman31efa302009-04-18 17:58:19 +00005866 return SE.getCouldNotCompute();
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005867
5868 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
5869 // modulo (N / D).
5870 //
5871 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
5872 // bit width during computations.
5873 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
5874 APInt Mod(BW + 1, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +00005875 Mod.setBit(BW - Mult2); // Mod = N / D
Wojciech Matyjewiczf0d21cd2008-07-20 15:55:14 +00005876 APInt I = AD.multiplicativeInverse(Mod);
5877
5878 // 4. Compute the minimum unsigned root of the equation:
5879 // I * (B / D) mod (N / D)
5880 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
5881
5882 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
5883 // bits.
5884 return SE.getConstant(Result.trunc(BW));
5885}
Chris Lattnerd934c702004-04-02 20:23:17 +00005886
5887/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
5888/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
5889/// might be the same) or two SCEVCouldNotCompute objects.
5890///
Dan Gohmanaf752342009-07-07 17:06:11 +00005891static std::pair<const SCEV *,const SCEV *>
Dan Gohmana37eaf22007-10-22 18:31:58 +00005892SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005893 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohman48f82222009-05-04 22:30:44 +00005894 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
5895 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
5896 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman01808ca2005-04-21 21:13:18 +00005897
Chris Lattnerd934c702004-04-02 20:23:17 +00005898 // We currently can only solve this if the coefficients are constants.
Reid Spencer983e3b32007-03-01 07:25:48 +00005899 if (!LC || !MC || !NC) {
Dan Gohman48f82222009-05-04 22:30:44 +00005900 const SCEV *CNC = SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005901 return std::make_pair(CNC, CNC);
5902 }
5903
Reid Spencer983e3b32007-03-01 07:25:48 +00005904 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnercad61e82007-04-15 19:52:49 +00005905 const APInt &L = LC->getValue()->getValue();
5906 const APInt &M = MC->getValue()->getValue();
5907 const APInt &N = NC->getValue()->getValue();
Reid Spencer983e3b32007-03-01 07:25:48 +00005908 APInt Two(BitWidth, 2);
5909 APInt Four(BitWidth, 4);
Misha Brukman01808ca2005-04-21 21:13:18 +00005910
Dan Gohmance973df2009-06-24 04:48:43 +00005911 {
Reid Spencer983e3b32007-03-01 07:25:48 +00005912 using namespace APIntOps;
Zhou Sheng2852d992007-04-07 17:48:27 +00005913 const APInt& C = L;
Reid Spencer983e3b32007-03-01 07:25:48 +00005914 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
5915 // The B coefficient is M-N/2
5916 APInt B(M);
5917 B -= sdiv(N,Two);
Misha Brukman01808ca2005-04-21 21:13:18 +00005918
Reid Spencer983e3b32007-03-01 07:25:48 +00005919 // The A coefficient is N/2
Zhou Sheng2852d992007-04-07 17:48:27 +00005920 APInt A(N.sdiv(Two));
Chris Lattnerd934c702004-04-02 20:23:17 +00005921
Reid Spencer983e3b32007-03-01 07:25:48 +00005922 // Compute the B^2-4ac term.
5923 APInt SqrtTerm(B);
5924 SqrtTerm *= B;
5925 SqrtTerm -= Four * (A * C);
Chris Lattnerd934c702004-04-02 20:23:17 +00005926
Nick Lewyckyfb780832012-08-01 09:14:36 +00005927 if (SqrtTerm.isNegative()) {
5928 // The loop is provably infinite.
5929 const SCEV *CNC = SE.getCouldNotCompute();
5930 return std::make_pair(CNC, CNC);
5931 }
5932
Reid Spencer983e3b32007-03-01 07:25:48 +00005933 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
5934 // integer value or else APInt::sqrt() will assert.
5935 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman01808ca2005-04-21 21:13:18 +00005936
Dan Gohmance973df2009-06-24 04:48:43 +00005937 // Compute the two solutions for the quadratic formula.
Reid Spencer983e3b32007-03-01 07:25:48 +00005938 // The divisions must be performed as signed divisions.
5939 APInt NegB(-B);
Nick Lewycky31555522011-10-03 07:10:45 +00005940 APInt TwoA(A << 1);
Nick Lewycky7b14e202008-11-03 02:43:49 +00005941 if (TwoA.isMinValue()) {
Dan Gohman48f82222009-05-04 22:30:44 +00005942 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky7b14e202008-11-03 02:43:49 +00005943 return std::make_pair(CNC, CNC);
5944 }
5945
Owen Anderson47db9412009-07-22 00:24:57 +00005946 LLVMContext &Context = SE.getContext();
Owen Andersonf1f17432009-07-06 22:37:39 +00005947
5948 ConstantInt *Solution1 =
Owen Andersonedb4a702009-07-24 23:12:02 +00005949 ConstantInt::get(Context, (NegB + SqrtVal).sdiv(TwoA));
Owen Andersonf1f17432009-07-06 22:37:39 +00005950 ConstantInt *Solution2 =
Owen Andersonedb4a702009-07-24 23:12:02 +00005951 ConstantInt::get(Context, (NegB - SqrtVal).sdiv(TwoA));
Misha Brukman01808ca2005-04-21 21:13:18 +00005952
Dan Gohmance973df2009-06-24 04:48:43 +00005953 return std::make_pair(SE.getConstant(Solution1),
Dan Gohmana37eaf22007-10-22 18:31:58 +00005954 SE.getConstant(Solution2));
Nick Lewycky31555522011-10-03 07:10:45 +00005955 } // end APIntOps namespace
Chris Lattnerd934c702004-04-02 20:23:17 +00005956}
5957
5958/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman4c720c02009-06-06 14:37:11 +00005959/// value to zero will execute. If not computable, return CouldNotCompute.
Andrew Trick8b55b732011-03-14 16:50:06 +00005960///
5961/// This is only used for loops with a "x != y" exit test. The exit condition is
5962/// now expressed as a single expression, V = x-y. So the exit test is
5963/// effectively V != 0. We know and take advantage of the fact that this
5964/// expression only being used in a comparison by zero context.
Andrew Trick3ca3f982011-07-26 17:19:55 +00005965ScalarEvolution::ExitLimit
Mark Heffernan2beab5f2014-10-10 17:39:11 +00005966ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L, bool ControlsExit) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005967 // If the value is a constant
Dan Gohmana30370b2009-05-04 22:02:23 +00005968 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00005969 // If the value is already zero, the branch will execute zero times.
Reid Spencer2e54a152007-03-02 00:28:52 +00005970 if (C->getValue()->isZero()) return C;
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005971 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00005972 }
5973
Dan Gohman48f82222009-05-04 22:30:44 +00005974 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Chris Lattnerd934c702004-04-02 20:23:17 +00005975 if (!AddRec || AddRec->getLoop() != L)
Dan Gohmanc5c85c02009-06-27 21:21:31 +00005976 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00005977
Chris Lattnerdff679f2011-01-09 22:39:48 +00005978 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
5979 // the quadratic equation to solve it.
5980 if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
5981 std::pair<const SCEV *,const SCEV *> Roots =
5982 SolveQuadraticEquation(AddRec, *this);
Dan Gohman48f82222009-05-04 22:30:44 +00005983 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
5984 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerdff679f2011-01-09 22:39:48 +00005985 if (R1 && R2) {
Chris Lattner09169212004-04-02 20:26:46 +00005986#if 0
David Greenedf1c4972009-12-23 22:18:14 +00005987 dbgs() << "HFTZ: " << *V << " - sol#1: " << *R1
Dan Gohmane20f8242009-04-21 00:47:46 +00005988 << " sol#2: " << *R2 << "\n";
Chris Lattner09169212004-04-02 20:26:46 +00005989#endif
Chris Lattnerd934c702004-04-02 20:23:17 +00005990 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00005991 if (ConstantInt *CB =
Chris Lattner28f140a2011-01-09 22:58:47 +00005992 dyn_cast<ConstantInt>(ConstantExpr::getICmp(CmpInst::ICMP_ULT,
5993 R1->getValue(),
5994 R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00005995 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00005996 std::swap(R1, R2); // R1 is the minimum root now.
Andrew Trick2a3b7162011-03-09 17:23:39 +00005997
Chris Lattnerd934c702004-04-02 20:23:17 +00005998 // We can only use this value if the chrec ends up with an exact zero
5999 // value at this index. When solving for "X*X != 5", for example, we
6000 // should not accept a root of 2.
Dan Gohmanaf752342009-07-07 17:06:11 +00006001 const SCEV *Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohmanbe928e32008-06-18 16:23:07 +00006002 if (Val->isZero())
6003 return R1; // We found a quadratic root!
Chris Lattnerd934c702004-04-02 20:23:17 +00006004 }
6005 }
Chris Lattnerdff679f2011-01-09 22:39:48 +00006006 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006007 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006008
Chris Lattnerdff679f2011-01-09 22:39:48 +00006009 // Otherwise we can only handle this if it is affine.
6010 if (!AddRec->isAffine())
6011 return getCouldNotCompute();
6012
6013 // If this is an affine expression, the execution count of this branch is
6014 // the minimum unsigned root of the following equation:
6015 //
6016 // Start + Step*N = 0 (mod 2^BW)
6017 //
6018 // equivalent to:
6019 //
6020 // Step*N = -Start (mod 2^BW)
6021 //
6022 // where BW is the common bit width of Start and Step.
6023
6024 // Get the initial value for the loop.
6025 const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
6026 const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
6027
6028 // For now we handle only constant steps.
Andrew Trick8b55b732011-03-14 16:50:06 +00006029 //
6030 // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
6031 // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
6032 // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
6033 // We have not yet seen any such cases.
Chris Lattnerdff679f2011-01-09 22:39:48 +00006034 const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
Craig Topper9f008862014-04-15 04:59:12 +00006035 if (!StepC || StepC->getValue()->equalsInt(0))
Chris Lattnerdff679f2011-01-09 22:39:48 +00006036 return getCouldNotCompute();
6037
Andrew Trick8b55b732011-03-14 16:50:06 +00006038 // For positive steps (counting up until unsigned overflow):
6039 // N = -Start/Step (as unsigned)
6040 // For negative steps (counting down to zero):
6041 // N = Start/-Step
6042 // First compute the unsigned distance from zero in the direction of Step.
Andrew Trickf1781db2011-03-14 17:28:02 +00006043 bool CountDown = StepC->getValue()->getValue().isNegative();
6044 const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
Andrew Trick8b55b732011-03-14 16:50:06 +00006045
6046 // Handle unitary steps, which cannot wraparound.
Andrew Trickf1781db2011-03-14 17:28:02 +00006047 // 1*N = -Start; -1*N = Start (mod 2^BW), so:
6048 // N = Distance (as unsigned)
Nick Lewycky31555522011-10-03 07:10:45 +00006049 if (StepC->getValue()->equalsInt(1) || StepC->getValue()->isAllOnesValue()) {
6050 ConstantRange CR = getUnsignedRange(Start);
6051 const SCEV *MaxBECount;
6052 if (!CountDown && CR.getUnsignedMin().isMinValue())
6053 // When counting up, the worst starting value is 1, not 0.
6054 MaxBECount = CR.getUnsignedMax().isMinValue()
6055 ? getConstant(APInt::getMinValue(CR.getBitWidth()))
6056 : getConstant(APInt::getMaxValue(CR.getBitWidth()));
6057 else
6058 MaxBECount = getConstant(CountDown ? CR.getUnsignedMax()
6059 : -CR.getUnsignedMin());
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006060 return ExitLimit(Distance, MaxBECount);
Nick Lewycky31555522011-10-03 07:10:45 +00006061 }
Andrew Trick2a3b7162011-03-09 17:23:39 +00006062
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006063 // If the step exactly divides the distance then unsigned divide computes the
6064 // backedge count.
6065 const SCEV *Q, *R;
6066 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
6067 SCEVDivision::divide(SE, Distance, Step, &Q, &R);
6068 if (R->isZero()) {
Andrew Trickee5aa7f2014-01-15 06:42:11 +00006069 const SCEV *Exact =
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006070 getUDivExactExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6071 return ExitLimit(Exact, Exact);
Andrew Trickee5aa7f2014-01-15 06:42:11 +00006072 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006073
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006074 // If the condition controls loop exit (the loop exits only if the expression
6075 // is true) and the addition is no-wrap we can use unsigned divide to
6076 // compute the backedge count. In this case, the step may not divide the
6077 // distance, but we don't care because if the condition is "missed" the loop
6078 // will have undefined behavior due to wrapping.
6079 if (ControlsExit && AddRec->getNoWrapFlags(SCEV::FlagNW)) {
6080 const SCEV *Exact =
6081 getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
6082 return ExitLimit(Exact, Exact);
6083 }
Benjamin Kramere75eaca2014-03-25 16:25:12 +00006084
Chris Lattnerdff679f2011-01-09 22:39:48 +00006085 // Then, try to solve the above equation provided that Start is constant.
6086 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
6087 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
6088 -StartC->getValue()->getValue(),
6089 *this);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006090 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006091}
6092
6093/// HowFarToNonZero - Return the number of times a backedge checking the
6094/// specified value for nonzero will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006095/// CouldNotCompute
Andrew Trick3ca3f982011-07-26 17:19:55 +00006096ScalarEvolution::ExitLimit
Dan Gohmanba820342010-02-24 17:31:30 +00006097ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Chris Lattnerd934c702004-04-02 20:23:17 +00006098 // Loops that look like: while (X == 0) are very strange indeed. We don't
6099 // handle them yet except for the trivial case. This could be expanded in the
6100 // future as needed.
Misha Brukman01808ca2005-04-21 21:13:18 +00006101
Chris Lattnerd934c702004-04-02 20:23:17 +00006102 // If the value is a constant, check to see if it is known to be non-zero
6103 // already. If so, the backedge will execute zero times.
Dan Gohmana30370b2009-05-04 22:02:23 +00006104 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewycky5a3db142008-02-21 09:14:53 +00006105 if (!C->getValue()->isNullValue())
Dan Gohman1d2ded72010-05-03 22:09:21 +00006106 return getConstant(C->getType(), 0);
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006107 return getCouldNotCompute(); // Otherwise it will loop infinitely.
Chris Lattnerd934c702004-04-02 20:23:17 +00006108 }
Misha Brukman01808ca2005-04-21 21:13:18 +00006109
Chris Lattnerd934c702004-04-02 20:23:17 +00006110 // We could implement others, but I really doubt anyone writes loops like
6111 // this, and if they did, they would already be constant folded.
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006112 return getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00006113}
6114
Dan Gohmanf9081a22008-09-15 22:18:04 +00006115/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
6116/// (which may not be an immediate predecessor) which has exactly one
6117/// successor from which BB is reachable, or null if no such block is
6118/// found.
6119///
Dan Gohman4e3c1132010-04-15 16:19:08 +00006120std::pair<BasicBlock *, BasicBlock *>
Dan Gohmanc8e23622009-04-21 23:15:49 +00006121ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohmanfa066ef2009-04-30 20:48:53 +00006122 // If the block has a unique predecessor, then there is no path from the
6123 // predecessor to the block that does not go through the direct edge
6124 // from the predecessor to the block.
Dan Gohmanf9081a22008-09-15 22:18:04 +00006125 if (BasicBlock *Pred = BB->getSinglePredecessor())
Dan Gohman4e3c1132010-04-15 16:19:08 +00006126 return std::make_pair(Pred, BB);
Dan Gohmanf9081a22008-09-15 22:18:04 +00006127
6128 // A loop's header is defined to be a block that dominates the loop.
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006129 // If the header has a unique predecessor outside the loop, it must be
6130 // a block that has exactly one successor that can reach the loop.
Dan Gohmanc8e23622009-04-21 23:15:49 +00006131 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006132 return std::make_pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohmanf9081a22008-09-15 22:18:04 +00006133
Dan Gohman4e3c1132010-04-15 16:19:08 +00006134 return std::pair<BasicBlock *, BasicBlock *>();
Dan Gohmanf9081a22008-09-15 22:18:04 +00006135}
6136
Dan Gohman450f4e02009-06-20 00:35:32 +00006137/// HasSameValue - SCEV structural equivalence is usually sufficient for
6138/// testing whether two expressions are equal, however for the purposes of
6139/// looking for a condition guarding a loop, it can be useful to be a little
6140/// more general, since a front-end may have replicated the controlling
6141/// expression.
6142///
Dan Gohmanaf752342009-07-07 17:06:11 +00006143static bool HasSameValue(const SCEV *A, const SCEV *B) {
Dan Gohman450f4e02009-06-20 00:35:32 +00006144 // Quick check to see if they are the same SCEV.
6145 if (A == B) return true;
6146
6147 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
6148 // two different instructions with the same value. Check for this case.
6149 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
6150 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
6151 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
6152 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
Dan Gohman2d085562009-08-25 17:56:57 +00006153 if (AI->isIdenticalTo(BI) && !AI->mayReadFromMemory())
Dan Gohman450f4e02009-06-20 00:35:32 +00006154 return true;
6155
6156 // Otherwise assume they may have a different value.
6157 return false;
6158}
6159
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006160/// SimplifyICmpOperands - Simplify LHS and RHS in a comparison with
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +00006161/// predicate Pred. Return true iff any changes were made.
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006162///
6163bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006164 const SCEV *&LHS, const SCEV *&RHS,
6165 unsigned Depth) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006166 bool Changed = false;
6167
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006168 // If we hit the max recursion limit bail out.
6169 if (Depth >= 3)
6170 return false;
6171
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006172 // Canonicalize a constant to the right side.
6173 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
6174 // Check for both operands constant.
6175 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
6176 if (ConstantExpr::getICmp(Pred,
6177 LHSC->getValue(),
6178 RHSC->getValue())->isNullValue())
6179 goto trivially_false;
6180 else
6181 goto trivially_true;
6182 }
6183 // Otherwise swap the operands to put the constant on the right.
6184 std::swap(LHS, RHS);
6185 Pred = ICmpInst::getSwappedPredicate(Pred);
6186 Changed = true;
6187 }
6188
6189 // If we're comparing an addrec with a value which is loop-invariant in the
Dan Gohmandf564ca2010-05-03 17:00:11 +00006190 // addrec's loop, put the addrec on the left. Also make a dominance check,
6191 // as both operands could be addrecs loop-invariant in each other's loop.
6192 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
6193 const Loop *L = AR->getLoop();
Dan Gohman20d9ce22010-11-17 21:41:58 +00006194 if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006195 std::swap(LHS, RHS);
6196 Pred = ICmpInst::getSwappedPredicate(Pred);
6197 Changed = true;
6198 }
Dan Gohmandf564ca2010-05-03 17:00:11 +00006199 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006200
6201 // If there's a constant operand, canonicalize comparisons with boundary
6202 // cases, and canonicalize *-or-equal comparisons to regular comparisons.
6203 if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
6204 const APInt &RA = RC->getValue()->getValue();
6205 switch (Pred) {
6206 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6207 case ICmpInst::ICMP_EQ:
6208 case ICmpInst::ICMP_NE:
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006209 // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
6210 if (!RA)
6211 if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
6212 if (const SCEVMulExpr *ME = dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
Benjamin Kramer406a2db2012-05-30 18:42:43 +00006213 if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
6214 ME->getOperand(0)->isAllOnesValue()) {
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006215 RHS = AE->getOperand(1);
6216 LHS = ME->getOperand(1);
6217 Changed = true;
6218 }
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006219 break;
6220 case ICmpInst::ICMP_UGE:
6221 if ((RA - 1).isMinValue()) {
6222 Pred = ICmpInst::ICMP_NE;
6223 RHS = getConstant(RA - 1);
6224 Changed = true;
6225 break;
6226 }
6227 if (RA.isMaxValue()) {
6228 Pred = ICmpInst::ICMP_EQ;
6229 Changed = true;
6230 break;
6231 }
6232 if (RA.isMinValue()) goto trivially_true;
6233
6234 Pred = ICmpInst::ICMP_UGT;
6235 RHS = getConstant(RA - 1);
6236 Changed = true;
6237 break;
6238 case ICmpInst::ICMP_ULE:
6239 if ((RA + 1).isMaxValue()) {
6240 Pred = ICmpInst::ICMP_NE;
6241 RHS = getConstant(RA + 1);
6242 Changed = true;
6243 break;
6244 }
6245 if (RA.isMinValue()) {
6246 Pred = ICmpInst::ICMP_EQ;
6247 Changed = true;
6248 break;
6249 }
6250 if (RA.isMaxValue()) goto trivially_true;
6251
6252 Pred = ICmpInst::ICMP_ULT;
6253 RHS = getConstant(RA + 1);
6254 Changed = true;
6255 break;
6256 case ICmpInst::ICMP_SGE:
6257 if ((RA - 1).isMinSignedValue()) {
6258 Pred = ICmpInst::ICMP_NE;
6259 RHS = getConstant(RA - 1);
6260 Changed = true;
6261 break;
6262 }
6263 if (RA.isMaxSignedValue()) {
6264 Pred = ICmpInst::ICMP_EQ;
6265 Changed = true;
6266 break;
6267 }
6268 if (RA.isMinSignedValue()) goto trivially_true;
6269
6270 Pred = ICmpInst::ICMP_SGT;
6271 RHS = getConstant(RA - 1);
6272 Changed = true;
6273 break;
6274 case ICmpInst::ICMP_SLE:
6275 if ((RA + 1).isMaxSignedValue()) {
6276 Pred = ICmpInst::ICMP_NE;
6277 RHS = getConstant(RA + 1);
6278 Changed = true;
6279 break;
6280 }
6281 if (RA.isMinSignedValue()) {
6282 Pred = ICmpInst::ICMP_EQ;
6283 Changed = true;
6284 break;
6285 }
6286 if (RA.isMaxSignedValue()) goto trivially_true;
6287
6288 Pred = ICmpInst::ICMP_SLT;
6289 RHS = getConstant(RA + 1);
6290 Changed = true;
6291 break;
6292 case ICmpInst::ICMP_UGT:
6293 if (RA.isMinValue()) {
6294 Pred = ICmpInst::ICMP_NE;
6295 Changed = true;
6296 break;
6297 }
6298 if ((RA + 1).isMaxValue()) {
6299 Pred = ICmpInst::ICMP_EQ;
6300 RHS = getConstant(RA + 1);
6301 Changed = true;
6302 break;
6303 }
6304 if (RA.isMaxValue()) goto trivially_false;
6305 break;
6306 case ICmpInst::ICMP_ULT:
6307 if (RA.isMaxValue()) {
6308 Pred = ICmpInst::ICMP_NE;
6309 Changed = true;
6310 break;
6311 }
6312 if ((RA - 1).isMinValue()) {
6313 Pred = ICmpInst::ICMP_EQ;
6314 RHS = getConstant(RA - 1);
6315 Changed = true;
6316 break;
6317 }
6318 if (RA.isMinValue()) goto trivially_false;
6319 break;
6320 case ICmpInst::ICMP_SGT:
6321 if (RA.isMinSignedValue()) {
6322 Pred = ICmpInst::ICMP_NE;
6323 Changed = true;
6324 break;
6325 }
6326 if ((RA + 1).isMaxSignedValue()) {
6327 Pred = ICmpInst::ICMP_EQ;
6328 RHS = getConstant(RA + 1);
6329 Changed = true;
6330 break;
6331 }
6332 if (RA.isMaxSignedValue()) goto trivially_false;
6333 break;
6334 case ICmpInst::ICMP_SLT:
6335 if (RA.isMaxSignedValue()) {
6336 Pred = ICmpInst::ICMP_NE;
6337 Changed = true;
6338 break;
6339 }
6340 if ((RA - 1).isMinSignedValue()) {
6341 Pred = ICmpInst::ICMP_EQ;
6342 RHS = getConstant(RA - 1);
6343 Changed = true;
6344 break;
6345 }
6346 if (RA.isMinSignedValue()) goto trivially_false;
6347 break;
6348 }
6349 }
6350
6351 // Check for obvious equality.
6352 if (HasSameValue(LHS, RHS)) {
6353 if (ICmpInst::isTrueWhenEqual(Pred))
6354 goto trivially_true;
6355 if (ICmpInst::isFalseWhenEqual(Pred))
6356 goto trivially_false;
6357 }
6358
Dan Gohman81585c12010-05-03 16:35:17 +00006359 // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
6360 // adding or subtracting 1 from one of the operands.
6361 switch (Pred) {
6362 case ICmpInst::ICMP_SLE:
6363 if (!getSignedRange(RHS).getSignedMax().isMaxSignedValue()) {
6364 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006365 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006366 Pred = ICmpInst::ICMP_SLT;
6367 Changed = true;
6368 } else if (!getSignedRange(LHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006369 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006370 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006371 Pred = ICmpInst::ICMP_SLT;
6372 Changed = true;
6373 }
6374 break;
6375 case ICmpInst::ICMP_SGE:
6376 if (!getSignedRange(RHS).getSignedMin().isMinSignedValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006377 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006378 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006379 Pred = ICmpInst::ICMP_SGT;
6380 Changed = true;
6381 } else if (!getSignedRange(LHS).getSignedMax().isMaxSignedValue()) {
6382 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006383 SCEV::FlagNSW);
Dan Gohman81585c12010-05-03 16:35:17 +00006384 Pred = ICmpInst::ICMP_SGT;
6385 Changed = true;
6386 }
6387 break;
6388 case ICmpInst::ICMP_ULE:
6389 if (!getUnsignedRange(RHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006390 RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006391 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006392 Pred = ICmpInst::ICMP_ULT;
6393 Changed = true;
6394 } else if (!getUnsignedRange(LHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006395 LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006396 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006397 Pred = ICmpInst::ICMP_ULT;
6398 Changed = true;
6399 }
6400 break;
6401 case ICmpInst::ICMP_UGE:
6402 if (!getUnsignedRange(RHS).getUnsignedMin().isMinValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006403 RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006404 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006405 Pred = ICmpInst::ICMP_UGT;
6406 Changed = true;
6407 } else if (!getUnsignedRange(LHS).getUnsignedMax().isMaxValue()) {
Dan Gohman267700c2010-05-03 20:23:47 +00006408 LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
Andrew Trick8b55b732011-03-14 16:50:06 +00006409 SCEV::FlagNUW);
Dan Gohman81585c12010-05-03 16:35:17 +00006410 Pred = ICmpInst::ICMP_UGT;
6411 Changed = true;
6412 }
6413 break;
6414 default:
6415 break;
6416 }
6417
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006418 // TODO: More simplifications are possible here.
6419
Benjamin Kramer50b26eb2012-05-30 18:32:23 +00006420 // Recursively simplify until we either hit a recursion limit or nothing
6421 // changes.
6422 if (Changed)
6423 return SimplifyICmpOperands(Pred, LHS, RHS, Depth+1);
6424
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006425 return Changed;
6426
6427trivially_true:
6428 // Return 0 == 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006429 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006430 Pred = ICmpInst::ICMP_EQ;
6431 return true;
6432
6433trivially_false:
6434 // Return 0 != 0.
Benjamin Kramerddd1b7b2010-11-20 18:43:35 +00006435 LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
Dan Gohman48ff3cf2010-04-24 01:28:42 +00006436 Pred = ICmpInst::ICMP_NE;
6437 return true;
6438}
6439
Dan Gohmane65c9172009-07-13 21:35:55 +00006440bool ScalarEvolution::isKnownNegative(const SCEV *S) {
6441 return getSignedRange(S).getSignedMax().isNegative();
6442}
6443
6444bool ScalarEvolution::isKnownPositive(const SCEV *S) {
6445 return getSignedRange(S).getSignedMin().isStrictlyPositive();
6446}
6447
6448bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
6449 return !getSignedRange(S).getSignedMin().isNegative();
6450}
6451
6452bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
6453 return !getSignedRange(S).getSignedMax().isStrictlyPositive();
6454}
6455
6456bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
6457 return isKnownNegative(S) || isKnownPositive(S);
6458}
6459
6460bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
6461 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman36cce7e2010-04-24 01:38:36 +00006462 // Canonicalize the inputs first.
6463 (void)SimplifyICmpOperands(Pred, LHS, RHS);
6464
Dan Gohman07591692010-04-11 22:16:48 +00006465 // If LHS or RHS is an addrec, check to see if the condition is true in
6466 // every iteration of the loop.
Justin Bognercbb84382014-05-23 00:06:56 +00006467 // If LHS and RHS are both addrec, both conditions must be true in
6468 // every iteration of the loop.
6469 const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
6470 const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
6471 bool LeftGuarded = false;
6472 bool RightGuarded = false;
6473 if (LAR) {
6474 const Loop *L = LAR->getLoop();
6475 if (isLoopEntryGuardedByCond(L, Pred, LAR->getStart(), RHS) &&
6476 isLoopBackedgeGuardedByCond(L, Pred, LAR->getPostIncExpr(*this), RHS)) {
6477 if (!RAR) return true;
6478 LeftGuarded = true;
6479 }
6480 }
6481 if (RAR) {
6482 const Loop *L = RAR->getLoop();
6483 if (isLoopEntryGuardedByCond(L, Pred, LHS, RAR->getStart()) &&
6484 isLoopBackedgeGuardedByCond(L, Pred, LHS, RAR->getPostIncExpr(*this))) {
6485 if (!LAR) return true;
6486 RightGuarded = true;
6487 }
6488 }
6489 if (LeftGuarded && RightGuarded)
6490 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00006491
Dan Gohman07591692010-04-11 22:16:48 +00006492 // Otherwise see what can be done with known constant ranges.
6493 return isKnownPredicateWithRanges(Pred, LHS, RHS);
6494}
6495
6496bool
6497ScalarEvolution::isKnownPredicateWithRanges(ICmpInst::Predicate Pred,
6498 const SCEV *LHS, const SCEV *RHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006499 if (HasSameValue(LHS, RHS))
6500 return ICmpInst::isTrueWhenEqual(Pred);
6501
Dan Gohman07591692010-04-11 22:16:48 +00006502 // This code is split out from isKnownPredicate because it is called from
6503 // within isLoopEntryGuardedByCond.
Dan Gohmane65c9172009-07-13 21:35:55 +00006504 switch (Pred) {
6505 default:
Dan Gohman8c129d72009-07-16 17:34:36 +00006506 llvm_unreachable("Unexpected ICmpInst::Predicate value!");
Dan Gohmane65c9172009-07-13 21:35:55 +00006507 case ICmpInst::ICMP_SGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00006508 std::swap(LHS, RHS);
6509 case ICmpInst::ICMP_SLT: {
6510 ConstantRange LHSRange = getSignedRange(LHS);
6511 ConstantRange RHSRange = getSignedRange(RHS);
6512 if (LHSRange.getSignedMax().slt(RHSRange.getSignedMin()))
6513 return true;
6514 if (LHSRange.getSignedMin().sge(RHSRange.getSignedMax()))
6515 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006516 break;
6517 }
6518 case ICmpInst::ICMP_SGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00006519 std::swap(LHS, RHS);
6520 case ICmpInst::ICMP_SLE: {
6521 ConstantRange LHSRange = getSignedRange(LHS);
6522 ConstantRange RHSRange = getSignedRange(RHS);
6523 if (LHSRange.getSignedMax().sle(RHSRange.getSignedMin()))
6524 return true;
6525 if (LHSRange.getSignedMin().sgt(RHSRange.getSignedMax()))
6526 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006527 break;
6528 }
6529 case ICmpInst::ICMP_UGT:
Dan Gohmane65c9172009-07-13 21:35:55 +00006530 std::swap(LHS, RHS);
6531 case ICmpInst::ICMP_ULT: {
6532 ConstantRange LHSRange = getUnsignedRange(LHS);
6533 ConstantRange RHSRange = getUnsignedRange(RHS);
6534 if (LHSRange.getUnsignedMax().ult(RHSRange.getUnsignedMin()))
6535 return true;
6536 if (LHSRange.getUnsignedMin().uge(RHSRange.getUnsignedMax()))
6537 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006538 break;
6539 }
6540 case ICmpInst::ICMP_UGE:
Dan Gohmane65c9172009-07-13 21:35:55 +00006541 std::swap(LHS, RHS);
6542 case ICmpInst::ICMP_ULE: {
6543 ConstantRange LHSRange = getUnsignedRange(LHS);
6544 ConstantRange RHSRange = getUnsignedRange(RHS);
6545 if (LHSRange.getUnsignedMax().ule(RHSRange.getUnsignedMin()))
6546 return true;
6547 if (LHSRange.getUnsignedMin().ugt(RHSRange.getUnsignedMax()))
6548 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006549 break;
6550 }
6551 case ICmpInst::ICMP_NE: {
6552 if (getUnsignedRange(LHS).intersectWith(getUnsignedRange(RHS)).isEmptySet())
6553 return true;
6554 if (getSignedRange(LHS).intersectWith(getSignedRange(RHS)).isEmptySet())
6555 return true;
6556
6557 const SCEV *Diff = getMinusSCEV(LHS, RHS);
6558 if (isKnownNonZero(Diff))
6559 return true;
6560 break;
6561 }
6562 case ICmpInst::ICMP_EQ:
Dan Gohman34392622009-07-20 23:54:43 +00006563 // The check at the top of the function catches the case where
6564 // the values are known to be equal.
Dan Gohmane65c9172009-07-13 21:35:55 +00006565 break;
6566 }
6567 return false;
6568}
6569
6570/// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
6571/// protected by a conditional between LHS and RHS. This is used to
6572/// to eliminate casts.
6573bool
6574ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
6575 ICmpInst::Predicate Pred,
6576 const SCEV *LHS, const SCEV *RHS) {
6577 // Interpret a null as meaning no loop, where there is obviously no guard
6578 // (interprocedural conditions notwithstanding).
6579 if (!L) return true;
6580
Sanjoy Das1f05c512014-10-10 21:22:34 +00006581 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6582
Dan Gohmane65c9172009-07-13 21:35:55 +00006583 BasicBlock *Latch = L->getLoopLatch();
6584 if (!Latch)
6585 return false;
6586
6587 BranchInst *LoopContinuePredicate =
6588 dyn_cast<BranchInst>(Latch->getTerminator());
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006589 if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
6590 isImpliedCond(Pred, LHS, RHS,
6591 LoopContinuePredicate->getCondition(),
6592 LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
6593 return true;
Dan Gohmane65c9172009-07-13 21:35:55 +00006594
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006595 // Check conditions due to any @llvm.assume intrinsics.
6596 for (auto &CI : AT->assumptions(F)) {
6597 if (!DT->dominates(CI, Latch->getTerminator()))
6598 continue;
6599
6600 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6601 return true;
6602 }
6603
6604 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006605}
6606
Dan Gohmanb50349a2010-04-11 19:27:13 +00006607/// isLoopEntryGuardedByCond - Test whether entry to the loop is protected
Dan Gohmane65c9172009-07-13 21:35:55 +00006608/// by a conditional between LHS and RHS. This is used to help avoid max
6609/// expressions in loop trip counts, and to eliminate casts.
6610bool
Dan Gohmanb50349a2010-04-11 19:27:13 +00006611ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
6612 ICmpInst::Predicate Pred,
6613 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman9cf09f82009-05-18 16:03:58 +00006614 // Interpret a null as meaning no loop, where there is obviously no guard
6615 // (interprocedural conditions notwithstanding).
6616 if (!L) return false;
6617
Sanjoy Das1f05c512014-10-10 21:22:34 +00006618 if (isKnownPredicateWithRanges(Pred, LHS, RHS)) return true;
6619
Dan Gohman8c77f1a2009-05-18 15:36:09 +00006620 // Starting at the loop predecessor, climb up the predecessor chain, as long
6621 // as there are predecessors that can be found that have unique successors
Dan Gohmanf9081a22008-09-15 22:18:04 +00006622 // leading to the original header.
Dan Gohman4e3c1132010-04-15 16:19:08 +00006623 for (std::pair<BasicBlock *, BasicBlock *>
Dan Gohman75c6b0b2010-06-22 23:43:28 +00006624 Pair(L->getLoopPredecessor(), L->getHeader());
Dan Gohman4e3c1132010-04-15 16:19:08 +00006625 Pair.first;
6626 Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
Dan Gohman2a62fd92008-08-12 20:17:31 +00006627
6628 BranchInst *LoopEntryPredicate =
Dan Gohman4e3c1132010-04-15 16:19:08 +00006629 dyn_cast<BranchInst>(Pair.first->getTerminator());
Dan Gohman2a62fd92008-08-12 20:17:31 +00006630 if (!LoopEntryPredicate ||
6631 LoopEntryPredicate->isUnconditional())
6632 continue;
6633
Dan Gohmane18c2d62010-08-10 23:46:30 +00006634 if (isImpliedCond(Pred, LHS, RHS,
6635 LoopEntryPredicate->getCondition(),
Dan Gohman4e3c1132010-04-15 16:19:08 +00006636 LoopEntryPredicate->getSuccessor(0) != Pair.second))
Dan Gohman2a62fd92008-08-12 20:17:31 +00006637 return true;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00006638 }
6639
Hal Finkelcebf0cc2014-09-07 21:37:59 +00006640 // Check conditions due to any @llvm.assume intrinsics.
6641 for (auto &CI : AT->assumptions(F)) {
6642 if (!DT->dominates(CI, L->getHeader()))
6643 continue;
6644
6645 if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
6646 return true;
6647 }
6648
Dan Gohman2a62fd92008-08-12 20:17:31 +00006649 return false;
Nick Lewyckyb5688cc2008-07-12 07:41:32 +00006650}
6651
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00006652/// RAII wrapper to prevent recursive application of isImpliedCond.
6653/// ScalarEvolution's PendingLoopPredicates set must be empty unless we are
6654/// currently evaluating isImpliedCond.
6655struct MarkPendingLoopPredicate {
6656 Value *Cond;
6657 DenseSet<Value*> &LoopPreds;
6658 bool Pending;
6659
6660 MarkPendingLoopPredicate(Value *C, DenseSet<Value*> &LP)
6661 : Cond(C), LoopPreds(LP) {
6662 Pending = !LoopPreds.insert(Cond).second;
6663 }
6664 ~MarkPendingLoopPredicate() {
6665 if (!Pending)
6666 LoopPreds.erase(Cond);
6667 }
6668};
6669
Dan Gohman430f0cc2009-07-21 23:03:19 +00006670/// isImpliedCond - Test whether the condition described by Pred, LHS,
6671/// and RHS is true whenever the given Cond value evaluates to true.
Dan Gohmane18c2d62010-08-10 23:46:30 +00006672bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006673 const SCEV *LHS, const SCEV *RHS,
Dan Gohmane18c2d62010-08-10 23:46:30 +00006674 Value *FoundCondValue,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006675 bool Inverse) {
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00006676 MarkPendingLoopPredicate Mark(FoundCondValue, PendingLoopPredicates);
6677 if (Mark.Pending)
6678 return false;
6679
Dan Gohman8b0a4192010-03-01 17:49:51 +00006680 // Recursively handle And and Or conditions.
Dan Gohmane18c2d62010-08-10 23:46:30 +00006681 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FoundCondValue)) {
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006682 if (BO->getOpcode() == Instruction::And) {
6683 if (!Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00006684 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6685 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006686 } else if (BO->getOpcode() == Instruction::Or) {
6687 if (Inverse)
Dan Gohmane18c2d62010-08-10 23:46:30 +00006688 return isImpliedCond(Pred, LHS, RHS, BO->getOperand(0), Inverse) ||
6689 isImpliedCond(Pred, LHS, RHS, BO->getOperand(1), Inverse);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006690 }
6691 }
6692
Dan Gohmane18c2d62010-08-10 23:46:30 +00006693 ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006694 if (!ICI) return false;
6695
Dan Gohmane65c9172009-07-13 21:35:55 +00006696 // Bail if the ICmp's operands' types are wider than the needed type
6697 // before attempting to call getSCEV on them. This avoids infinite
6698 // recursion, since the analysis of widening casts can require loop
6699 // exit condition information for overflow checking, which would
6700 // lead back here.
6701 if (getTypeSizeInBits(LHS->getType()) <
Dan Gohman430f0cc2009-07-21 23:03:19 +00006702 getTypeSizeInBits(ICI->getOperand(0)->getType()))
Dan Gohmane65c9172009-07-13 21:35:55 +00006703 return false;
6704
Andrew Trickfa594032012-11-29 18:35:13 +00006705 // Now that we found a conditional branch that dominates the loop or controls
6706 // the loop latch. Check to see if it is the comparison we are looking for.
Dan Gohman430f0cc2009-07-21 23:03:19 +00006707 ICmpInst::Predicate FoundPred;
6708 if (Inverse)
6709 FoundPred = ICI->getInversePredicate();
6710 else
6711 FoundPred = ICI->getPredicate();
6712
6713 const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
6714 const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
Dan Gohmane65c9172009-07-13 21:35:55 +00006715
6716 // Balance the types. The case where FoundLHS' type is wider than
6717 // LHS' type is checked for above.
6718 if (getTypeSizeInBits(LHS->getType()) >
6719 getTypeSizeInBits(FoundLHS->getType())) {
Stepan Dyatkovskiy431993b2014-01-09 12:26:12 +00006720 if (CmpInst::isSigned(FoundPred)) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006721 FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
6722 FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
6723 } else {
6724 FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
6725 FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
6726 }
6727 }
6728
Dan Gohman430f0cc2009-07-21 23:03:19 +00006729 // Canonicalize the query to match the way instcombine will have
6730 // canonicalized the comparison.
Dan Gohman3673aa12010-04-24 01:34:53 +00006731 if (SimplifyICmpOperands(Pred, LHS, RHS))
6732 if (LHS == RHS)
Dan Gohmanb5025c72010-05-03 18:00:24 +00006733 return CmpInst::isTrueWhenEqual(Pred);
Benjamin Kramerba11a982012-11-29 19:07:57 +00006734 if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
6735 if (FoundLHS == FoundRHS)
6736 return CmpInst::isFalseWhenEqual(FoundPred);
Dan Gohman430f0cc2009-07-21 23:03:19 +00006737
6738 // Check to see if we can make the LHS or RHS match.
6739 if (LHS == FoundRHS || RHS == FoundLHS) {
6740 if (isa<SCEVConstant>(RHS)) {
6741 std::swap(FoundLHS, FoundRHS);
6742 FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
6743 } else {
6744 std::swap(LHS, RHS);
6745 Pred = ICmpInst::getSwappedPredicate(Pred);
6746 }
6747 }
6748
6749 // Check whether the found predicate is the same as the desired predicate.
6750 if (FoundPred == Pred)
6751 return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS);
6752
6753 // Check whether swapping the found predicate makes it the same as the
6754 // desired predicate.
6755 if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
6756 if (isa<SCEVConstant>(RHS))
6757 return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS);
6758 else
6759 return isImpliedCondOperands(ICmpInst::getSwappedPredicate(Pred),
6760 RHS, LHS, FoundLHS, FoundRHS);
6761 }
6762
6763 // Check whether the actual condition is beyond sufficient.
6764 if (FoundPred == ICmpInst::ICMP_EQ)
6765 if (ICmpInst::isTrueWhenEqual(Pred))
6766 if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS))
6767 return true;
6768 if (Pred == ICmpInst::ICMP_NE)
6769 if (!ICmpInst::isTrueWhenEqual(FoundPred))
6770 if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS))
6771 return true;
6772
6773 // Otherwise assume the worst.
6774 return false;
Dan Gohmane65c9172009-07-13 21:35:55 +00006775}
6776
Dan Gohman430f0cc2009-07-21 23:03:19 +00006777/// isImpliedCondOperands - Test whether the condition described by Pred,
Dan Gohman8b0a4192010-03-01 17:49:51 +00006778/// LHS, and RHS is true whenever the condition described by Pred, FoundLHS,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006779/// and FoundRHS is true.
6780bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
6781 const SCEV *LHS, const SCEV *RHS,
6782 const SCEV *FoundLHS,
6783 const SCEV *FoundRHS) {
6784 return isImpliedCondOperandsHelper(Pred, LHS, RHS,
6785 FoundLHS, FoundRHS) ||
6786 // ~x < ~y --> x > y
6787 isImpliedCondOperandsHelper(Pred, LHS, RHS,
6788 getNotSCEV(FoundRHS),
6789 getNotSCEV(FoundLHS));
6790}
6791
6792/// isImpliedCondOperandsHelper - Test whether the condition described by
Dan Gohman8b0a4192010-03-01 17:49:51 +00006793/// Pred, LHS, and RHS is true whenever the condition described by Pred,
Dan Gohman430f0cc2009-07-21 23:03:19 +00006794/// FoundLHS, and FoundRHS is true.
Dan Gohmane65c9172009-07-13 21:35:55 +00006795bool
Dan Gohman430f0cc2009-07-21 23:03:19 +00006796ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
6797 const SCEV *LHS, const SCEV *RHS,
6798 const SCEV *FoundLHS,
6799 const SCEV *FoundRHS) {
Dan Gohmane65c9172009-07-13 21:35:55 +00006800 switch (Pred) {
Dan Gohman8c129d72009-07-16 17:34:36 +00006801 default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
6802 case ICmpInst::ICMP_EQ:
6803 case ICmpInst::ICMP_NE:
6804 if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
6805 return true;
6806 break;
Dan Gohmane65c9172009-07-13 21:35:55 +00006807 case ICmpInst::ICMP_SLT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006808 case ICmpInst::ICMP_SLE:
Dan Gohman07591692010-04-11 22:16:48 +00006809 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
6810 isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006811 return true;
6812 break;
6813 case ICmpInst::ICMP_SGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006814 case ICmpInst::ICMP_SGE:
Dan Gohman07591692010-04-11 22:16:48 +00006815 if (isKnownPredicateWithRanges(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
6816 isKnownPredicateWithRanges(ICmpInst::ICMP_SLE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006817 return true;
6818 break;
6819 case ICmpInst::ICMP_ULT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006820 case ICmpInst::ICMP_ULE:
Dan Gohman07591692010-04-11 22:16:48 +00006821 if (isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
6822 isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006823 return true;
6824 break;
6825 case ICmpInst::ICMP_UGT:
Dan Gohman8c129d72009-07-16 17:34:36 +00006826 case ICmpInst::ICMP_UGE:
Dan Gohman07591692010-04-11 22:16:48 +00006827 if (isKnownPredicateWithRanges(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
6828 isKnownPredicateWithRanges(ICmpInst::ICMP_ULE, RHS, FoundRHS))
Dan Gohmane65c9172009-07-13 21:35:55 +00006829 return true;
6830 break;
6831 }
6832
6833 return false;
Dan Gohmanf19aeec2009-06-24 01:18:18 +00006834}
6835
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006836// Verify if an linear IV with positive stride can overflow when in a
6837// less-than comparison, knowing the invariant term of the comparison, the
6838// stride and the knowledge of NSW/NUW flags on the recurrence.
6839bool ScalarEvolution::doesIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
6840 bool IsSigned, bool NoWrap) {
6841 if (NoWrap) return false;
Dan Gohman51aaf022010-01-26 04:40:18 +00006842
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006843 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6844 const SCEV *One = getConstant(Stride->getType(), 1);
Andrew Trick2afa3252011-03-09 17:29:58 +00006845
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006846 if (IsSigned) {
6847 APInt MaxRHS = getSignedRange(RHS).getSignedMax();
6848 APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
6849 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6850 .getSignedMax();
Andrew Trick2afa3252011-03-09 17:29:58 +00006851
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006852 // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
6853 return (MaxValue - MaxStrideMinusOne).slt(MaxRHS);
Dan Gohman36bad002009-09-17 18:05:20 +00006854 }
Dan Gohman01048422009-06-21 23:46:38 +00006855
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006856 APInt MaxRHS = getUnsignedRange(RHS).getUnsignedMax();
6857 APInt MaxValue = APInt::getMaxValue(BitWidth);
6858 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6859 .getUnsignedMax();
6860
6861 // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
6862 return (MaxValue - MaxStrideMinusOne).ult(MaxRHS);
6863}
6864
6865// Verify if an linear IV with negative stride can overflow when in a
6866// greater-than comparison, knowing the invariant term of the comparison,
6867// the stride and the knowledge of NSW/NUW flags on the recurrence.
6868bool ScalarEvolution::doesIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
6869 bool IsSigned, bool NoWrap) {
6870 if (NoWrap) return false;
6871
6872 unsigned BitWidth = getTypeSizeInBits(RHS->getType());
6873 const SCEV *One = getConstant(Stride->getType(), 1);
6874
6875 if (IsSigned) {
6876 APInt MinRHS = getSignedRange(RHS).getSignedMin();
6877 APInt MinValue = APInt::getSignedMinValue(BitWidth);
6878 APInt MaxStrideMinusOne = getSignedRange(getMinusSCEV(Stride, One))
6879 .getSignedMax();
6880
6881 // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
6882 return (MinValue + MaxStrideMinusOne).sgt(MinRHS);
6883 }
6884
6885 APInt MinRHS = getUnsignedRange(RHS).getUnsignedMin();
6886 APInt MinValue = APInt::getMinValue(BitWidth);
6887 APInt MaxStrideMinusOne = getUnsignedRange(getMinusSCEV(Stride, One))
6888 .getUnsignedMax();
6889
6890 // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
6891 return (MinValue + MaxStrideMinusOne).ugt(MinRHS);
6892}
6893
6894// Compute the backedge taken count knowing the interval difference, the
6895// stride and presence of the equality in the comparison.
6896const SCEV *ScalarEvolution::computeBECount(const SCEV *Delta, const SCEV *Step,
6897 bool Equality) {
6898 const SCEV *One = getConstant(Step->getType(), 1);
6899 Delta = Equality ? getAddExpr(Delta, Step)
6900 : getAddExpr(Delta, getMinusSCEV(Step, One));
6901 return getUDivExpr(Delta, Step);
Dan Gohman01048422009-06-21 23:46:38 +00006902}
6903
Chris Lattner587a75b2005-08-15 23:33:51 +00006904/// HowManyLessThans - Return the number of times a backedge containing the
6905/// specified less-than comparison will execute. If not computable, return
Dan Gohman4c720c02009-06-06 14:37:11 +00006906/// CouldNotCompute.
Andrew Trick5b245a12013-05-31 06:43:25 +00006907///
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006908/// @param ControlsExit is true when the LHS < RHS condition directly controls
6909/// the branch (loops exits only if condition is true). In this case, we can use
6910/// NoWrapFlags to skip overflow checks.
Andrew Trick3ca3f982011-07-26 17:19:55 +00006911ScalarEvolution::ExitLimit
Dan Gohmance973df2009-06-24 04:48:43 +00006912ScalarEvolution::HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006913 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006914 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006915 // We handle only IV < Invariant
6916 if (!isLoopInvariant(RHS, L))
Dan Gohmanc5c85c02009-06-27 21:21:31 +00006917 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00006918
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006919 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohman2b8da352009-04-30 20:47:05 +00006920
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006921 // Avoid weird loops
6922 if (!IV || IV->getLoop() != L || !IV->isAffine())
6923 return getCouldNotCompute();
Chris Lattner587a75b2005-08-15 23:33:51 +00006924
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006925 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006926 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00006927
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006928 const SCEV *Stride = IV->getStepRecurrence(*this);
Wojciech Matyjewicz35545fd2008-02-13 11:51:34 +00006929
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006930 // Avoid negative or zero stride values
6931 if (!isKnownPositive(Stride))
6932 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00006933
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006934 // Avoid proven overflow cases: this will ensure that the backedge taken count
6935 // will not generate any unsigned overflow. Relaxed no-overflow conditions
6936 // exploit NoWrapFlags, allowing to optimize in presence of undefined
6937 // behaviors like the case of C language.
6938 if (!Stride->isOne() && doesIVOverflowOnLT(RHS, Stride, IsSigned, NoWrap))
6939 return getCouldNotCompute();
Dan Gohman2b8da352009-04-30 20:47:05 +00006940
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006941 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT
6942 : ICmpInst::ICMP_ULT;
6943 const SCEV *Start = IV->getStart();
6944 const SCEV *End = RHS;
6945 if (!isLoopEntryGuardedByCond(L, Cond, getMinusSCEV(Start, Stride), RHS))
6946 End = IsSigned ? getSMaxExpr(RHS, Start)
6947 : getUMaxExpr(RHS, Start);
Dan Gohman51aaf022010-01-26 04:40:18 +00006948
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006949 const SCEV *BECount = computeBECount(getMinusSCEV(End, Start), Stride, false);
Dan Gohman2b8da352009-04-30 20:47:05 +00006950
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006951 APInt MinStart = IsSigned ? getSignedRange(Start).getSignedMin()
6952 : getUnsignedRange(Start).getUnsignedMin();
Andrew Trick2afa3252011-03-09 17:29:58 +00006953
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006954 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
6955 : getUnsignedRange(Stride).getUnsignedMin();
Dan Gohman2b8da352009-04-30 20:47:05 +00006956
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006957 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
6958 APInt Limit = IsSigned ? APInt::getSignedMaxValue(BitWidth) - (MinStride - 1)
6959 : APInt::getMaxValue(BitWidth) - (MinStride - 1);
Chris Lattner587a75b2005-08-15 23:33:51 +00006960
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006961 // Although End can be a MAX expression we estimate MaxEnd considering only
6962 // the case End = RHS. This is safe because in the other case (End - Start)
6963 // is zero, leading to a zero maximum backedge taken count.
6964 APInt MaxEnd =
6965 IsSigned ? APIntOps::smin(getSignedRange(RHS).getSignedMax(), Limit)
6966 : APIntOps::umin(getUnsignedRange(RHS).getUnsignedMax(), Limit);
6967
Arnaud A. de Grandmaison75c9e6d2014-03-15 22:13:15 +00006968 const SCEV *MaxBECount;
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006969 if (isa<SCEVConstant>(BECount))
6970 MaxBECount = BECount;
6971 else
6972 MaxBECount = computeBECount(getConstant(MaxEnd - MinStart),
6973 getConstant(MinStride), false);
6974
6975 if (isa<SCEVCouldNotCompute>(MaxBECount))
6976 MaxBECount = BECount;
6977
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006978 return ExitLimit(BECount, MaxBECount);
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006979}
6980
6981ScalarEvolution::ExitLimit
6982ScalarEvolution::HowManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
6983 const Loop *L, bool IsSigned,
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006984 bool ControlsExit) {
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006985 // We handle only IV > Invariant
6986 if (!isLoopInvariant(RHS, L))
6987 return getCouldNotCompute();
6988
6989 const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
6990
6991 // Avoid weird loops
6992 if (!IV || IV->getLoop() != L || !IV->isAffine())
6993 return getCouldNotCompute();
6994
Mark Heffernan2beab5f2014-10-10 17:39:11 +00006995 bool NoWrap = ControlsExit &&
Andrew Trick34e2f0c2013-11-06 02:08:26 +00006996 IV->getNoWrapFlags(IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW);
6997
6998 const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
6999
7000 // Avoid negative or zero stride values
7001 if (!isKnownPositive(Stride))
7002 return getCouldNotCompute();
7003
7004 // Avoid proven overflow cases: this will ensure that the backedge taken count
7005 // will not generate any unsigned overflow. Relaxed no-overflow conditions
7006 // exploit NoWrapFlags, allowing to optimize in presence of undefined
7007 // behaviors like the case of C language.
7008 if (!Stride->isOne() && doesIVOverflowOnGT(RHS, Stride, IsSigned, NoWrap))
7009 return getCouldNotCompute();
7010
7011 ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT
7012 : ICmpInst::ICMP_UGT;
7013
7014 const SCEV *Start = IV->getStart();
7015 const SCEV *End = RHS;
7016 if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS))
7017 End = IsSigned ? getSMinExpr(RHS, Start)
7018 : getUMinExpr(RHS, Start);
7019
7020 const SCEV *BECount = computeBECount(getMinusSCEV(Start, End), Stride, false);
7021
7022 APInt MaxStart = IsSigned ? getSignedRange(Start).getSignedMax()
7023 : getUnsignedRange(Start).getUnsignedMax();
7024
7025 APInt MinStride = IsSigned ? getSignedRange(Stride).getSignedMin()
7026 : getUnsignedRange(Stride).getUnsignedMin();
7027
7028 unsigned BitWidth = getTypeSizeInBits(LHS->getType());
7029 APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
7030 : APInt::getMinValue(BitWidth) + (MinStride - 1);
7031
7032 // Although End can be a MIN expression we estimate MinEnd considering only
7033 // the case End = RHS. This is safe because in the other case (Start - End)
7034 // is zero, leading to a zero maximum backedge taken count.
7035 APInt MinEnd =
7036 IsSigned ? APIntOps::smax(getSignedRange(RHS).getSignedMin(), Limit)
7037 : APIntOps::umax(getUnsignedRange(RHS).getUnsignedMin(), Limit);
7038
7039
7040 const SCEV *MaxBECount = getCouldNotCompute();
7041 if (isa<SCEVConstant>(BECount))
7042 MaxBECount = BECount;
7043 else
7044 MaxBECount = computeBECount(getConstant(MaxStart - MinEnd),
7045 getConstant(MinStride), false);
7046
7047 if (isa<SCEVCouldNotCompute>(MaxBECount))
7048 MaxBECount = BECount;
7049
Mark Heffernan2beab5f2014-10-10 17:39:11 +00007050 return ExitLimit(BECount, MaxBECount);
Chris Lattner587a75b2005-08-15 23:33:51 +00007051}
7052
Chris Lattnerd934c702004-04-02 20:23:17 +00007053/// getNumIterationsInRange - Return the number of iterations of this loop that
7054/// produce values in the specified constant range. Another way of looking at
7055/// this is that it returns the first iteration number where the value is not in
7056/// the condition, thus computing the exit count. If the iteration count can't
7057/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohmanaf752342009-07-07 17:06:11 +00007058const SCEV *SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohmance973df2009-06-24 04:48:43 +00007059 ScalarEvolution &SE) const {
Chris Lattnerd934c702004-04-02 20:23:17 +00007060 if (Range.isFullSet()) // Infinite loop.
Dan Gohman31efa302009-04-18 17:58:19 +00007061 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007062
7063 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmana30370b2009-05-04 22:02:23 +00007064 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencer2e54a152007-03-02 00:28:52 +00007065 if (!SC->getValue()->isZero()) {
Dan Gohmanaf752342009-07-07 17:06:11 +00007066 SmallVector<const SCEV *, 4> Operands(op_begin(), op_end());
Dan Gohman1d2ded72010-05-03 22:09:21 +00007067 Operands[0] = SE.getConstant(SC->getType(), 0);
Andrew Trick8b55b732011-03-14 16:50:06 +00007068 const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
Andrew Trickf6b01ff2011-03-15 00:37:00 +00007069 getNoWrapFlags(FlagNW));
Dan Gohmana30370b2009-05-04 22:02:23 +00007070 if (const SCEVAddRecExpr *ShiftedAddRec =
7071 dyn_cast<SCEVAddRecExpr>(Shifted))
Chris Lattnerd934c702004-04-02 20:23:17 +00007072 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohmana37eaf22007-10-22 18:31:58 +00007073 Range.subtract(SC->getValue()->getValue()), SE);
Chris Lattnerd934c702004-04-02 20:23:17 +00007074 // This is strange and shouldn't happen.
Dan Gohman31efa302009-04-18 17:58:19 +00007075 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007076 }
7077
7078 // The only time we can solve this is when we have all constant indices.
7079 // Otherwise, we cannot determine the overflow conditions.
7080 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
7081 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman31efa302009-04-18 17:58:19 +00007082 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007083
7084
7085 // Okay at this point we know that all elements of the chrec are constants and
7086 // that the start element is zero.
7087
7088 // First check to see if the range contains zero. If not, the first
7089 // iteration exits.
Dan Gohmanb397e1a2009-04-21 01:07:12 +00007090 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman0a40ad92009-04-16 03:18:22 +00007091 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman1d2ded72010-05-03 22:09:21 +00007092 return SE.getConstant(getType(), 0);
Misha Brukman01808ca2005-04-21 21:13:18 +00007093
Chris Lattnerd934c702004-04-02 20:23:17 +00007094 if (isAffine()) {
7095 // If this is an affine expression then we have this situation:
7096 // Solve {0,+,A} in Range === Ax in Range
7097
Nick Lewycky52460262007-07-16 02:08:00 +00007098 // We know that zero is in the range. If A is positive then we know that
7099 // the upper value of the range must be the first possible exit value.
7100 // If A is negative then the lower of the range is the last possible loop
7101 // value. Also note that we already checked for a full range.
Dan Gohman0a40ad92009-04-16 03:18:22 +00007102 APInt One(BitWidth,1);
Nick Lewycky52460262007-07-16 02:08:00 +00007103 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
7104 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattnerd934c702004-04-02 20:23:17 +00007105
Nick Lewycky52460262007-07-16 02:08:00 +00007106 // The exit value should be (End+A)/A.
Nick Lewycky39349612007-09-27 14:12:54 +00007107 APInt ExitVal = (End + A).udiv(A);
Owen Andersonedb4a702009-07-24 23:12:02 +00007108 ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
Chris Lattnerd934c702004-04-02 20:23:17 +00007109
7110 // Evaluate at the exit value. If we really did fall out of the valid
7111 // range, then we computed our trip count, otherwise wrap around or other
7112 // things must have happened.
Dan Gohmana37eaf22007-10-22 18:31:58 +00007113 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007114 if (Range.contains(Val->getValue()))
Dan Gohman31efa302009-04-18 17:58:19 +00007115 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007116
7117 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer3a7e9d82007-02-28 19:57:34 +00007118 assert(Range.contains(
Dan Gohmance973df2009-06-24 04:48:43 +00007119 EvaluateConstantChrecAtConstant(this,
Owen Andersonedb4a702009-07-24 23:12:02 +00007120 ConstantInt::get(SE.getContext(), ExitVal - One), SE)->getValue()) &&
Chris Lattnerd934c702004-04-02 20:23:17 +00007121 "Linear scev computation is off in a bad way!");
Dan Gohmana37eaf22007-10-22 18:31:58 +00007122 return SE.getConstant(ExitValue);
Chris Lattnerd934c702004-04-02 20:23:17 +00007123 } else if (isQuadratic()) {
7124 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
7125 // quadratic equation to solve it. To do this, we must frame our problem in
7126 // terms of figuring out when zero is crossed, instead of when
7127 // Range.getUpper() is crossed.
Dan Gohmanaf752342009-07-07 17:06:11 +00007128 SmallVector<const SCEV *, 4> NewOps(op_begin(), op_end());
Dan Gohmana37eaf22007-10-22 18:31:58 +00007129 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Andrew Trick8b55b732011-03-14 16:50:06 +00007130 const SCEV *NewAddRec = SE.getAddRecExpr(NewOps, getLoop(),
7131 // getNoWrapFlags(FlagNW)
7132 FlagAnyWrap);
Chris Lattnerd934c702004-04-02 20:23:17 +00007133
7134 // Next, solve the constructed addrec
Dan Gohmanaf752342009-07-07 17:06:11 +00007135 std::pair<const SCEV *,const SCEV *> Roots =
Dan Gohmana37eaf22007-10-22 18:31:58 +00007136 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohman48f82222009-05-04 22:30:44 +00007137 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
7138 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Chris Lattnerd934c702004-04-02 20:23:17 +00007139 if (R1) {
7140 // Pick the smallest positive root value.
Zhou Sheng75b871f2007-01-11 12:24:14 +00007141 if (ConstantInt *CB =
Owen Anderson487375e2009-07-29 18:55:55 +00007142 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Owen Andersonf1f17432009-07-06 22:37:39 +00007143 R1->getValue(), R2->getValue()))) {
Reid Spencercddc9df2007-01-12 04:24:46 +00007144 if (CB->getZExtValue() == false)
Chris Lattnerd934c702004-04-02 20:23:17 +00007145 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman01808ca2005-04-21 21:13:18 +00007146
Chris Lattnerd934c702004-04-02 20:23:17 +00007147 // Make sure the root is not off by one. The returned iteration should
7148 // not be in the range, but the previous one should be. When solving
7149 // for "X*X < 5", for example, we should not return a root of 2.
7150 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohmana37eaf22007-10-22 18:31:58 +00007151 R1->getValue(),
7152 SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007153 if (Range.contains(R1Val->getValue())) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007154 // The next iteration must be out of the range...
Owen Andersonf1f17432009-07-06 22:37:39 +00007155 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00007156 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()+1);
Misha Brukman01808ca2005-04-21 21:13:18 +00007157
Dan Gohmana37eaf22007-10-22 18:31:58 +00007158 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007159 if (!Range.contains(R1Val->getValue()))
Dan Gohmana37eaf22007-10-22 18:31:58 +00007160 return SE.getConstant(NextVal);
Dan Gohman31efa302009-04-18 17:58:19 +00007161 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007162 }
Misha Brukman01808ca2005-04-21 21:13:18 +00007163
Chris Lattnerd934c702004-04-02 20:23:17 +00007164 // If R1 was not in the range, then it is a good return value. Make
7165 // sure that R1-1 WAS in the range though, just in case.
Owen Andersonf1f17432009-07-06 22:37:39 +00007166 ConstantInt *NextVal =
Owen Andersonedb4a702009-07-24 23:12:02 +00007167 ConstantInt::get(SE.getContext(), R1->getValue()->getValue()-1);
Dan Gohmana37eaf22007-10-22 18:31:58 +00007168 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Reid Spencer6a440332007-03-01 07:54:15 +00007169 if (Range.contains(R1Val->getValue()))
Chris Lattnerd934c702004-04-02 20:23:17 +00007170 return R1;
Dan Gohman31efa302009-04-18 17:58:19 +00007171 return SE.getCouldNotCompute(); // Something strange happened
Chris Lattnerd934c702004-04-02 20:23:17 +00007172 }
7173 }
7174 }
7175
Dan Gohman31efa302009-04-18 17:58:19 +00007176 return SE.getCouldNotCompute();
Chris Lattnerd934c702004-04-02 20:23:17 +00007177}
7178
Sebastian Pop448712b2014-05-07 18:01:20 +00007179namespace {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00007180struct FindUndefs {
7181 bool Found;
7182 FindUndefs() : Found(false) {}
7183
7184 bool follow(const SCEV *S) {
7185 if (const SCEVUnknown *C = dyn_cast<SCEVUnknown>(S)) {
7186 if (isa<UndefValue>(C->getValue()))
7187 Found = true;
7188 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
7189 if (isa<UndefValue>(C->getValue()))
7190 Found = true;
7191 }
7192
7193 // Keep looking if we haven't found it yet.
7194 return !Found;
7195 }
7196 bool isDone() const {
7197 // Stop recursion if we have found an undef.
7198 return Found;
7199 }
7200};
7201}
7202
7203// Return true when S contains at least an undef value.
7204static inline bool
7205containsUndefs(const SCEV *S) {
7206 FindUndefs F;
7207 SCEVTraversal<FindUndefs> ST(F);
7208 ST.visitAll(S);
7209
7210 return F.Found;
7211}
7212
7213namespace {
Sebastian Pop448712b2014-05-07 18:01:20 +00007214// Collect all steps of SCEV expressions.
7215struct SCEVCollectStrides {
7216 ScalarEvolution &SE;
7217 SmallVectorImpl<const SCEV *> &Strides;
7218
7219 SCEVCollectStrides(ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &S)
7220 : SE(SE), Strides(S) {}
7221
7222 bool follow(const SCEV *S) {
7223 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
7224 Strides.push_back(AR->getStepRecurrence(SE));
7225 return true;
7226 }
7227 bool isDone() const { return false; }
7228};
7229
7230// Collect all SCEVUnknown and SCEVMulExpr expressions.
7231struct SCEVCollectTerms {
7232 SmallVectorImpl<const SCEV *> &Terms;
7233
7234 SCEVCollectTerms(SmallVectorImpl<const SCEV *> &T)
7235 : Terms(T) {}
7236
7237 bool follow(const SCEV *S) {
Sebastian Popa6e58602014-05-27 22:41:45 +00007238 if (isa<SCEVUnknown>(S) || isa<SCEVMulExpr>(S)) {
Sebastian Popa7d3d6a2014-05-07 19:00:32 +00007239 if (!containsUndefs(S))
7240 Terms.push_back(S);
Sebastian Pop448712b2014-05-07 18:01:20 +00007241
7242 // Stop recursion: once we collected a term, do not walk its operands.
7243 return false;
7244 }
7245
7246 // Keep looking.
7247 return true;
7248 }
7249 bool isDone() const { return false; }
7250};
7251}
7252
7253/// Find parametric terms in this SCEVAddRecExpr.
7254void SCEVAddRecExpr::collectParametricTerms(
7255 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Terms) const {
7256 SmallVector<const SCEV *, 4> Strides;
7257 SCEVCollectStrides StrideCollector(SE, Strides);
7258 visitAll(this, StrideCollector);
7259
7260 DEBUG({
7261 dbgs() << "Strides:\n";
7262 for (const SCEV *S : Strides)
7263 dbgs() << *S << "\n";
7264 });
7265
7266 for (const SCEV *S : Strides) {
7267 SCEVCollectTerms TermCollector(Terms);
7268 visitAll(S, TermCollector);
7269 }
7270
7271 DEBUG({
7272 dbgs() << "Terms:\n";
7273 for (const SCEV *T : Terms)
7274 dbgs() << *T << "\n";
7275 });
7276}
7277
Sebastian Popb1a548f2014-05-12 19:01:53 +00007278static bool findArrayDimensionsRec(ScalarEvolution &SE,
Sebastian Pop448712b2014-05-07 18:01:20 +00007279 SmallVectorImpl<const SCEV *> &Terms,
Sebastian Pop47fe7de2014-05-09 22:45:07 +00007280 SmallVectorImpl<const SCEV *> &Sizes) {
Sebastian Pope30bd352014-05-27 22:41:56 +00007281 int Last = Terms.size() - 1;
7282 const SCEV *Step = Terms[Last];
Sebastian Popc62c6792013-11-12 22:47:20 +00007283
Sebastian Pop448712b2014-05-07 18:01:20 +00007284 // End of recursion.
Sebastian Pope30bd352014-05-27 22:41:56 +00007285 if (Last == 0) {
7286 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Step)) {
Sebastian Pop448712b2014-05-07 18:01:20 +00007287 SmallVector<const SCEV *, 2> Qs;
7288 for (const SCEV *Op : M->operands())
7289 if (!isa<SCEVConstant>(Op))
7290 Qs.push_back(Op);
Sebastian Popc62c6792013-11-12 22:47:20 +00007291
Sebastian Pope30bd352014-05-27 22:41:56 +00007292 Step = SE.getMulExpr(Qs);
Sebastian Popc62c6792013-11-12 22:47:20 +00007293 }
7294
Sebastian Pope30bd352014-05-27 22:41:56 +00007295 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007296 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00007297 }
7298
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00007299 for (const SCEV *&Term : Terms) {
Sebastian Pop448712b2014-05-07 18:01:20 +00007300 // Normalize the terms before the next call to findArrayDimensionsRec.
7301 const SCEV *Q, *R;
Sebastian Pope30bd352014-05-27 22:41:56 +00007302 SCEVDivision::divide(SE, Term, Step, &Q, &R);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007303
7304 // Bail out when GCD does not evenly divide one of the terms.
7305 if (!R->isZero())
7306 return false;
7307
Benjamin Kramer8cff45a2014-05-10 17:47:18 +00007308 Term = Q;
Sebastian Popc62c6792013-11-12 22:47:20 +00007309 }
7310
Tobias Grosser3080cf12014-05-08 07:55:34 +00007311 // Remove all SCEVConstants.
Tobias Grosser1e9db7e2014-05-08 21:43:19 +00007312 Terms.erase(std::remove_if(Terms.begin(), Terms.end(), [](const SCEV *E) {
7313 return isa<SCEVConstant>(E);
7314 }),
7315 Terms.end());
Sebastian Popc62c6792013-11-12 22:47:20 +00007316
Sebastian Pop448712b2014-05-07 18:01:20 +00007317 if (Terms.size() > 0)
Sebastian Popb1a548f2014-05-12 19:01:53 +00007318 if (!findArrayDimensionsRec(SE, Terms, Sizes))
7319 return false;
7320
Sebastian Pope30bd352014-05-27 22:41:56 +00007321 Sizes.push_back(Step);
Sebastian Popb1a548f2014-05-12 19:01:53 +00007322 return true;
Sebastian Pop448712b2014-05-07 18:01:20 +00007323}
Sebastian Popc62c6792013-11-12 22:47:20 +00007324
Sebastian Pop448712b2014-05-07 18:01:20 +00007325namespace {
7326struct FindParameter {
7327 bool FoundParameter;
7328 FindParameter() : FoundParameter(false) {}
Sebastian Popc62c6792013-11-12 22:47:20 +00007329
Sebastian Pop448712b2014-05-07 18:01:20 +00007330 bool follow(const SCEV *S) {
7331 if (isa<SCEVUnknown>(S)) {
7332 FoundParameter = true;
7333 // Stop recursion: we found a parameter.
7334 return false;
7335 }
7336 // Keep looking.
7337 return true;
Sebastian Popc62c6792013-11-12 22:47:20 +00007338 }
Sebastian Pop448712b2014-05-07 18:01:20 +00007339 bool isDone() const {
7340 // Stop recursion if we have found a parameter.
7341 return FoundParameter;
Sebastian Popc62c6792013-11-12 22:47:20 +00007342 }
Sebastian Popc62c6792013-11-12 22:47:20 +00007343};
7344}
7345
Sebastian Pop448712b2014-05-07 18:01:20 +00007346// Returns true when S contains at least a SCEVUnknown parameter.
7347static inline bool
7348containsParameters(const SCEV *S) {
7349 FindParameter F;
7350 SCEVTraversal<FindParameter> ST(F);
7351 ST.visitAll(S);
7352
7353 return F.FoundParameter;
7354}
7355
7356// Returns true when one of the SCEVs of Terms contains a SCEVUnknown parameter.
7357static inline bool
7358containsParameters(SmallVectorImpl<const SCEV *> &Terms) {
7359 for (const SCEV *T : Terms)
7360 if (containsParameters(T))
7361 return true;
7362 return false;
7363}
7364
7365// Return the number of product terms in S.
7366static inline int numberOfTerms(const SCEV *S) {
7367 if (const SCEVMulExpr *Expr = dyn_cast<SCEVMulExpr>(S))
7368 return Expr->getNumOperands();
7369 return 1;
7370}
7371
Sebastian Popa6e58602014-05-27 22:41:45 +00007372static const SCEV *removeConstantFactors(ScalarEvolution &SE, const SCEV *T) {
7373 if (isa<SCEVConstant>(T))
7374 return nullptr;
7375
7376 if (isa<SCEVUnknown>(T))
7377 return T;
7378
7379 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(T)) {
7380 SmallVector<const SCEV *, 2> Factors;
7381 for (const SCEV *Op : M->operands())
7382 if (!isa<SCEVConstant>(Op))
7383 Factors.push_back(Op);
7384
7385 return SE.getMulExpr(Factors);
7386 }
7387
7388 return T;
7389}
7390
7391/// Return the size of an element read or written by Inst.
7392const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
7393 Type *Ty;
7394 if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
7395 Ty = Store->getValueOperand()->getType();
7396 else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
Tobias Grosser40ac1002014-06-08 19:21:20 +00007397 Ty = Load->getType();
Sebastian Popa6e58602014-05-27 22:41:45 +00007398 else
7399 return nullptr;
7400
7401 Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
7402 return getSizeOfExpr(ETy, Ty);
7403}
7404
Sebastian Pop448712b2014-05-07 18:01:20 +00007405/// Second step of delinearization: compute the array dimensions Sizes from the
7406/// set of Terms extracted from the memory access function of this SCEVAddRec.
Sebastian Popa6e58602014-05-27 22:41:45 +00007407void ScalarEvolution::findArrayDimensions(SmallVectorImpl<const SCEV *> &Terms,
7408 SmallVectorImpl<const SCEV *> &Sizes,
7409 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007410
Sebastian Pop53524082014-05-29 19:44:05 +00007411 if (Terms.size() < 1 || !ElementSize)
Sebastian Pop448712b2014-05-07 18:01:20 +00007412 return;
7413
7414 // Early return when Terms do not contain parameters: we do not delinearize
7415 // non parametric SCEVs.
7416 if (!containsParameters(Terms))
7417 return;
7418
7419 DEBUG({
7420 dbgs() << "Terms:\n";
7421 for (const SCEV *T : Terms)
7422 dbgs() << *T << "\n";
7423 });
7424
7425 // Remove duplicates.
7426 std::sort(Terms.begin(), Terms.end());
7427 Terms.erase(std::unique(Terms.begin(), Terms.end()), Terms.end());
7428
7429 // Put larger terms first.
7430 std::sort(Terms.begin(), Terms.end(), [](const SCEV *LHS, const SCEV *RHS) {
7431 return numberOfTerms(LHS) > numberOfTerms(RHS);
7432 });
7433
Sebastian Popa6e58602014-05-27 22:41:45 +00007434 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
7435
7436 // Divide all terms by the element size.
7437 for (const SCEV *&Term : Terms) {
7438 const SCEV *Q, *R;
7439 SCEVDivision::divide(SE, Term, ElementSize, &Q, &R);
7440 Term = Q;
7441 }
7442
7443 SmallVector<const SCEV *, 4> NewTerms;
7444
7445 // Remove constant factors.
7446 for (const SCEV *T : Terms)
7447 if (const SCEV *NewT = removeConstantFactors(SE, T))
7448 NewTerms.push_back(NewT);
7449
Sebastian Pop448712b2014-05-07 18:01:20 +00007450 DEBUG({
7451 dbgs() << "Terms after sorting:\n";
Sebastian Popa6e58602014-05-27 22:41:45 +00007452 for (const SCEV *T : NewTerms)
Sebastian Pop448712b2014-05-07 18:01:20 +00007453 dbgs() << *T << "\n";
7454 });
7455
Sebastian Popa6e58602014-05-27 22:41:45 +00007456 if (NewTerms.empty() ||
7457 !findArrayDimensionsRec(SE, NewTerms, Sizes)) {
Sebastian Popb1a548f2014-05-12 19:01:53 +00007458 Sizes.clear();
7459 return;
7460 }
Sebastian Pop448712b2014-05-07 18:01:20 +00007461
Sebastian Popa6e58602014-05-27 22:41:45 +00007462 // The last element to be pushed into Sizes is the size of an element.
7463 Sizes.push_back(ElementSize);
7464
Sebastian Pop448712b2014-05-07 18:01:20 +00007465 DEBUG({
7466 dbgs() << "Sizes:\n";
7467 for (const SCEV *S : Sizes)
7468 dbgs() << *S << "\n";
7469 });
7470}
7471
7472/// Third step of delinearization: compute the access functions for the
7473/// Subscripts based on the dimensions in Sizes.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007474void SCEVAddRecExpr::computeAccessFunctions(
Sebastian Pop448712b2014-05-07 18:01:20 +00007475 ScalarEvolution &SE, SmallVectorImpl<const SCEV *> &Subscripts,
7476 SmallVectorImpl<const SCEV *> &Sizes) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007477
Sebastian Popb1a548f2014-05-12 19:01:53 +00007478 // Early exit in case this SCEV is not an affine multivariate function.
7479 if (Sizes.empty() || !this->isAffine())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007480 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007481
Sebastian Pop28e6b972014-05-27 22:41:51 +00007482 const SCEV *Res = this;
Sebastian Pop448712b2014-05-07 18:01:20 +00007483 int Last = Sizes.size() - 1;
7484 for (int i = Last; i >= 0; i--) {
7485 const SCEV *Q, *R;
7486 SCEVDivision::divide(SE, Res, Sizes[i], &Q, &R);
7487
7488 DEBUG({
7489 dbgs() << "Res: " << *Res << "\n";
7490 dbgs() << "Sizes[i]: " << *Sizes[i] << "\n";
7491 dbgs() << "Res divided by Sizes[i]:\n";
7492 dbgs() << "Quotient: " << *Q << "\n";
7493 dbgs() << "Remainder: " << *R << "\n";
7494 });
7495
7496 Res = Q;
7497
Sebastian Popa6e58602014-05-27 22:41:45 +00007498 // Do not record the last subscript corresponding to the size of elements in
7499 // the array.
Sebastian Pop448712b2014-05-07 18:01:20 +00007500 if (i == Last) {
Sebastian Popa6e58602014-05-27 22:41:45 +00007501
7502 // Bail out if the remainder is too complex.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007503 if (isa<SCEVAddRecExpr>(R)) {
7504 Subscripts.clear();
7505 Sizes.clear();
7506 return;
7507 }
Sebastian Popa6e58602014-05-27 22:41:45 +00007508
Sebastian Pop448712b2014-05-07 18:01:20 +00007509 continue;
7510 }
7511
7512 // Record the access function for the current subscript.
7513 Subscripts.push_back(R);
7514 }
7515
7516 // Also push in last position the remainder of the last division: it will be
7517 // the access function of the innermost dimension.
7518 Subscripts.push_back(Res);
7519
7520 std::reverse(Subscripts.begin(), Subscripts.end());
7521
7522 DEBUG({
7523 dbgs() << "Subscripts:\n";
7524 for (const SCEV *S : Subscripts)
7525 dbgs() << *S << "\n";
7526 });
Sebastian Pop448712b2014-05-07 18:01:20 +00007527}
7528
Sebastian Popc62c6792013-11-12 22:47:20 +00007529/// Splits the SCEV into two vectors of SCEVs representing the subscripts and
7530/// sizes of an array access. Returns the remainder of the delinearization that
Sebastian Pop7ee14722013-11-13 22:37:58 +00007531/// is the offset start of the array. The SCEV->delinearize algorithm computes
7532/// the multiples of SCEV coefficients: that is a pattern matching of sub
7533/// expressions in the stride and base of a SCEV corresponding to the
7534/// computation of a GCD (greatest common divisor) of base and stride. When
7535/// SCEV->delinearize fails, it returns the SCEV unchanged.
7536///
7537/// For example: when analyzing the memory access A[i][j][k] in this loop nest
7538///
7539/// void foo(long n, long m, long o, double A[n][m][o]) {
7540///
7541/// for (long i = 0; i < n; i++)
7542/// for (long j = 0; j < m; j++)
7543/// for (long k = 0; k < o; k++)
7544/// A[i][j][k] = 1.0;
7545/// }
7546///
7547/// the delinearization input is the following AddRec SCEV:
7548///
7549/// AddRec: {{{%A,+,(8 * %m * %o)}<%for.i>,+,(8 * %o)}<%for.j>,+,8}<%for.k>
7550///
7551/// From this SCEV, we are able to say that the base offset of the access is %A
7552/// because it appears as an offset that does not divide any of the strides in
7553/// the loops:
7554///
7555/// CHECK: Base offset: %A
7556///
7557/// and then SCEV->delinearize determines the size of some of the dimensions of
7558/// the array as these are the multiples by which the strides are happening:
7559///
7560/// CHECK: ArrayDecl[UnknownSize][%m][%o] with elements of sizeof(double) bytes.
7561///
7562/// Note that the outermost dimension remains of UnknownSize because there are
7563/// no strides that would help identifying the size of the last dimension: when
7564/// the array has been statically allocated, one could compute the size of that
7565/// dimension by dividing the overall size of the array by the size of the known
7566/// dimensions: %m * %o * 8.
7567///
7568/// Finally delinearize provides the access functions for the array reference
7569/// that does correspond to A[i][j][k] of the above C testcase:
7570///
7571/// CHECK: ArrayRef[{0,+,1}<%for.i>][{0,+,1}<%for.j>][{0,+,1}<%for.k>]
7572///
7573/// The testcases are checking the output of a function pass:
7574/// DelinearizationPass that walks through all loads and stores of a function
7575/// asking for the SCEV of the memory access with respect to all enclosing
7576/// loops, calling SCEV->delinearize on that and printing the results.
7577
Sebastian Pop28e6b972014-05-27 22:41:51 +00007578void SCEVAddRecExpr::delinearize(ScalarEvolution &SE,
7579 SmallVectorImpl<const SCEV *> &Subscripts,
7580 SmallVectorImpl<const SCEV *> &Sizes,
7581 const SCEV *ElementSize) const {
Sebastian Pop448712b2014-05-07 18:01:20 +00007582 // First step: collect parametric terms.
7583 SmallVector<const SCEV *, 4> Terms;
7584 collectParametricTerms(SE, Terms);
Sebastian Popc62c6792013-11-12 22:47:20 +00007585
Sebastian Popb1a548f2014-05-12 19:01:53 +00007586 if (Terms.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007587 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007588
Sebastian Pop448712b2014-05-07 18:01:20 +00007589 // Second step: find subscript sizes.
Sebastian Popa6e58602014-05-27 22:41:45 +00007590 SE.findArrayDimensions(Terms, Sizes, ElementSize);
Sebastian Pop7ee14722013-11-13 22:37:58 +00007591
Sebastian Popb1a548f2014-05-12 19:01:53 +00007592 if (Sizes.empty())
Sebastian Pop28e6b972014-05-27 22:41:51 +00007593 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007594
Sebastian Pop448712b2014-05-07 18:01:20 +00007595 // Third step: compute the access functions for each subscript.
Sebastian Pop28e6b972014-05-27 22:41:51 +00007596 computeAccessFunctions(SE, Subscripts, Sizes);
Sebastian Popc62c6792013-11-12 22:47:20 +00007597
Sebastian Pop28e6b972014-05-27 22:41:51 +00007598 if (Subscripts.empty())
7599 return;
Sebastian Popb1a548f2014-05-12 19:01:53 +00007600
Sebastian Pop448712b2014-05-07 18:01:20 +00007601 DEBUG({
7602 dbgs() << "succeeded to delinearize " << *this << "\n";
7603 dbgs() << "ArrayDecl[UnknownSize]";
7604 for (const SCEV *S : Sizes)
7605 dbgs() << "[" << *S << "]";
Sebastian Popc62c6792013-11-12 22:47:20 +00007606
Sebastian Pop444621a2014-05-09 22:45:02 +00007607 dbgs() << "\nArrayRef";
7608 for (const SCEV *S : Subscripts)
Sebastian Pop448712b2014-05-07 18:01:20 +00007609 dbgs() << "[" << *S << "]";
7610 dbgs() << "\n";
7611 });
Sebastian Popc62c6792013-11-12 22:47:20 +00007612}
Chris Lattnerd934c702004-04-02 20:23:17 +00007613
7614//===----------------------------------------------------------------------===//
Dan Gohman48f82222009-05-04 22:30:44 +00007615// SCEVCallbackVH Class Implementation
7616//===----------------------------------------------------------------------===//
7617
Dan Gohmand33a0902009-05-19 19:22:47 +00007618void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmandd707af2009-07-13 22:20:53 +00007619 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Dan Gohman48f82222009-05-04 22:30:44 +00007620 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
7621 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007622 SE->ValueExprMap.erase(getValPtr());
Dan Gohman48f82222009-05-04 22:30:44 +00007623 // this now dangles!
7624}
7625
Dan Gohman7a066722010-07-28 01:09:07 +00007626void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
Dan Gohmandd707af2009-07-13 22:20:53 +00007627 assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
Eric Christopheref6d5932010-07-29 01:25:38 +00007628
Dan Gohman48f82222009-05-04 22:30:44 +00007629 // Forget all the expressions associated with users of the old value,
7630 // so that future queries will recompute the expressions using the new
7631 // value.
Dan Gohman7cac9572010-08-02 23:49:30 +00007632 Value *Old = getValPtr();
Chandler Carruthcdf47882014-03-09 03:16:01 +00007633 SmallVector<User *, 16> Worklist(Old->user_begin(), Old->user_end());
Dan Gohmanf34f8632009-07-14 14:34:04 +00007634 SmallPtrSet<User *, 8> Visited;
Dan Gohman48f82222009-05-04 22:30:44 +00007635 while (!Worklist.empty()) {
7636 User *U = Worklist.pop_back_val();
7637 // Deleting the Old value will cause this to dangle. Postpone
7638 // that until everything else is done.
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007639 if (U == Old)
Dan Gohman48f82222009-05-04 22:30:44 +00007640 continue;
Dan Gohmanf34f8632009-07-14 14:34:04 +00007641 if (!Visited.insert(U))
7642 continue;
Dan Gohman48f82222009-05-04 22:30:44 +00007643 if (PHINode *PN = dyn_cast<PHINode>(U))
7644 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007645 SE->ValueExprMap.erase(U);
Chandler Carruthcdf47882014-03-09 03:16:01 +00007646 Worklist.insert(Worklist.end(), U->user_begin(), U->user_end());
Dan Gohman48f82222009-05-04 22:30:44 +00007647 }
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007648 // Delete the Old value.
7649 if (PHINode *PN = dyn_cast<PHINode>(Old))
7650 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007651 SE->ValueExprMap.erase(Old);
Dan Gohman8aeb0fb2010-07-28 00:28:25 +00007652 // this now dangles!
Dan Gohman48f82222009-05-04 22:30:44 +00007653}
7654
Dan Gohmand33a0902009-05-19 19:22:47 +00007655ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohman48f82222009-05-04 22:30:44 +00007656 : CallbackVH(V), SE(se) {}
7657
7658//===----------------------------------------------------------------------===//
Chris Lattnerd934c702004-04-02 20:23:17 +00007659// ScalarEvolution Class Implementation
7660//===----------------------------------------------------------------------===//
7661
Dan Gohmanc8e23622009-04-21 23:15:49 +00007662ScalarEvolution::ScalarEvolution()
Craig Topper9f008862014-04-15 04:59:12 +00007663 : FunctionPass(ID), ValuesAtScopes(64), LoopDispositions(64),
7664 BlockDispositions(64), FirstUnknown(nullptr) {
Owen Anderson6c18d1a2010-10-19 17:21:58 +00007665 initializeScalarEvolutionPass(*PassRegistry::getPassRegistry());
Dan Gohmanc8e23622009-04-21 23:15:49 +00007666}
7667
Chris Lattnerd934c702004-04-02 20:23:17 +00007668bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanc8e23622009-04-21 23:15:49 +00007669 this->F = &F;
Hal Finkel60db0582014-09-07 18:57:58 +00007670 AT = &getAnalysis<AssumptionTracker>();
Dan Gohmanc8e23622009-04-21 23:15:49 +00007671 LI = &getAnalysis<LoopInfo>();
Rafael Espindola93512512014-02-25 17:30:31 +00007672 DataLayoutPass *DLP = getAnalysisIfAvailable<DataLayoutPass>();
Craig Topper9f008862014-04-15 04:59:12 +00007673 DL = DLP ? &DLP->getDataLayout() : nullptr;
Chad Rosierc24b86f2011-12-01 03:08:23 +00007674 TLI = &getAnalysis<TargetLibraryInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +00007675 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
Chris Lattnerd934c702004-04-02 20:23:17 +00007676 return false;
7677}
7678
7679void ScalarEvolution::releaseMemory() {
Dan Gohman7cac9572010-08-02 23:49:30 +00007680 // Iterate through all the SCEVUnknown instances and call their
7681 // destructors, so that they release their references to their values.
7682 for (SCEVUnknown *U = FirstUnknown; U; U = U->Next)
7683 U->~SCEVUnknown();
Craig Topper9f008862014-04-15 04:59:12 +00007684 FirstUnknown = nullptr;
Dan Gohman7cac9572010-08-02 23:49:30 +00007685
Dan Gohman9bad2fb2010-08-27 18:55:03 +00007686 ValueExprMap.clear();
Andrew Trick3ca3f982011-07-26 17:19:55 +00007687
7688 // Free any extra memory created for ExitNotTakenInfo in the unlikely event
7689 // that a loop had multiple computable exits.
7690 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
7691 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end();
7692 I != E; ++I) {
7693 I->second.clear();
7694 }
7695
Andrew Trick7fa4e0f2012-05-19 00:48:25 +00007696 assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
7697
Dan Gohmanc8e23622009-04-21 23:15:49 +00007698 BackedgeTakenCounts.clear();
7699 ConstantEvolutionLoopExitValue.clear();
Dan Gohman5122d612009-05-08 20:47:27 +00007700 ValuesAtScopes.clear();
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007701 LoopDispositions.clear();
Dan Gohman8ea83d82010-11-18 00:34:22 +00007702 BlockDispositions.clear();
Dan Gohman761065e2010-11-17 02:44:44 +00007703 UnsignedRanges.clear();
7704 SignedRanges.clear();
Dan Gohmanc5c85c02009-06-27 21:21:31 +00007705 UniqueSCEVs.clear();
7706 SCEVAllocator.Reset();
Chris Lattnerd934c702004-04-02 20:23:17 +00007707}
7708
7709void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
7710 AU.setPreservesAll();
Hal Finkel60db0582014-09-07 18:57:58 +00007711 AU.addRequired<AssumptionTracker>();
Chris Lattnerd934c702004-04-02 20:23:17 +00007712 AU.addRequiredTransitive<LoopInfo>();
Chandler Carruth73523022014-01-13 13:07:17 +00007713 AU.addRequiredTransitive<DominatorTreeWrapperPass>();
Chad Rosierc24b86f2011-12-01 03:08:23 +00007714 AU.addRequired<TargetLibraryInfo>();
Dan Gohman0a40ad92009-04-16 03:18:22 +00007715}
7716
Dan Gohmanc8e23622009-04-21 23:15:49 +00007717bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman0bddac12009-02-24 18:55:53 +00007718 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Chris Lattnerd934c702004-04-02 20:23:17 +00007719}
7720
Dan Gohmanc8e23622009-04-21 23:15:49 +00007721static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Chris Lattnerd934c702004-04-02 20:23:17 +00007722 const Loop *L) {
7723 // Print all inner loops first
7724 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
7725 PrintLoopInfo(OS, SE, *I);
Misha Brukman01808ca2005-04-21 21:13:18 +00007726
Dan Gohmanbc694912010-01-09 18:17:45 +00007727 OS << "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007728 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007729 OS << ": ";
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00007730
Dan Gohmancb0efec2009-12-18 01:14:11 +00007731 SmallVector<BasicBlock *, 8> ExitBlocks;
Chris Lattnerd72c3eb2004-04-18 22:14:10 +00007732 L->getExitBlocks(ExitBlocks);
7733 if (ExitBlocks.size() != 1)
Nick Lewyckyd1200b02008-01-02 02:49:20 +00007734 OS << "<multiple exits> ";
Chris Lattnerd934c702004-04-02 20:23:17 +00007735
Dan Gohman0bddac12009-02-24 18:55:53 +00007736 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
7737 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Chris Lattnerd934c702004-04-02 20:23:17 +00007738 } else {
Dan Gohman0bddac12009-02-24 18:55:53 +00007739 OS << "Unpredictable backedge-taken count. ";
Chris Lattnerd934c702004-04-02 20:23:17 +00007740 }
7741
Dan Gohmanbc694912010-01-09 18:17:45 +00007742 OS << "\n"
7743 "Loop ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007744 L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007745 OS << ": ";
Dan Gohman69942932009-06-24 00:33:16 +00007746
7747 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
7748 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
7749 } else {
7750 OS << "Unpredictable max backedge-taken count. ";
7751 }
7752
7753 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00007754}
7755
Dan Gohmancb0efec2009-12-18 01:14:11 +00007756void ScalarEvolution::print(raw_ostream &OS, const Module *) const {
Dan Gohman8b0a4192010-03-01 17:49:51 +00007757 // ScalarEvolution's implementation of the print method is to print
Dan Gohmanc8e23622009-04-21 23:15:49 +00007758 // out SCEV values of all instructions that are interesting. Doing
7759 // this potentially causes it to create new SCEV objects though,
7760 // which technically conflicts with the const qualifier. This isn't
Dan Gohman028e6152009-07-10 20:25:29 +00007761 // observable from outside the class though, so casting away the
7762 // const isn't dangerous.
Dan Gohmancb0efec2009-12-18 01:14:11 +00007763 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
Chris Lattnerd934c702004-04-02 20:23:17 +00007764
Dan Gohmanbc694912010-01-09 18:17:45 +00007765 OS << "Classifying expressions for: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007766 F->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007767 OS << "\n";
Chris Lattnerd934c702004-04-02 20:23:17 +00007768 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohmand18dc2c2010-05-03 17:03:23 +00007769 if (isSCEVable(I->getType()) && !isa<CmpInst>(*I)) {
Dan Gohmanfda3c4a2009-07-13 23:03:05 +00007770 OS << *I << '\n';
Dan Gohman81313fd2008-09-14 17:21:12 +00007771 OS << " --> ";
Dan Gohmanaf752342009-07-07 17:06:11 +00007772 const SCEV *SV = SE.getSCEV(&*I);
Chris Lattnerd934c702004-04-02 20:23:17 +00007773 SV->print(OS);
Misha Brukman01808ca2005-04-21 21:13:18 +00007774
Dan Gohmanb9063a82009-06-19 17:49:54 +00007775 const Loop *L = LI->getLoopFor((*I).getParent());
7776
Dan Gohmanaf752342009-07-07 17:06:11 +00007777 const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohmanb9063a82009-06-19 17:49:54 +00007778 if (AtUse != SV) {
7779 OS << " --> ";
7780 AtUse->print(OS);
7781 }
7782
7783 if (L) {
Dan Gohman94c468f2009-06-18 00:37:45 +00007784 OS << "\t\t" "Exits: ";
Dan Gohmanaf752342009-07-07 17:06:11 +00007785 const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanafd6db92010-11-17 21:23:15 +00007786 if (!SE.isLoopInvariant(ExitValue, L)) {
Chris Lattnerd934c702004-04-02 20:23:17 +00007787 OS << "<<Unknown>>";
7788 } else {
7789 OS << *ExitValue;
7790 }
7791 }
7792
Chris Lattnerd934c702004-04-02 20:23:17 +00007793 OS << "\n";
7794 }
7795
Dan Gohmanbc694912010-01-09 18:17:45 +00007796 OS << "Determining loop execution counts for: ";
Chandler Carruthd48cdbf2014-01-09 02:29:41 +00007797 F->printAsOperand(OS, /*PrintType=*/false);
Dan Gohmanbc694912010-01-09 18:17:45 +00007798 OS << "\n";
Dan Gohmanc8e23622009-04-21 23:15:49 +00007799 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
7800 PrintLoopInfo(OS, &SE, *I);
Chris Lattnerd934c702004-04-02 20:23:17 +00007801}
Dan Gohmane20f8242009-04-21 00:47:46 +00007802
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007803ScalarEvolution::LoopDisposition
7804ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007805 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values = LoopDispositions[S];
7806 for (unsigned u = 0; u < Values.size(); u++) {
7807 if (Values[u].first == L)
7808 return Values[u].second;
7809 }
7810 Values.push_back(std::make_pair(L, LoopVariant));
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007811 LoopDisposition D = computeLoopDisposition(S, L);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007812 SmallVector<std::pair<const Loop *, LoopDisposition>, 2> &Values2 = LoopDispositions[S];
7813 for (unsigned u = Values2.size(); u > 0; u--) {
7814 if (Values2[u - 1].first == L) {
7815 Values2[u - 1].second = D;
7816 break;
7817 }
7818 }
7819 return D;
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007820}
7821
7822ScalarEvolution::LoopDisposition
7823ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00007824 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohmanafd6db92010-11-17 21:23:15 +00007825 case scConstant:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007826 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007827 case scTruncate:
7828 case scZeroExtend:
7829 case scSignExtend:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007830 return getLoopDisposition(cast<SCEVCastExpr>(S)->getOperand(), L);
Dan Gohmanafd6db92010-11-17 21:23:15 +00007831 case scAddRecExpr: {
7832 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
7833
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007834 // If L is the addrec's loop, it's computable.
7835 if (AR->getLoop() == L)
7836 return LoopComputable;
7837
Dan Gohmanafd6db92010-11-17 21:23:15 +00007838 // Add recurrences are never invariant in the function-body (null loop).
7839 if (!L)
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007840 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007841
7842 // This recurrence is variant w.r.t. L if L contains AR's loop.
7843 if (L->contains(AR->getLoop()))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007844 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007845
7846 // This recurrence is invariant w.r.t. L if AR's loop contains L.
7847 if (AR->getLoop()->contains(L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007848 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007849
7850 // This recurrence is variant w.r.t. L if any of its operands
7851 // are variant.
7852 for (SCEVAddRecExpr::op_iterator I = AR->op_begin(), E = AR->op_end();
7853 I != E; ++I)
7854 if (!isLoopInvariant(*I, L))
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007855 return LoopVariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007856
7857 // Otherwise it's loop-invariant.
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007858 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007859 }
7860 case scAddExpr:
7861 case scMulExpr:
7862 case scUMaxExpr:
7863 case scSMaxExpr: {
7864 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohmanafd6db92010-11-17 21:23:15 +00007865 bool HasVarying = false;
7866 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
7867 I != E; ++I) {
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007868 LoopDisposition D = getLoopDisposition(*I, L);
7869 if (D == LoopVariant)
7870 return LoopVariant;
7871 if (D == LoopComputable)
7872 HasVarying = true;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007873 }
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007874 return HasVarying ? LoopComputable : LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007875 }
7876 case scUDivExpr: {
7877 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007878 LoopDisposition LD = getLoopDisposition(UDiv->getLHS(), L);
7879 if (LD == LoopVariant)
7880 return LoopVariant;
7881 LoopDisposition RD = getLoopDisposition(UDiv->getRHS(), L);
7882 if (RD == LoopVariant)
7883 return LoopVariant;
7884 return (LD == LoopInvariant && RD == LoopInvariant) ?
7885 LoopInvariant : LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007886 }
7887 case scUnknown:
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007888 // All non-instruction values are loop invariant. All instructions are loop
7889 // invariant if they are not contained in the specified loop.
7890 // Instructions are never considered invariant in the function body
7891 // (null loop) because they are defined within the "loop".
7892 if (Instruction *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
7893 return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
7894 return LoopInvariant;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007895 case scCouldNotCompute:
7896 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohmanafd6db92010-11-17 21:23:15 +00007897 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00007898 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman7ee1bbb2010-11-17 23:21:44 +00007899}
7900
7901bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
7902 return getLoopDisposition(S, L) == LoopInvariant;
7903}
7904
7905bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
7906 return getLoopDisposition(S, L) == LoopComputable;
Dan Gohmanafd6db92010-11-17 21:23:15 +00007907}
Dan Gohman20d9ce22010-11-17 21:41:58 +00007908
Dan Gohman8ea83d82010-11-18 00:34:22 +00007909ScalarEvolution::BlockDisposition
7910ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007911 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values = BlockDispositions[S];
7912 for (unsigned u = 0; u < Values.size(); u++) {
7913 if (Values[u].first == BB)
7914 return Values[u].second;
7915 }
7916 Values.push_back(std::make_pair(BB, DoesNotDominateBlock));
Dan Gohman8ea83d82010-11-18 00:34:22 +00007917 BlockDisposition D = computeBlockDisposition(S, BB);
Wan Xiaofeib2c8cdc2013-11-12 09:40:41 +00007918 SmallVector<std::pair<const BasicBlock *, BlockDisposition>, 2> &Values2 = BlockDispositions[S];
7919 for (unsigned u = Values2.size(); u > 0; u--) {
7920 if (Values2[u - 1].first == BB) {
7921 Values2[u - 1].second = D;
7922 break;
7923 }
7924 }
7925 return D;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007926}
7927
Dan Gohman8ea83d82010-11-18 00:34:22 +00007928ScalarEvolution::BlockDisposition
7929ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
Benjamin Kramer987b8502014-02-11 19:02:55 +00007930 switch (static_cast<SCEVTypes>(S->getSCEVType())) {
Dan Gohman20d9ce22010-11-17 21:41:58 +00007931 case scConstant:
Dan Gohman8ea83d82010-11-18 00:34:22 +00007932 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007933 case scTruncate:
7934 case scZeroExtend:
7935 case scSignExtend:
Dan Gohman8ea83d82010-11-18 00:34:22 +00007936 return getBlockDisposition(cast<SCEVCastExpr>(S)->getOperand(), BB);
Dan Gohman20d9ce22010-11-17 21:41:58 +00007937 case scAddRecExpr: {
7938 // This uses a "dominates" query instead of "properly dominates" query
Dan Gohman8ea83d82010-11-18 00:34:22 +00007939 // to test for proper dominance too, because the instruction which
7940 // produces the addrec's value is a PHI, and a PHI effectively properly
7941 // dominates its entire containing block.
Dan Gohman20d9ce22010-11-17 21:41:58 +00007942 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
7943 if (!DT->dominates(AR->getLoop()->getHeader(), BB))
Dan Gohman8ea83d82010-11-18 00:34:22 +00007944 return DoesNotDominateBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007945 }
7946 // FALL THROUGH into SCEVNAryExpr handling.
7947 case scAddExpr:
7948 case scMulExpr:
7949 case scUMaxExpr:
7950 case scSMaxExpr: {
7951 const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00007952 bool Proper = true;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007953 for (SCEVNAryExpr::op_iterator I = NAry->op_begin(), E = NAry->op_end();
Dan Gohman8ea83d82010-11-18 00:34:22 +00007954 I != E; ++I) {
7955 BlockDisposition D = getBlockDisposition(*I, BB);
7956 if (D == DoesNotDominateBlock)
7957 return DoesNotDominateBlock;
7958 if (D == DominatesBlock)
7959 Proper = false;
7960 }
7961 return Proper ? ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007962 }
7963 case scUDivExpr: {
7964 const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00007965 const SCEV *LHS = UDiv->getLHS(), *RHS = UDiv->getRHS();
7966 BlockDisposition LD = getBlockDisposition(LHS, BB);
7967 if (LD == DoesNotDominateBlock)
7968 return DoesNotDominateBlock;
7969 BlockDisposition RD = getBlockDisposition(RHS, BB);
7970 if (RD == DoesNotDominateBlock)
7971 return DoesNotDominateBlock;
7972 return (LD == ProperlyDominatesBlock && RD == ProperlyDominatesBlock) ?
7973 ProperlyDominatesBlock : DominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007974 }
7975 case scUnknown:
7976 if (Instruction *I =
Dan Gohman8ea83d82010-11-18 00:34:22 +00007977 dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
7978 if (I->getParent() == BB)
7979 return DominatesBlock;
7980 if (DT->properlyDominates(I->getParent(), BB))
7981 return ProperlyDominatesBlock;
7982 return DoesNotDominateBlock;
7983 }
7984 return ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007985 case scCouldNotCompute:
7986 llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
Dan Gohman20d9ce22010-11-17 21:41:58 +00007987 }
Benjamin Kramer987b8502014-02-11 19:02:55 +00007988 llvm_unreachable("Unknown SCEV kind!");
Dan Gohman8ea83d82010-11-18 00:34:22 +00007989}
7990
7991bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
7992 return getBlockDisposition(S, BB) >= DominatesBlock;
7993}
7994
7995bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
7996 return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
Dan Gohman20d9ce22010-11-17 21:41:58 +00007997}
Dan Gohman534749b2010-11-17 22:27:42 +00007998
Andrew Trick365e31c2012-07-13 23:33:03 +00007999namespace {
8000// Search for a SCEV expression node within an expression tree.
8001// Implements SCEVTraversal::Visitor.
8002struct SCEVSearch {
8003 const SCEV *Node;
8004 bool IsFound;
8005
8006 SCEVSearch(const SCEV *N): Node(N), IsFound(false) {}
8007
8008 bool follow(const SCEV *S) {
8009 IsFound |= (S == Node);
8010 return !IsFound;
8011 }
8012 bool isDone() const { return IsFound; }
8013};
8014}
8015
Dan Gohman534749b2010-11-17 22:27:42 +00008016bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
Andrew Trick365e31c2012-07-13 23:33:03 +00008017 SCEVSearch Search(Op);
8018 visitAll(S, Search);
8019 return Search.IsFound;
Dan Gohman534749b2010-11-17 22:27:42 +00008020}
Dan Gohman7e6b3932010-11-17 23:28:48 +00008021
8022void ScalarEvolution::forgetMemoizedResults(const SCEV *S) {
8023 ValuesAtScopes.erase(S);
8024 LoopDispositions.erase(S);
Dan Gohman8ea83d82010-11-18 00:34:22 +00008025 BlockDispositions.erase(S);
Dan Gohman7e6b3932010-11-17 23:28:48 +00008026 UnsignedRanges.erase(S);
8027 SignedRanges.erase(S);
Andrew Trick9093e152013-03-26 03:14:53 +00008028
8029 for (DenseMap<const Loop*, BackedgeTakenInfo>::iterator I =
8030 BackedgeTakenCounts.begin(), E = BackedgeTakenCounts.end(); I != E; ) {
8031 BackedgeTakenInfo &BEInfo = I->second;
8032 if (BEInfo.hasOperand(S, this)) {
8033 BEInfo.clear();
8034 BackedgeTakenCounts.erase(I++);
8035 }
8036 else
8037 ++I;
8038 }
Dan Gohman7e6b3932010-11-17 23:28:48 +00008039}
Benjamin Kramer214935e2012-10-26 17:31:32 +00008040
8041typedef DenseMap<const Loop *, std::string> VerifyMap;
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008042
Alp Tokercb402912014-01-24 17:20:08 +00008043/// replaceSubString - Replaces all occurrences of From in Str with To.
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008044static void replaceSubString(std::string &Str, StringRef From, StringRef To) {
8045 size_t Pos = 0;
8046 while ((Pos = Str.find(From, Pos)) != std::string::npos) {
8047 Str.replace(Pos, From.size(), To.data(), To.size());
8048 Pos += To.size();
8049 }
8050}
8051
Benjamin Kramer214935e2012-10-26 17:31:32 +00008052/// getLoopBackedgeTakenCounts - Helper method for verifyAnalysis.
8053static void
8054getLoopBackedgeTakenCounts(Loop *L, VerifyMap &Map, ScalarEvolution &SE) {
8055 for (Loop::reverse_iterator I = L->rbegin(), E = L->rend(); I != E; ++I) {
8056 getLoopBackedgeTakenCounts(*I, Map, SE); // recurse.
8057
8058 std::string &S = Map[L];
8059 if (S.empty()) {
8060 raw_string_ostream OS(S);
8061 SE.getBackedgeTakenCount(L)->print(OS);
Benjamin Kramer24d270d2012-10-27 10:45:01 +00008062
8063 // false and 0 are semantically equivalent. This can happen in dead loops.
8064 replaceSubString(OS.str(), "false", "0");
8065 // Remove wrap flags, their use in SCEV is highly fragile.
8066 // FIXME: Remove this when SCEV gets smarter about them.
8067 replaceSubString(OS.str(), "<nw>", "");
8068 replaceSubString(OS.str(), "<nsw>", "");
8069 replaceSubString(OS.str(), "<nuw>", "");
Benjamin Kramer214935e2012-10-26 17:31:32 +00008070 }
8071 }
8072}
8073
8074void ScalarEvolution::verifyAnalysis() const {
8075 if (!VerifySCEV)
8076 return;
8077
8078 ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
8079
8080 // Gather stringified backedge taken counts for all loops using SCEV's caches.
8081 // FIXME: It would be much better to store actual values instead of strings,
8082 // but SCEV pointers will change if we drop the caches.
8083 VerifyMap BackedgeDumpsOld, BackedgeDumpsNew;
8084 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8085 getLoopBackedgeTakenCounts(*I, BackedgeDumpsOld, SE);
8086
8087 // Gather stringified backedge taken counts for all loops without using
8088 // SCEV's caches.
8089 SE.releaseMemory();
8090 for (LoopInfo::reverse_iterator I = LI->rbegin(), E = LI->rend(); I != E; ++I)
8091 getLoopBackedgeTakenCounts(*I, BackedgeDumpsNew, SE);
8092
8093 // Now compare whether they're the same with and without caches. This allows
8094 // verifying that no pass changed the cache.
8095 assert(BackedgeDumpsOld.size() == BackedgeDumpsNew.size() &&
8096 "New loops suddenly appeared!");
8097
8098 for (VerifyMap::iterator OldI = BackedgeDumpsOld.begin(),
8099 OldE = BackedgeDumpsOld.end(),
8100 NewI = BackedgeDumpsNew.begin();
8101 OldI != OldE; ++OldI, ++NewI) {
8102 assert(OldI->first == NewI->first && "Loop order changed!");
8103
8104 // Compare the stringified SCEVs. We don't care if undef backedgetaken count
8105 // changes.
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008106 // FIXME: We currently ignore SCEV changes from/to CouldNotCompute. This
Benjamin Kramer214935e2012-10-26 17:31:32 +00008107 // means that a pass is buggy or SCEV has to learn a new pattern but is
8108 // usually not harmful.
8109 if (OldI->second != NewI->second &&
8110 OldI->second.find("undef") == std::string::npos &&
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008111 NewI->second.find("undef") == std::string::npos &&
8112 OldI->second != "***COULDNOTCOMPUTE***" &&
Benjamin Kramer214935e2012-10-26 17:31:32 +00008113 NewI->second != "***COULDNOTCOMPUTE***") {
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008114 dbgs() << "SCEVValidator: SCEV for loop '"
Benjamin Kramer214935e2012-10-26 17:31:32 +00008115 << OldI->first->getHeader()->getName()
Benjamin Kramer5bc077a2012-10-27 11:36:07 +00008116 << "' changed from '" << OldI->second
8117 << "' to '" << NewI->second << "'!\n";
Benjamin Kramer214935e2012-10-26 17:31:32 +00008118 std::abort();
8119 }
8120 }
8121
8122 // TODO: Verify more things.
8123}