blob: 50137fad674469a9e5453d98e085080e78fabdd0 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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
Owen Andersonecd0cd72009-06-22 21:39:50 +000017// can handle. These classes are reference counted, managed by the const SCEV*
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
31//
32// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
36// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
Evan Cheng98c073b2009-02-17 00:13:06 +000069#include "llvm/Analysis/Dominators.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070#include "llvm/Analysis/LoopInfo.h"
Dan Gohmana7726c32009-06-16 19:52:01 +000071#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000073#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000074#include "llvm/Support/CommandLine.h"
75#include "llvm/Support/Compiler.h"
76#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000077#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078#include "llvm/Support/InstIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000079#include "llvm/Support/MathExtras.h"
Dan Gohman13058cc2009-04-21 00:47:46 +000080#include "llvm/Support/raw_ostream.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000081#include "llvm/ADT/Statistic.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000082#include "llvm/ADT/STLExtras.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084using namespace llvm;
85
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086STATISTIC(NumArrayLenItCounts,
87 "Number of trip counts computed with array length");
88STATISTIC(NumTripCountsComputed,
89 "Number of loops with predictable loop counts");
90STATISTIC(NumTripCountsNotComputed,
91 "Number of loops without predictable loop counts");
92STATISTIC(NumBruteForceTripCountsComputed,
93 "Number of loops with trip counts computed by force");
94
Dan Gohman089efff2008-05-13 00:00:25 +000095static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
97 cl::desc("Maximum number of iterations SCEV will "
98 "symbolically execute a constant derived loop"),
99 cl::init(100));
100
Dan Gohman089efff2008-05-13 00:00:25 +0000101static RegisterPass<ScalarEvolution>
102R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103char ScalarEvolution::ID = 0;
104
105//===----------------------------------------------------------------------===//
106// SCEV class definitions
107//===----------------------------------------------------------------------===//
108
109//===----------------------------------------------------------------------===//
110// Implementation of the SCEV class.
111//
112SCEV::~SCEV() {}
113void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000114 print(errs());
115 errs() << '\n';
116}
117
118void SCEV::print(std::ostream &o) const {
119 raw_os_ostream OS(o);
120 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000121}
122
Dan Gohman7b560c42008-06-18 16:23:07 +0000123bool SCEV::isZero() const {
124 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
125 return SC->getValue()->isZero();
126 return false;
127}
128
Dan Gohmanf8bc8e82009-05-18 15:22:39 +0000129bool SCEV::isOne() const {
130 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
131 return SC->getValue()->isOne();
132 return false;
133}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000134
Dan Gohmanf05118e2009-06-24 00:30:26 +0000135bool SCEV::isAllOnesValue() const {
136 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
137 return SC->getValue()->isAllOnesValue();
138 return false;
139}
140
Owen Andersonb70139d2009-06-22 21:57:23 +0000141SCEVCouldNotCompute::SCEVCouldNotCompute() :
142 SCEV(scCouldNotCompute) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000143
144bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
149const Type *SCEVCouldNotCompute::getType() const {
150 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
151 return 0;
152}
153
154bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
155 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
156 return false;
157}
158
Owen Andersonecd0cd72009-06-22 21:39:50 +0000159const SCEV* SCEVCouldNotCompute::
160replaceSymbolicValuesWithConcrete(const SCEV* Sym,
161 const SCEV* Conc,
Dan Gohman89f85052007-10-22 18:31:58 +0000162 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 return this;
164}
165
Dan Gohman13058cc2009-04-21 00:47:46 +0000166void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000167 OS << "***COULDNOTCOMPUTE***";
168}
169
170bool SCEVCouldNotCompute::classof(const SCEV *S) {
171 return S->getSCEVType() == scCouldNotCompute;
172}
173
174
175// SCEVConstants - Only allow the creation of one SCEVConstant for any
Owen Andersonecd0cd72009-06-22 21:39:50 +0000176// particular value. Don't use a const SCEV* here, or else the object will
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177// never be deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000178
Owen Andersonecd0cd72009-06-22 21:39:50 +0000179const SCEV* ScalarEvolution::getConstant(ConstantInt *V) {
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000180 SCEVConstant *&R = SCEVConstants[V];
Owen Andersonb70139d2009-06-22 21:57:23 +0000181 if (R == 0) R = new SCEVConstant(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000182 return R;
183}
184
Owen Andersonecd0cd72009-06-22 21:39:50 +0000185const SCEV* ScalarEvolution::getConstant(const APInt& Val) {
Dan Gohman89f85052007-10-22 18:31:58 +0000186 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187}
188
Owen Andersonecd0cd72009-06-22 21:39:50 +0000189const SCEV*
Dan Gohman8fd520a2009-06-15 22:12:54 +0000190ScalarEvolution::getConstant(const Type *Ty, uint64_t V, bool isSigned) {
191 return getConstant(ConstantInt::get(cast<IntegerType>(Ty), V, isSigned));
192}
193
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000194const Type *SCEVConstant::getType() const { return V->getType(); }
195
Dan Gohman13058cc2009-04-21 00:47:46 +0000196void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000197 WriteAsOperand(OS, V, false);
198}
199
Dan Gohman2a381532009-04-21 01:25:57 +0000200SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
Owen Andersonb70139d2009-06-22 21:57:23 +0000201 const SCEV* op, const Type *ty)
202 : SCEV(SCEVTy), Op(op), Ty(ty) {}
Dan Gohman2a381532009-04-21 01:25:57 +0000203
204bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
205 return Op->dominates(BB, DT);
206}
207
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
Owen Andersonecd0cd72009-06-22 21:39:50 +0000209// particular input. Don't use a const SCEV* here, or else the object will
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210// never be deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211
Owen Andersonb70139d2009-06-22 21:57:23 +0000212SCEVTruncateExpr::SCEVTruncateExpr(const SCEV* op, const Type *ty)
213 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000214 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
215 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000217}
218
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219
Dan Gohman13058cc2009-04-21 00:47:46 +0000220void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000221 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000222}
223
224// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
Owen Andersonecd0cd72009-06-22 21:39:50 +0000225// particular input. Don't use a const SCEV* here, or else the object will never
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226// be deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000227
Owen Andersonb70139d2009-06-22 21:57:23 +0000228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEV* op, const Type *ty)
229 : SCEVCastExpr(scZeroExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000230 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
231 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232 "Cannot zero extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000233}
234
Dan Gohman13058cc2009-04-21 00:47:46 +0000235void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000236 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000237}
238
239// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
Owen Andersonecd0cd72009-06-22 21:39:50 +0000240// particular input. Don't use a const SCEV* here, or else the object will never
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241// be deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
Owen Andersonb70139d2009-06-22 21:57:23 +0000243SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEV* op, const Type *ty)
244 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000245 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
246 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000248}
249
Dan Gohman13058cc2009-04-21 00:47:46 +0000250void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000251 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000252}
253
254// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
Owen Andersonecd0cd72009-06-22 21:39:50 +0000255// particular input. Don't use a const SCEV* here, or else the object will never
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000256// be deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000257
Dan Gohman13058cc2009-04-21 00:47:46 +0000258void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000259 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
260 const char *OpStr = getOperationStr();
261 OS << "(" << *Operands[0];
262 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
263 OS << OpStr << *Operands[i];
264 OS << ")";
265}
266
Owen Andersonecd0cd72009-06-22 21:39:50 +0000267const SCEV* SCEVCommutativeExpr::
268replaceSymbolicValuesWithConcrete(const SCEV* Sym,
269 const SCEV* Conc,
Dan Gohman89f85052007-10-22 18:31:58 +0000270 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000271 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000272 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000273 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000274 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000275 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 NewOps.reserve(getNumOperands());
277 for (unsigned j = 0; j != i; ++j)
278 NewOps.push_back(getOperand(j));
279 NewOps.push_back(H);
280 for (++i; i != e; ++i)
281 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000282 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283
284 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000285 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000287 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000288 else if (isa<SCEVSMaxExpr>(this))
289 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000290 else if (isa<SCEVUMaxExpr>(this))
291 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000292 else
293 assert(0 && "Unknown commutative expr!");
294 }
295 }
296 return this;
297}
298
Dan Gohman72a8a022009-05-07 14:00:19 +0000299bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000300 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
301 if (!getOperand(i)->dominates(BB, DT))
302 return false;
303 }
304 return true;
305}
306
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000307
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000308// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Owen Andersonecd0cd72009-06-22 21:39:50 +0000309// input. Don't use a const SCEV* here, or else the object will never be
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000310// deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000311
Evan Cheng98c073b2009-02-17 00:13:06 +0000312bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
313 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
314}
315
Dan Gohman13058cc2009-04-21 00:47:46 +0000316void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000317 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000318}
319
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000320const Type *SCEVUDivExpr::getType() const {
Dan Gohman140f08f2009-05-26 17:44:05 +0000321 // In most cases the types of LHS and RHS will be the same, but in some
322 // crazy cases one or the other may be a pointer. ScalarEvolution doesn't
323 // depend on the type for correctness, but handling types carefully can
324 // avoid extra casts in the SCEVExpander. The LHS is more likely to be
325 // a pointer type than the RHS, so use the RHS' type here.
326 return RHS->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327}
328
329// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
Owen Andersonecd0cd72009-06-22 21:39:50 +0000330// particular input. Don't use a const SCEV* here, or else the object will never
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331// be deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332
Owen Andersonecd0cd72009-06-22 21:39:50 +0000333const SCEV* SCEVAddRecExpr::
334replaceSymbolicValuesWithConcrete(const SCEV* Sym,
335 const SCEV* Conc,
Dan Gohman89f85052007-10-22 18:31:58 +0000336 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000337 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000338 const SCEV* H =
Dan Gohman89f85052007-10-22 18:31:58 +0000339 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340 if (H != getOperand(i)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000341 SmallVector<const SCEV*, 8> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342 NewOps.reserve(getNumOperands());
343 for (unsigned j = 0; j != i; ++j)
344 NewOps.push_back(getOperand(j));
345 NewOps.push_back(H);
346 for (++i; i != e; ++i)
347 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000348 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349
Dan Gohman89f85052007-10-22 18:31:58 +0000350 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000351 }
352 }
353 return this;
354}
355
356
357bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
358 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
359 // contain L and if the start is invariant.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000360 // Add recurrences are never invariant in the function-body (null loop).
361 return QueryLoop &&
362 !QueryLoop->contains(L->getHeader()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 getOperand(0)->isLoopInvariant(QueryLoop);
364}
365
366
Dan Gohman13058cc2009-04-21 00:47:46 +0000367void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 OS << "{" << *Operands[0];
369 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
370 OS << ",+," << *Operands[i];
371 OS << "}<" << L->getHeader()->getName() + ">";
372}
373
374// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
Owen Andersonecd0cd72009-06-22 21:39:50 +0000375// value. Don't use a const SCEV* here, or else the object will never be
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000376// deleted!
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377
378bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
379 // All non-instruction values are loop invariant. All instructions are loop
380 // invariant if they are not contained in the specified loop.
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000381 // Instructions are never considered invariant in the function body
382 // (null loop) because they are defined within the "loop".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000383 if (Instruction *I = dyn_cast<Instruction>(V))
Dan Gohmanae1eaae2009-05-20 01:01:24 +0000384 return L && !L->contains(I->getParent());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000385 return true;
386}
387
Evan Cheng98c073b2009-02-17 00:13:06 +0000388bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
389 if (Instruction *I = dyn_cast<Instruction>(getValue()))
390 return DT->dominates(I->getParent(), BB);
391 return true;
392}
393
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394const Type *SCEVUnknown::getType() const {
395 return V->getType();
396}
397
Dan Gohman13058cc2009-04-21 00:47:46 +0000398void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 WriteAsOperand(OS, V, false);
400}
401
402//===----------------------------------------------------------------------===//
403// SCEV Utilities
404//===----------------------------------------------------------------------===//
405
406namespace {
407 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
408 /// than the complexity of the RHS. This comparator is used to canonicalize
409 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000410 class VISIBILITY_HIDDEN SCEVComplexityCompare {
411 LoopInfo *LI;
412 public:
413 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
414
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000415 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000416 // Primarily, sort the SCEVs by their getSCEVType().
417 if (LHS->getSCEVType() != RHS->getSCEVType())
418 return LHS->getSCEVType() < RHS->getSCEVType();
419
420 // Aside from the getSCEVType() ordering, the particular ordering
421 // isn't very important except that it's beneficial to be consistent,
422 // so that (a + b) and (b + a) don't end up as different expressions.
423
424 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
425 // not as complete as it could be.
426 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
427 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
428
Dan Gohmand0c01232009-05-19 02:15:55 +0000429 // Order pointer values after integer values. This helps SCEVExpander
430 // form GEPs.
431 if (isa<PointerType>(LU->getType()) && !isa<PointerType>(RU->getType()))
432 return false;
433 if (isa<PointerType>(RU->getType()) && !isa<PointerType>(LU->getType()))
434 return true;
435
Dan Gohman5d486452009-05-07 14:39:04 +0000436 // Compare getValueID values.
437 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
438 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
439
440 // Sort arguments by their position.
441 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
442 const Argument *RA = cast<Argument>(RU->getValue());
443 return LA->getArgNo() < RA->getArgNo();
444 }
445
446 // For instructions, compare their loop depth, and their opcode.
447 // This is pretty loose.
448 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
449 Instruction *RV = cast<Instruction>(RU->getValue());
450
451 // Compare loop depths.
452 if (LI->getLoopDepth(LV->getParent()) !=
453 LI->getLoopDepth(RV->getParent()))
454 return LI->getLoopDepth(LV->getParent()) <
455 LI->getLoopDepth(RV->getParent());
456
457 // Compare opcodes.
458 if (LV->getOpcode() != RV->getOpcode())
459 return LV->getOpcode() < RV->getOpcode();
460
461 // Compare the number of operands.
462 if (LV->getNumOperands() != RV->getNumOperands())
463 return LV->getNumOperands() < RV->getNumOperands();
464 }
465
466 return false;
467 }
468
Dan Gohman56fc8f12009-06-14 22:51:25 +0000469 // Compare constant values.
470 if (const SCEVConstant *LC = dyn_cast<SCEVConstant>(LHS)) {
471 const SCEVConstant *RC = cast<SCEVConstant>(RHS);
472 return LC->getValue()->getValue().ult(RC->getValue()->getValue());
473 }
474
475 // Compare addrec loop depths.
476 if (const SCEVAddRecExpr *LA = dyn_cast<SCEVAddRecExpr>(LHS)) {
477 const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
478 if (LA->getLoop()->getLoopDepth() != RA->getLoop()->getLoopDepth())
479 return LA->getLoop()->getLoopDepth() < RA->getLoop()->getLoopDepth();
480 }
Dan Gohman5d486452009-05-07 14:39:04 +0000481
482 // Lexicographically compare n-ary expressions.
483 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
484 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
485 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
486 if (i >= RC->getNumOperands())
487 return false;
488 if (operator()(LC->getOperand(i), RC->getOperand(i)))
489 return true;
490 if (operator()(RC->getOperand(i), LC->getOperand(i)))
491 return false;
492 }
493 return LC->getNumOperands() < RC->getNumOperands();
494 }
495
Dan Gohman6e10db12009-05-07 19:23:21 +0000496 // Lexicographically compare udiv expressions.
497 if (const SCEVUDivExpr *LC = dyn_cast<SCEVUDivExpr>(LHS)) {
498 const SCEVUDivExpr *RC = cast<SCEVUDivExpr>(RHS);
499 if (operator()(LC->getLHS(), RC->getLHS()))
500 return true;
501 if (operator()(RC->getLHS(), LC->getLHS()))
502 return false;
503 if (operator()(LC->getRHS(), RC->getRHS()))
504 return true;
505 if (operator()(RC->getRHS(), LC->getRHS()))
506 return false;
507 return false;
508 }
509
Dan Gohman5d486452009-05-07 14:39:04 +0000510 // Compare cast expressions by operand.
511 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
512 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
513 return operator()(LC->getOperand(), RC->getOperand());
514 }
515
516 assert(0 && "Unknown SCEV kind!");
517 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518 }
519 };
520}
521
522/// GroupByComplexity - Given a list of SCEV objects, order them by their
523/// complexity, and group objects of the same complexity together by value.
524/// When this routine is finished, we know that any duplicates in the vector are
525/// consecutive and that complexity is monotonically increasing.
526///
527/// Note that we go take special precautions to ensure that we get determinstic
528/// results from this routine. In other words, we don't want the results of
529/// this to depend on where the addresses of various SCEV objects happened to
530/// land in memory.
531///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000532static void GroupByComplexity(SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman5d486452009-05-07 14:39:04 +0000533 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 if (Ops.size() < 2) return; // Noop
535 if (Ops.size() == 2) {
536 // This is the common case, which also happens to be trivially simple.
537 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000538 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000539 std::swap(Ops[0], Ops[1]);
540 return;
541 }
542
543 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000544 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000545
546 // Now that we are sorted by complexity, group elements of the same
547 // complexity. Note that this is, at worst, N^2, but the vector is likely to
548 // be extremely short in practice. Note that we take this approach because we
549 // do not want to depend on the addresses of the objects we are grouping.
550 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000551 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552 unsigned Complexity = S->getSCEVType();
553
554 // If there are any objects of the same complexity and same value as this
555 // one, group them.
556 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
557 if (Ops[j] == S) { // Found a duplicate.
558 // Move it to immediately after i'th element.
559 std::swap(Ops[i+1], Ops[j]);
560 ++i; // no need to rescan it.
561 if (i == e-2) return; // Done!
562 }
563 }
564 }
565}
566
567
568
569//===----------------------------------------------------------------------===//
570// Simple SCEV method implementations
571//===----------------------------------------------------------------------===//
572
Eli Friedman7489ec92008-08-04 23:49:06 +0000573/// BinomialCoefficient - Compute BC(It, K). The result has width W.
Dan Gohmanc8a29272009-05-24 23:45:28 +0000574/// Assume, K > 0.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000575static const SCEV* BinomialCoefficient(const SCEV* It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000576 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000577 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000578 // Handle the simplest case efficiently.
579 if (K == 1)
580 return SE.getTruncateOrZeroExtend(It, ResultTy);
581
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000582 // We are using the following formula for BC(It, K):
583 //
584 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
585 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000586 // Suppose, W is the bitwidth of the return value. We must be prepared for
587 // overflow. Hence, we must assure that the result of our computation is
588 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
589 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000590 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000591 // However, this code doesn't use exactly that formula; the formula it uses
592 // is something like the following, where T is the number of factors of 2 in
593 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
594 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000595 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000596 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000597 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000598 // This formula is trivially equivalent to the previous formula. However,
599 // this formula can be implemented much more efficiently. The trick is that
600 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
601 // arithmetic. To do exact division in modular arithmetic, all we have
602 // to do is multiply by the inverse. Therefore, this step can be done at
603 // width W.
604 //
605 // The next issue is how to safely do the division by 2^T. The way this
606 // is done is by doing the multiplication step at a width of at least W + T
607 // bits. This way, the bottom W+T bits of the product are accurate. Then,
608 // when we perform the division by 2^T (which is equivalent to a right shift
609 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
610 // truncated out after the division by 2^T.
611 //
612 // In comparison to just directly using the first formula, this technique
613 // is much more efficient; using the first formula requires W * K bits,
614 // but this formula less than W + K bits. Also, the first formula requires
615 // a division step, whereas this formula only requires multiplies and shifts.
616 //
617 // It doesn't matter whether the subtraction step is done in the calculation
618 // width or the input iteration count's width; if the subtraction overflows,
619 // the result must be zero anyway. We prefer here to do it in the width of
620 // the induction variable because it helps a lot for certain cases; CodeGen
621 // isn't smart enough to ignore the overflow, which leads to much less
622 // efficient code if the width of the subtraction is wider than the native
623 // register width.
624 //
625 // (It's possible to not widen at all by pulling out factors of 2 before
626 // the multiplication; for example, K=2 can be calculated as
627 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
628 // extra arithmetic, so it's not an obvious win, and it gets
629 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000630
Eli Friedman7489ec92008-08-04 23:49:06 +0000631 // Protection from insane SCEVs; this bound is conservative,
632 // but it probably doesn't matter.
633 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000634 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000635
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000636 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000637
Eli Friedman7489ec92008-08-04 23:49:06 +0000638 // Calculate K! / 2^T and T; we divide out the factors of two before
639 // multiplying for calculating K! / 2^T to avoid overflow.
640 // Other overflow doesn't matter because we only care about the bottom
641 // W bits of the result.
642 APInt OddFactorial(W, 1);
643 unsigned T = 1;
644 for (unsigned i = 3; i <= K; ++i) {
645 APInt Mult(W, i);
646 unsigned TwoFactors = Mult.countTrailingZeros();
647 T += TwoFactors;
648 Mult = Mult.lshr(TwoFactors);
649 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000651
Eli Friedman7489ec92008-08-04 23:49:06 +0000652 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000653 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000654
655 // Calcuate 2^T, at width T+W.
656 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
657
658 // Calculate the multiplicative inverse of K! / 2^T;
659 // this multiplication factor will perform the exact division by
660 // K! / 2^T.
661 APInt Mod = APInt::getSignedMinValue(W+1);
662 APInt MultiplyFactor = OddFactorial.zext(W+1);
663 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
664 MultiplyFactor = MultiplyFactor.trunc(W);
665
666 // Calculate the product, at width T+W
667 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
Owen Andersonecd0cd72009-06-22 21:39:50 +0000668 const SCEV* Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
Eli Friedman7489ec92008-08-04 23:49:06 +0000669 for (unsigned i = 1; i != K; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000670 const SCEV* S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
Eli Friedman7489ec92008-08-04 23:49:06 +0000671 Dividend = SE.getMulExpr(Dividend,
672 SE.getTruncateOrZeroExtend(S, CalculationTy));
673 }
674
675 // Divide by 2^T
Owen Andersonecd0cd72009-06-22 21:39:50 +0000676 const SCEV* DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
Eli Friedman7489ec92008-08-04 23:49:06 +0000677
678 // Truncate the result, and divide by K! / 2^T.
679
680 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
681 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000682}
683
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000684/// evaluateAtIteration - Return the value of this chain of recurrences at
685/// the specified iteration number. We can evaluate this recurrence by
686/// multiplying each element in the chain by the binomial coefficient
687/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
688///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000689/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000691/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000693const SCEV* SCEVAddRecExpr::evaluateAtIteration(const SCEV* It,
Dan Gohman89f85052007-10-22 18:31:58 +0000694 ScalarEvolution &SE) const {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000695 const SCEV* Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000696 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000697 // The computation is correct in the face of overflow provided that the
698 // multiplication is performed _after_ the evaluation of the binomial
699 // coefficient.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000700 const SCEV* Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000701 if (isa<SCEVCouldNotCompute>(Coeff))
702 return Coeff;
703
704 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000705 }
706 return Result;
707}
708
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000709//===----------------------------------------------------------------------===//
710// SCEV Expression folder implementations
711//===----------------------------------------------------------------------===//
712
Owen Andersonecd0cd72009-06-22 21:39:50 +0000713const SCEV* ScalarEvolution::getTruncateExpr(const SCEV* Op,
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000714 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000715 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000716 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000717 assert(isSCEVable(Ty) &&
718 "This is not a conversion to a SCEVable type!");
719 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000720
Dan Gohmanc76b5452009-05-04 22:02:23 +0000721 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman55788cf2009-06-24 00:38:39 +0000722 return getConstant(
723 cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724
Dan Gohman1a5c4992009-04-22 16:20:48 +0000725 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000726 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000727 return getTruncateExpr(ST->getOperand(), Ty);
728
Nick Lewycky37d04642009-04-23 05:15:08 +0000729 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000730 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000731 return getTruncateOrSignExtend(SS->getOperand(), Ty);
732
733 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000734 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000735 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
736
Dan Gohman1c0aa2c2009-06-18 16:24:47 +0000737 // If the input value is a chrec scev, truncate the chrec's operands.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000738 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000739 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman45b3b542009-05-08 21:03:19 +0000741 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
742 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000743 }
744
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000745 SCEVTruncateExpr *&Result = SCEVTruncates[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000746 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 return Result;
748}
749
Owen Andersonecd0cd72009-06-22 21:39:50 +0000750const SCEV* ScalarEvolution::getZeroExtendExpr(const SCEV* Op,
Dan Gohman36d40922009-04-16 19:25:55 +0000751 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000752 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000753 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000754 assert(isSCEVable(Ty) &&
755 "This is not a conversion to a SCEVable type!");
756 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000757
Dan Gohmanc76b5452009-05-04 22:02:23 +0000758 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000759 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000760 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
761 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000762 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000763 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764
Dan Gohman1a5c4992009-04-22 16:20:48 +0000765 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000766 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000767 return getZeroExtendExpr(SZ->getOperand(), Ty);
768
Dan Gohmana9dba962009-04-27 20:16:15 +0000769 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000771 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000772 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000773 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000774 if (AR->isAffine()) {
775 // Check whether the backedge-taken count is SCEVCouldNotCompute.
776 // Note that this serves two purposes: It filters out loops that are
777 // simply not analyzable, and it covers the case where this code is
778 // being called from within backedge-taken count analysis, such that
779 // attempting to ask for the backedge-taken count would likely result
780 // in infinite recursion. In the later case, the analysis code will
781 // cope with a conservative value, and it will take care to purge
782 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000783 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000784 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000785 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000786 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000787 const SCEV* Start = AR->getStart();
788 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000789
790 // Check whether the backedge-taken count can be losslessly casted to
791 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000792 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000793 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000794 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000795 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
796 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000797 const Type *WideTy =
798 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000799 // Check whether Start+Step*MaxBECount has no unsigned overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000800 const SCEV* ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000801 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000802 getTruncateOrZeroExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000803 const SCEV* Add = getAddExpr(Start, ZMul);
804 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000805 getAddExpr(getZeroExtendExpr(Start, WideTy),
806 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
807 getZeroExtendExpr(Step, WideTy)));
808 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000809 // Return the expression with the addrec on the outside.
810 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
811 getZeroExtendExpr(Step, Ty),
812 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000813
814 // Similar to above, only this time treat the step value as signed.
815 // This covers loops that count down.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000816 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000817 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000818 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000819 Add = getAddExpr(Start, SMul);
Dan Gohman3bb37f52009-05-18 15:58:39 +0000820 OperandExtendedAdd =
821 getAddExpr(getZeroExtendExpr(Start, WideTy),
822 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
823 getSignExtendExpr(Step, WideTy)));
824 if (getZeroExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000825 // Return the expression with the addrec on the outside.
826 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
827 getSignExtendExpr(Step, Ty),
828 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000829 }
830 }
831 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000833 SCEVZeroExtendExpr *&Result = SCEVZeroExtends[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000834 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 return Result;
836}
837
Owen Andersonecd0cd72009-06-22 21:39:50 +0000838const SCEV* ScalarEvolution::getSignExtendExpr(const SCEV* Op,
Dan Gohmana9dba962009-04-27 20:16:15 +0000839 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000840 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000841 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000842 assert(isSCEVable(Ty) &&
843 "This is not a conversion to a SCEVable type!");
844 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000845
Dan Gohmanc76b5452009-05-04 22:02:23 +0000846 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000847 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000848 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
849 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
Dan Gohman55788cf2009-06-24 00:38:39 +0000850 return getConstant(cast<ConstantInt>(C));
Dan Gohman01c2ee72009-04-16 03:18:22 +0000851 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000852
Dan Gohman1a5c4992009-04-22 16:20:48 +0000853 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000854 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000855 return getSignExtendExpr(SS->getOperand(), Ty);
856
Dan Gohmana9dba962009-04-27 20:16:15 +0000857 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000859 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000861 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000862 if (AR->isAffine()) {
863 // Check whether the backedge-taken count is SCEVCouldNotCompute.
864 // Note that this serves two purposes: It filters out loops that are
865 // simply not analyzable, and it covers the case where this code is
866 // being called from within backedge-taken count analysis, such that
867 // attempting to ask for the backedge-taken count would likely result
868 // in infinite recursion. In the later case, the analysis code will
869 // cope with a conservative value, and it will take care to purge
870 // that value once it has finished.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000871 const SCEV* MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000872 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000873 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000874 // overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000875 const SCEV* Start = AR->getStart();
876 const SCEV* Step = AR->getStepRecurrence(*this);
Dan Gohmana9dba962009-04-27 20:16:15 +0000877
878 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000879 // the addrec's type. The count is always unsigned.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000880 const SCEV* CastedMaxBECount =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000881 getTruncateOrZeroExtend(MaxBECount, Start->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +0000882 const SCEV* RecastedMaxBECount =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000883 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType());
884 if (MaxBECount == RecastedMaxBECount) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000885 const Type *WideTy =
886 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000887 // Check whether Start+Step*MaxBECount has no signed overflow.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000888 const SCEV* SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000889 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000890 getTruncateOrSignExtend(Step, Start->getType()));
Owen Andersonecd0cd72009-06-22 21:39:50 +0000891 const SCEV* Add = getAddExpr(Start, SMul);
892 const SCEV* OperandExtendedAdd =
Dan Gohman3bb37f52009-05-18 15:58:39 +0000893 getAddExpr(getSignExtendExpr(Start, WideTy),
894 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
895 getSignExtendExpr(Step, WideTy)));
896 if (getSignExtendExpr(Add, WideTy) == OperandExtendedAdd)
Dan Gohman3ded5b22009-04-29 22:28:28 +0000897 // Return the expression with the addrec on the outside.
898 return getAddRecExpr(getSignExtendExpr(Start, Ty),
899 getSignExtendExpr(Step, Ty),
900 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000901 }
902 }
903 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000904
Owen Andersonc48fbfe2009-06-22 18:25:46 +0000905 SCEVSignExtendExpr *&Result = SCEVSignExtends[std::make_pair(Op, Ty)];
Owen Andersonb70139d2009-06-22 21:57:23 +0000906 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 return Result;
908}
909
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000910/// getAnyExtendExpr - Return a SCEV for the given operand extended with
911/// unspecified bits out to the given type.
912///
Owen Andersonecd0cd72009-06-22 21:39:50 +0000913const SCEV* ScalarEvolution::getAnyExtendExpr(const SCEV* Op,
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000914 const Type *Ty) {
915 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
916 "This is not an extending conversion!");
917 assert(isSCEVable(Ty) &&
918 "This is not a conversion to a SCEVable type!");
919 Ty = getEffectiveSCEVType(Ty);
920
921 // Sign-extend negative constants.
922 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
923 if (SC->getValue()->getValue().isNegative())
924 return getSignExtendExpr(Op, Ty);
925
926 // Peel off a truncate cast.
927 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +0000928 const SCEV* NewOp = T->getOperand();
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000929 if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
930 return getAnyExtendExpr(NewOp, Ty);
931 return getTruncateOrNoop(NewOp, Ty);
932 }
933
934 // Next try a zext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000935 const SCEV* ZExt = getZeroExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000936 if (!isa<SCEVZeroExtendExpr>(ZExt))
937 return ZExt;
938
939 // Next try a sext cast. If the cast is folded, use it.
Owen Andersonecd0cd72009-06-22 21:39:50 +0000940 const SCEV* SExt = getSignExtendExpr(Op, Ty);
Dan Gohmane1ca7e82009-06-13 15:56:47 +0000941 if (!isa<SCEVSignExtendExpr>(SExt))
942 return SExt;
943
944 // If the expression is obviously signed, use the sext cast value.
945 if (isa<SCEVSMaxExpr>(Op))
946 return SExt;
947
948 // Absent any other information, use the zext cast value.
949 return ZExt;
950}
951
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000952/// CollectAddOperandsWithScales - Process the given Ops list, which is
953/// a list of operands to be added under the given scale, update the given
954/// map. This is a helper function for getAddRecExpr. As an example of
955/// what it does, given a sequence of operands that would form an add
956/// expression like this:
957///
958/// m + n + 13 + (A * (o + p + (B * q + m + 29))) + r + (-1 * r)
959///
960/// where A and B are constants, update the map with these values:
961///
962/// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
963///
964/// and add 13 + A*B*29 to AccumulatedConstant.
965/// This will allow getAddRecExpr to produce this:
966///
967/// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
968///
969/// This form often exposes folding opportunities that are hidden in
970/// the original operand list.
971///
972/// Return true iff it appears that any interesting folding opportunities
973/// may be exposed. This helps getAddRecExpr short-circuit extra work in
974/// the common case where no interesting opportunities are present, and
975/// is also used as a check to avoid infinite recursion.
976///
977static bool
Owen Andersonecd0cd72009-06-22 21:39:50 +0000978CollectAddOperandsWithScales(DenseMap<const SCEV*, APInt> &M,
979 SmallVector<const SCEV*, 8> &NewOps,
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000980 APInt &AccumulatedConstant,
Owen Andersonecd0cd72009-06-22 21:39:50 +0000981 const SmallVectorImpl<const SCEV*> &Ops,
Dan Gohman27bd4cb2009-06-14 22:58:51 +0000982 const APInt &Scale,
983 ScalarEvolution &SE) {
984 bool Interesting = false;
985
986 // Iterate over the add operands.
987 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
988 const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
989 if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
990 APInt NewScale =
991 Scale * cast<SCEVConstant>(Mul->getOperand(0))->getValue()->getValue();
992 if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
993 // A multiplication of a constant with another add; recurse.
994 Interesting |=
995 CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
996 cast<SCEVAddExpr>(Mul->getOperand(1))
997 ->getOperands(),
998 NewScale, SE);
999 } else {
1000 // A multiplication of a constant with some other value. Update
1001 // the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001002 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin()+1, Mul->op_end());
1003 const SCEV* Key = SE.getMulExpr(MulOps);
1004 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001005 M.insert(std::make_pair(Key, APInt()));
1006 if (Pair.second) {
1007 Pair.first->second = NewScale;
1008 NewOps.push_back(Pair.first->first);
1009 } else {
1010 Pair.first->second += NewScale;
1011 // The map already had an entry for this value, which may indicate
1012 // a folding opportunity.
1013 Interesting = true;
1014 }
1015 }
1016 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1017 // Pull a buried constant out to the outside.
1018 if (Scale != 1 || AccumulatedConstant != 0 || C->isZero())
1019 Interesting = true;
1020 AccumulatedConstant += Scale * C->getValue()->getValue();
1021 } else {
1022 // An ordinary operand. Update the map.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001023 std::pair<DenseMap<const SCEV*, APInt>::iterator, bool> Pair =
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001024 M.insert(std::make_pair(Ops[i], APInt()));
1025 if (Pair.second) {
1026 Pair.first->second = Scale;
1027 NewOps.push_back(Pair.first->first);
1028 } else {
1029 Pair.first->second += Scale;
1030 // The map already had an entry for this value, which may indicate
1031 // a folding opportunity.
1032 Interesting = true;
1033 }
1034 }
1035 }
1036
1037 return Interesting;
1038}
1039
1040namespace {
1041 struct APIntCompare {
1042 bool operator()(const APInt &LHS, const APInt &RHS) const {
1043 return LHS.ult(RHS);
1044 }
1045 };
1046}
1047
Dan Gohmanc8a29272009-05-24 23:45:28 +00001048/// getAddExpr - Get a canonical add expression, or something simpler if
1049/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001050const SCEV* ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 assert(!Ops.empty() && "Cannot get empty add!");
1052 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001053#ifndef NDEBUG
1054 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1055 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1056 getEffectiveSCEVType(Ops[0]->getType()) &&
1057 "SCEVAddExpr operand types don't match!");
1058#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001059
1060 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001061 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062
1063 // If there are any constants, fold them together.
1064 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001065 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001066 ++Idx;
1067 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001068 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001069 // We found two constants, fold them together!
Dan Gohman02ff9392009-06-14 22:47:23 +00001070 Ops[0] = getConstant(LHSC->getValue()->getValue() +
1071 RHSC->getValue()->getValue());
Dan Gohman68f23e82009-06-14 22:53:57 +00001072 if (Ops.size() == 2) return Ops[0];
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001073 Ops.erase(Ops.begin()+1); // Erase the folded element
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001074 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001075 }
1076
1077 // If we are left with a constant zero being added, strip it off.
1078 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1079 Ops.erase(Ops.begin());
1080 --Idx;
1081 }
1082 }
1083
1084 if (Ops.size() == 1) return Ops[0];
1085
1086 // Okay, check to see if the same value occurs in the operand list twice. If
1087 // so, merge them together into an multiply expression. Since we sorted the
1088 // list, these values are required to be adjacent.
1089 const Type *Ty = Ops[0]->getType();
1090 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1091 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
1092 // Found a match, merge the two values into a multiply, and add any
1093 // remaining values to the result.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001094 const SCEV* Two = getIntegerSCEV(2, Ty);
1095 const SCEV* Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001096 if (Ops.size() == 2)
1097 return Mul;
1098 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
1099 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +00001100 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 }
1102
Dan Gohman45b3b542009-05-08 21:03:19 +00001103 // Check for truncates. If all the operands are truncated from the same
1104 // type, see if factoring out the truncate would permit the result to be
1105 // folded. eg., trunc(x) + m*trunc(n) --> trunc(x + trunc(m)*n)
1106 // if the contents of the resulting outer trunc fold to something simple.
1107 for (; Idx < Ops.size() && isa<SCEVTruncateExpr>(Ops[Idx]); ++Idx) {
1108 const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(Ops[Idx]);
1109 const Type *DstType = Trunc->getType();
1110 const Type *SrcType = Trunc->getOperand()->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00001111 SmallVector<const SCEV*, 8> LargeOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001112 bool Ok = true;
1113 // Check all the operands to see if they can be represented in the
1114 // source type of the truncate.
1115 for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
1116 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
1117 if (T->getOperand()->getType() != SrcType) {
1118 Ok = false;
1119 break;
1120 }
1121 LargeOps.push_back(T->getOperand());
1122 } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
1123 // This could be either sign or zero extension, but sign extension
1124 // is much more likely to be foldable here.
1125 LargeOps.push_back(getSignExtendExpr(C, SrcType));
1126 } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001127 SmallVector<const SCEV*, 8> LargeMulOps;
Dan Gohman45b3b542009-05-08 21:03:19 +00001128 for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
1129 if (const SCEVTruncateExpr *T =
1130 dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
1131 if (T->getOperand()->getType() != SrcType) {
1132 Ok = false;
1133 break;
1134 }
1135 LargeMulOps.push_back(T->getOperand());
1136 } else if (const SCEVConstant *C =
1137 dyn_cast<SCEVConstant>(M->getOperand(j))) {
1138 // This could be either sign or zero extension, but sign extension
1139 // is much more likely to be foldable here.
1140 LargeMulOps.push_back(getSignExtendExpr(C, SrcType));
1141 } else {
1142 Ok = false;
1143 break;
1144 }
1145 }
1146 if (Ok)
1147 LargeOps.push_back(getMulExpr(LargeMulOps));
1148 } else {
1149 Ok = false;
1150 break;
1151 }
1152 }
1153 if (Ok) {
1154 // Evaluate the expression in the larger type.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001155 const SCEV* Fold = getAddExpr(LargeOps);
Dan Gohman45b3b542009-05-08 21:03:19 +00001156 // If it folds to something simple, use it. Otherwise, don't.
1157 if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
1158 return getTruncateExpr(Fold, DstType);
1159 }
1160 }
1161
1162 // Skip past any other cast SCEVs.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
1164 ++Idx;
1165
1166 // If there are add operands they would be next.
1167 if (Idx < Ops.size()) {
1168 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001169 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001170 // If we have an add, expand the add operands onto the end of the operands
1171 // list.
1172 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
1173 Ops.erase(Ops.begin()+Idx);
1174 DeletedAdd = true;
1175 }
1176
1177 // If we deleted at least one add, we added operands to the end of the list,
1178 // and they are not necessarily sorted. Recurse to resort and resimplify
1179 // any operands we just aquired.
1180 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +00001181 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001182 }
1183
1184 // Skip over the add expression until we get to a multiply.
1185 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1186 ++Idx;
1187
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001188 // Check to see if there are any folding opportunities present with
1189 // operands multiplied by constant values.
1190 if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
1191 uint64_t BitWidth = getTypeSizeInBits(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001192 DenseMap<const SCEV*, APInt> M;
1193 SmallVector<const SCEV*, 8> NewOps;
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001194 APInt AccumulatedConstant(BitWidth, 0);
1195 if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
1196 Ops, APInt(BitWidth, 1), *this)) {
1197 // Some interesting folding opportunity is present, so its worthwhile to
1198 // re-generate the operands list. Group the operands by constant scale,
1199 // to avoid multiplying by the same constant scale multiple times.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001200 std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare> MulOpLists;
1201 for (SmallVector<const SCEV*, 8>::iterator I = NewOps.begin(),
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001202 E = NewOps.end(); I != E; ++I)
1203 MulOpLists[M.find(*I)->second].push_back(*I);
1204 // Re-generate the operands list.
1205 Ops.clear();
1206 if (AccumulatedConstant != 0)
1207 Ops.push_back(getConstant(AccumulatedConstant));
Owen Andersonecd0cd72009-06-22 21:39:50 +00001208 for (std::map<APInt, SmallVector<const SCEV*, 4>, APIntCompare>::iterator I =
Dan Gohman27bd4cb2009-06-14 22:58:51 +00001209 MulOpLists.begin(), E = MulOpLists.end(); I != E; ++I)
1210 if (I->first != 0)
1211 Ops.push_back(getMulExpr(getConstant(I->first), getAddExpr(I->second)));
1212 if (Ops.empty())
1213 return getIntegerSCEV(0, Ty);
1214 if (Ops.size() == 1)
1215 return Ops[0];
1216 return getAddExpr(Ops);
1217 }
1218 }
1219
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 // If we are adding something to a multiply expression, make sure the
1221 // something is not already an operand of the multiply. If so, merge it into
1222 // the multiply.
1223 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001224 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001225 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001226 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001227 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Dan Gohman02ff9392009-06-14 22:47:23 +00001228 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(Ops[AddOp])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001229 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001230 const SCEV* InnerMul = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 if (Mul->getNumOperands() != 2) {
1232 // If the multiply has more than two operands, we must get the
1233 // Y*Z term.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001234 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001236 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001237 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001238 const SCEV* One = getIntegerSCEV(1, Ty);
1239 const SCEV* AddOne = getAddExpr(InnerMul, One);
1240 const SCEV* OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001241 if (Ops.size() == 2) return OuterMul;
1242 if (AddOp < Idx) {
1243 Ops.erase(Ops.begin()+AddOp);
1244 Ops.erase(Ops.begin()+Idx-1);
1245 } else {
1246 Ops.erase(Ops.begin()+Idx);
1247 Ops.erase(Ops.begin()+AddOp-1);
1248 }
1249 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001250 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 }
1252
1253 // Check this multiply against other multiplies being added together.
1254 for (unsigned OtherMulIdx = Idx+1;
1255 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1256 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001257 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001258 // If MulOp occurs in OtherMul, we can fold the two multiplies
1259 // together.
1260 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1261 OMulOp != e; ++OMulOp)
1262 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1263 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
Owen Andersonecd0cd72009-06-22 21:39:50 +00001264 const SCEV* InnerMul1 = Mul->getOperand(MulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001265 if (Mul->getNumOperands() != 2) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001266 SmallVector<const SCEV*, 4> MulOps(Mul->op_begin(), Mul->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001268 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001269 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001270 const SCEV* InnerMul2 = OtherMul->getOperand(OMulOp == 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001271 if (OtherMul->getNumOperands() != 2) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001272 SmallVector<const SCEV*, 4> MulOps(OtherMul->op_begin(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 OtherMul->op_end());
1274 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001275 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001276 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001277 const SCEV* InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1278 const SCEV* OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001279 if (Ops.size() == 2) return OuterMul;
1280 Ops.erase(Ops.begin()+Idx);
1281 Ops.erase(Ops.begin()+OtherMulIdx-1);
1282 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001283 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001284 }
1285 }
1286 }
1287 }
1288
1289 // If there are any add recurrences in the operands list, see if any other
1290 // added values are loop invariant. If so, we can fold them into the
1291 // recurrence.
1292 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1293 ++Idx;
1294
1295 // Scan over all recurrences, trying to fold loop invariants into them.
1296 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1297 // Scan all of the other operands to this add and add them to the vector if
1298 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001299 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001300 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001301 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1302 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1303 LIOps.push_back(Ops[i]);
1304 Ops.erase(Ops.begin()+i);
1305 --i; --e;
1306 }
1307
1308 // If we found some loop invariants, fold them into the recurrence.
1309 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001310 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001311 LIOps.push_back(AddRec->getStart());
1312
Owen Andersonecd0cd72009-06-22 21:39:50 +00001313 SmallVector<const SCEV*, 4> AddRecOps(AddRec->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001314 AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001315 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316
Owen Andersonecd0cd72009-06-22 21:39:50 +00001317 const SCEV* NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 // If all of the other operands were loop invariant, we are done.
1319 if (Ops.size() == 1) return NewRec;
1320
1321 // Otherwise, add the folded AddRec by the non-liv parts.
1322 for (unsigned i = 0;; ++i)
1323 if (Ops[i] == AddRec) {
1324 Ops[i] = NewRec;
1325 break;
1326 }
Dan Gohman89f85052007-10-22 18:31:58 +00001327 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001328 }
1329
1330 // Okay, if there weren't any loop invariants to be folded, check to see if
1331 // there are multiple AddRec's with the same loop induction variable being
1332 // added together. If so, we can fold them.
1333 for (unsigned OtherIdx = Idx+1;
1334 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1335 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001336 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001337 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1338 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
Owen Andersonecd0cd72009-06-22 21:39:50 +00001339 SmallVector<const SCEV*, 4> NewOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1341 if (i >= NewOps.size()) {
1342 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1343 OtherAddRec->op_end());
1344 break;
1345 }
Dan Gohman89f85052007-10-22 18:31:58 +00001346 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 }
Owen Andersonecd0cd72009-06-22 21:39:50 +00001348 const SCEV* NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349
1350 if (Ops.size() == 2) return NewAddRec;
1351
1352 Ops.erase(Ops.begin()+Idx);
1353 Ops.erase(Ops.begin()+OtherIdx-1);
1354 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001355 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001356 }
1357 }
1358
1359 // Otherwise couldn't fold anything into this recurrence. Move onto the
1360 // next one.
1361 }
1362
1363 // Okay, it looks like we really DO need an add expr. Check to see if we
1364 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001365 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001366 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scAddExpr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001368 if (Result == 0) Result = new SCEVAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001369 return Result;
1370}
1371
1372
Dan Gohmanc8a29272009-05-24 23:45:28 +00001373/// getMulExpr - Get a canonical multiply expression, or something simpler if
1374/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001375const SCEV* ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV*> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001376 assert(!Ops.empty() && "Cannot get empty mul!");
Dan Gohmana77b3d42009-05-18 15:44:58 +00001377#ifndef NDEBUG
1378 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1379 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1380 getEffectiveSCEVType(Ops[0]->getType()) &&
1381 "SCEVMulExpr operand types don't match!");
1382#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383
1384 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001385 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386
1387 // If there are any constants, fold them together.
1388 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001389 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390
1391 // C1*(C2+V) -> C1*C2 + C1*V
1392 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001393 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 if (Add->getNumOperands() == 2 &&
1395 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001396 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1397 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001398
1399
1400 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001401 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001403 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1404 RHSC->getValue()->getValue());
1405 Ops[0] = getConstant(Fold);
1406 Ops.erase(Ops.begin()+1); // Erase the folded element
1407 if (Ops.size() == 1) return Ops[0];
1408 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001409 }
1410
1411 // If we are left with a constant one being multiplied, strip it off.
1412 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1413 Ops.erase(Ops.begin());
1414 --Idx;
1415 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1416 // If we have a multiply of zero, it will always be zero.
1417 return Ops[0];
1418 }
1419 }
1420
1421 // Skip over the add expression until we get to a multiply.
1422 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1423 ++Idx;
1424
1425 if (Ops.size() == 1)
1426 return Ops[0];
1427
1428 // If there are mul operands inline them all into this expression.
1429 if (Idx < Ops.size()) {
1430 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001431 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001432 // If we have an mul, expand the mul operands onto the end of the operands
1433 // list.
1434 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1435 Ops.erase(Ops.begin()+Idx);
1436 DeletedMul = true;
1437 }
1438
1439 // If we deleted at least one mul, we added operands to the end of the list,
1440 // and they are not necessarily sorted. Recurse to resort and resimplify
1441 // any operands we just aquired.
1442 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001443 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444 }
1445
1446 // If there are any add recurrences in the operands list, see if any other
1447 // added values are loop invariant. If so, we can fold them into the
1448 // recurrence.
1449 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1450 ++Idx;
1451
1452 // Scan over all recurrences, trying to fold loop invariants into them.
1453 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1454 // Scan all of the other operands to this mul and add them to the vector if
1455 // they are loop invariant w.r.t. the recurrence.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001456 SmallVector<const SCEV*, 8> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001457 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1459 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1460 LIOps.push_back(Ops[i]);
1461 Ops.erase(Ops.begin()+i);
1462 --i; --e;
1463 }
1464
1465 // If we found some loop invariants, fold them into the recurrence.
1466 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001467 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Owen Andersonecd0cd72009-06-22 21:39:50 +00001468 SmallVector<const SCEV*, 4> NewOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001469 NewOps.reserve(AddRec->getNumOperands());
1470 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001471 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001473 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001474 } else {
1475 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001476 SmallVector<const SCEV*, 4> MulOps(LIOps.begin(), LIOps.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001477 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001478 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479 }
1480 }
1481
Owen Andersonecd0cd72009-06-22 21:39:50 +00001482 const SCEV* NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483
1484 // If all of the other operands were loop invariant, we are done.
1485 if (Ops.size() == 1) return NewRec;
1486
1487 // Otherwise, multiply the folded AddRec by the non-liv parts.
1488 for (unsigned i = 0;; ++i)
1489 if (Ops[i] == AddRec) {
1490 Ops[i] = NewRec;
1491 break;
1492 }
Dan Gohman89f85052007-10-22 18:31:58 +00001493 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001494 }
1495
1496 // Okay, if there weren't any loop invariants to be folded, check to see if
1497 // there are multiple AddRec's with the same loop induction variable being
1498 // multiplied together. If so, we can fold them.
1499 for (unsigned OtherIdx = Idx+1;
1500 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1501 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001502 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1504 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001505 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001506 const SCEV* NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001507 G->getStart());
Owen Andersonecd0cd72009-06-22 21:39:50 +00001508 const SCEV* B = F->getStepRecurrence(*this);
1509 const SCEV* D = G->getStepRecurrence(*this);
1510 const SCEV* NewStep = getAddExpr(getMulExpr(F, D),
Dan Gohman89f85052007-10-22 18:31:58 +00001511 getMulExpr(G, B),
1512 getMulExpr(B, D));
Owen Andersonecd0cd72009-06-22 21:39:50 +00001513 const SCEV* NewAddRec = getAddRecExpr(NewStart, NewStep,
Dan Gohman89f85052007-10-22 18:31:58 +00001514 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 if (Ops.size() == 2) return NewAddRec;
1516
1517 Ops.erase(Ops.begin()+Idx);
1518 Ops.erase(Ops.begin()+OtherIdx-1);
1519 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001520 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001521 }
1522 }
1523
1524 // Otherwise couldn't fold anything into this recurrence. Move onto the
1525 // next one.
1526 }
1527
1528 // Okay, it looks like we really DO need an mul expr. Check to see if we
1529 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001530 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001531 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scMulExpr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001532 SCEVOps)];
1533 if (Result == 0)
Owen Andersonb70139d2009-06-22 21:57:23 +00001534 Result = new SCEVMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001535 return Result;
1536}
1537
Dan Gohmanc8a29272009-05-24 23:45:28 +00001538/// getUDivExpr - Get a canonical multiply expression, or something simpler if
1539/// possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001540const SCEV* ScalarEvolution::getUDivExpr(const SCEV* LHS,
1541 const SCEV* RHS) {
Dan Gohmana77b3d42009-05-18 15:44:58 +00001542 assert(getEffectiveSCEVType(LHS->getType()) ==
1543 getEffectiveSCEVType(RHS->getType()) &&
1544 "SCEVUDivExpr operand types don't match!");
1545
Dan Gohmanc76b5452009-05-04 22:02:23 +00001546 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001547 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001548 return LHS; // X udiv 1 --> x
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001549 if (RHSC->isZero())
1550 return getIntegerSCEV(0, LHS->getType()); // value is undefined
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001552 // Determine if the division can be folded into the operands of
1553 // its operands.
1554 // TODO: Generalize this to non-constants by using known-bits information.
1555 const Type *Ty = LHS->getType();
1556 unsigned LZ = RHSC->getValue()->getValue().countLeadingZeros();
1557 unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ;
1558 // For non-power-of-two values, effectively round the value up to the
1559 // nearest power of two.
1560 if (!RHSC->getValue()->getValue().isPowerOf2())
1561 ++MaxShiftAmt;
1562 const IntegerType *ExtTy =
1563 IntegerType::get(getTypeSizeInBits(Ty) + MaxShiftAmt);
1564 // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
1565 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
1566 if (const SCEVConstant *Step =
1567 dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this)))
1568 if (!Step->getValue()->getValue()
1569 .urem(RHSC->getValue()->getValue()) &&
Dan Gohman14374d32009-05-08 23:11:16 +00001570 getZeroExtendExpr(AR, ExtTy) ==
1571 getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
1572 getZeroExtendExpr(Step, ExtTy),
1573 AR->getLoop())) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001574 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001575 for (unsigned i = 0, e = AR->getNumOperands(); i != e; ++i)
1576 Operands.push_back(getUDivExpr(AR->getOperand(i), RHS));
1577 return getAddRecExpr(Operands, AR->getLoop());
1578 }
1579 // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001580 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001581 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001582 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i)
1583 Operands.push_back(getZeroExtendExpr(M->getOperand(i), ExtTy));
1584 if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001585 // Find an operand that's safely divisible.
1586 for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001587 const SCEV* Op = M->getOperand(i);
1588 const SCEV* Div = getUDivExpr(Op, RHSC);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001589 if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001590 const SmallVectorImpl<const SCEV*> &MOperands = M->getOperands();
1591 Operands = SmallVector<const SCEV*, 4>(MOperands.begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001592 MOperands.end());
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001593 Operands[i] = Div;
1594 return getMulExpr(Operands);
1595 }
1596 }
Dan Gohman14374d32009-05-08 23:11:16 +00001597 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001598 // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
Dan Gohman14374d32009-05-08 23:11:16 +00001599 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(LHS)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001600 SmallVector<const SCEV*, 4> Operands;
Dan Gohman14374d32009-05-08 23:11:16 +00001601 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i)
1602 Operands.push_back(getZeroExtendExpr(A->getOperand(i), ExtTy));
1603 if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
1604 Operands.clear();
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001605 for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001606 const SCEV* Op = getUDivExpr(A->getOperand(i), RHS);
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001607 if (isa<SCEVUDivExpr>(Op) || getMulExpr(Op, RHS) != A->getOperand(i))
1608 break;
1609 Operands.push_back(Op);
1610 }
1611 if (Operands.size() == A->getNumOperands())
1612 return getAddExpr(Operands);
1613 }
Dan Gohman14374d32009-05-08 23:11:16 +00001614 }
Dan Gohmanaf0a1512009-05-08 20:18:49 +00001615
1616 // Fold if both operands are constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001617 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001618 Constant *LHSCV = LHSC->getValue();
1619 Constant *RHSCV = RHSC->getValue();
Dan Gohman55788cf2009-06-24 00:38:39 +00001620 return getConstant(cast<ConstantInt>(ConstantExpr::getUDiv(LHSCV,
1621 RHSCV)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001622 }
1623 }
1624
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001625 SCEVUDivExpr *&Result = SCEVUDivs[std::make_pair(LHS, RHS)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001626 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001627 return Result;
1628}
1629
1630
Dan Gohmanc8a29272009-05-24 23:45:28 +00001631/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1632/// Simplify the expression as much as possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001633const SCEV* ScalarEvolution::getAddRecExpr(const SCEV* Start,
1634 const SCEV* Step, const Loop *L) {
1635 SmallVector<const SCEV*, 4> Operands;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001636 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001637 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001638 if (StepChrec->getLoop() == L) {
1639 Operands.insert(Operands.end(), StepChrec->op_begin(),
1640 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001641 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001642 }
1643
1644 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001645 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001646}
1647
Dan Gohmanc8a29272009-05-24 23:45:28 +00001648/// getAddRecExpr - Get an add recurrence expression for the specified loop.
1649/// Simplify the expression as much as possible.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001650const SCEV* ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV*> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001651 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001652 if (Operands.size() == 1) return Operands[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001653#ifndef NDEBUG
1654 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
1655 assert(getEffectiveSCEVType(Operands[i]->getType()) ==
1656 getEffectiveSCEVType(Operands[0]->getType()) &&
1657 "SCEVAddRecExpr operand types don't match!");
1658#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001659
Dan Gohman7b560c42008-06-18 16:23:07 +00001660 if (Operands.back()->isZero()) {
1661 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001662 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001663 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001664
Dan Gohman42936882008-08-08 18:33:12 +00001665 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001666 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001667 const Loop* NestedLoop = NestedAR->getLoop();
1668 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00001669 SmallVector<const SCEV*, 4> NestedOperands(NestedAR->op_begin(),
Dan Gohman02ff9392009-06-14 22:47:23 +00001670 NestedAR->op_end());
Dan Gohman42936882008-08-08 18:33:12 +00001671 Operands[0] = NestedAR->getStart();
1672 NestedOperands[0] = getAddRecExpr(Operands, L);
1673 return getAddRecExpr(NestedOperands, NestedLoop);
1674 }
1675 }
1676
Dan Gohmanbff6b582009-05-04 22:30:44 +00001677 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001678 SCEVAddRecExpr *&Result = SCEVAddRecExprs[std::make_pair(L, SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001679 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 return Result;
1681}
1682
Owen Andersonecd0cd72009-06-22 21:39:50 +00001683const SCEV* ScalarEvolution::getSMaxExpr(const SCEV* LHS,
1684 const SCEV* RHS) {
1685 SmallVector<const SCEV*, 2> Ops;
Nick Lewycky711640a2007-11-25 22:41:31 +00001686 Ops.push_back(LHS);
1687 Ops.push_back(RHS);
1688 return getSMaxExpr(Ops);
1689}
1690
Owen Andersonecd0cd72009-06-22 21:39:50 +00001691const SCEV*
1692ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001693 assert(!Ops.empty() && "Cannot get empty smax!");
1694 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001695#ifndef NDEBUG
1696 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1697 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1698 getEffectiveSCEVType(Ops[0]->getType()) &&
1699 "SCEVSMaxExpr operand types don't match!");
1700#endif
Nick Lewycky711640a2007-11-25 22:41:31 +00001701
1702 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001703 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001704
1705 // If there are any constants, fold them together.
1706 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001707 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001708 ++Idx;
1709 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001710 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001711 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001712 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001713 APIntOps::smax(LHSC->getValue()->getValue(),
1714 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001715 Ops[0] = getConstant(Fold);
1716 Ops.erase(Ops.begin()+1); // Erase the folded element
1717 if (Ops.size() == 1) return Ops[0];
1718 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001719 }
1720
1721 // If we are left with a constant -inf, strip it off.
1722 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1723 Ops.erase(Ops.begin());
1724 --Idx;
1725 }
1726 }
1727
1728 if (Ops.size() == 1) return Ops[0];
1729
1730 // Find the first SMax
1731 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1732 ++Idx;
1733
1734 // Check to see if one of the operands is an SMax. If so, expand its operands
1735 // onto our operand list, and recurse to simplify.
1736 if (Idx < Ops.size()) {
1737 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001738 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001739 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1740 Ops.erase(Ops.begin()+Idx);
1741 DeletedSMax = true;
1742 }
1743
1744 if (DeletedSMax)
1745 return getSMaxExpr(Ops);
1746 }
1747
1748 // Okay, check to see if the same value occurs in the operand list twice. If
1749 // so, delete one. Since we sorted the list, these values are required to
1750 // be adjacent.
1751 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1752 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1753 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1754 --i; --e;
1755 }
1756
1757 if (Ops.size() == 1) return Ops[0];
1758
1759 assert(!Ops.empty() && "Reduced smax down to nothing!");
1760
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001761 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001762 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001763 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001764 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scSMaxExpr,
Nick Lewycky711640a2007-11-25 22:41:31 +00001765 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001766 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
Nick Lewycky711640a2007-11-25 22:41:31 +00001767 return Result;
1768}
1769
Owen Andersonecd0cd72009-06-22 21:39:50 +00001770const SCEV* ScalarEvolution::getUMaxExpr(const SCEV* LHS,
1771 const SCEV* RHS) {
1772 SmallVector<const SCEV*, 2> Ops;
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001773 Ops.push_back(LHS);
1774 Ops.push_back(RHS);
1775 return getUMaxExpr(Ops);
1776}
1777
Owen Andersonecd0cd72009-06-22 21:39:50 +00001778const SCEV*
1779ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV*> &Ops) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001780 assert(!Ops.empty() && "Cannot get empty umax!");
1781 if (Ops.size() == 1) return Ops[0];
Dan Gohmana77b3d42009-05-18 15:44:58 +00001782#ifndef NDEBUG
1783 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
1784 assert(getEffectiveSCEVType(Ops[i]->getType()) ==
1785 getEffectiveSCEVType(Ops[0]->getType()) &&
1786 "SCEVUMaxExpr operand types don't match!");
1787#endif
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001788
1789 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001790 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001791
1792 // If there are any constants, fold them together.
1793 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001794 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001795 ++Idx;
1796 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001797 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001798 // We found two constants, fold them together!
1799 ConstantInt *Fold = ConstantInt::get(
1800 APIntOps::umax(LHSC->getValue()->getValue(),
1801 RHSC->getValue()->getValue()));
1802 Ops[0] = getConstant(Fold);
1803 Ops.erase(Ops.begin()+1); // Erase the folded element
1804 if (Ops.size() == 1) return Ops[0];
1805 LHSC = cast<SCEVConstant>(Ops[0]);
1806 }
1807
1808 // If we are left with a constant zero, strip it off.
1809 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1810 Ops.erase(Ops.begin());
1811 --Idx;
1812 }
1813 }
1814
1815 if (Ops.size() == 1) return Ops[0];
1816
1817 // Find the first UMax
1818 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1819 ++Idx;
1820
1821 // Check to see if one of the operands is a UMax. If so, expand its operands
1822 // onto our operand list, and recurse to simplify.
1823 if (Idx < Ops.size()) {
1824 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001825 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001826 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1827 Ops.erase(Ops.begin()+Idx);
1828 DeletedUMax = true;
1829 }
1830
1831 if (DeletedUMax)
1832 return getUMaxExpr(Ops);
1833 }
1834
1835 // Okay, check to see if the same value occurs in the operand list twice. If
1836 // so, delete one. Since we sorted the list, these values are required to
1837 // be adjacent.
1838 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1839 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1840 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1841 --i; --e;
1842 }
1843
1844 if (Ops.size() == 1) return Ops[0];
1845
1846 assert(!Ops.empty() && "Reduced umax down to nothing!");
1847
1848 // Okay, it looks like we really DO need a umax expr. Check to see if we
1849 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001850 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001851 SCEVCommutativeExpr *&Result = SCEVCommExprs[std::make_pair(scUMaxExpr,
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001852 SCEVOps)];
Owen Andersonb70139d2009-06-22 21:57:23 +00001853 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001854 return Result;
1855}
1856
Owen Andersonecd0cd72009-06-22 21:39:50 +00001857const SCEV* ScalarEvolution::getSMinExpr(const SCEV* LHS,
1858 const SCEV* RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001859 // ~smax(~x, ~y) == smin(x, y).
1860 return getNotSCEV(getSMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1861}
1862
Owen Andersonecd0cd72009-06-22 21:39:50 +00001863const SCEV* ScalarEvolution::getUMinExpr(const SCEV* LHS,
1864 const SCEV* RHS) {
Dan Gohmand01fff82009-06-22 03:18:45 +00001865 // ~umax(~x, ~y) == umin(x, y)
1866 return getNotSCEV(getUMaxExpr(getNotSCEV(LHS), getNotSCEV(RHS)));
1867}
1868
Owen Andersonecd0cd72009-06-22 21:39:50 +00001869const SCEV* ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001870 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001871 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001872 if (isa<ConstantPointerNull>(V))
1873 return getIntegerSCEV(0, V->getType());
Owen Andersonc48fbfe2009-06-22 18:25:46 +00001874 SCEVUnknown *&Result = SCEVUnknowns[V];
Owen Andersonb70139d2009-06-22 21:57:23 +00001875 if (Result == 0) Result = new SCEVUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001876 return Result;
1877}
1878
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880// Basic SCEV Analysis and PHI Idiom Recognition Code
1881//
1882
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001883/// isSCEVable - Test if values of the given type are analyzable within
1884/// the SCEV framework. This primarily includes integer types, and it
1885/// can optionally include pointer types if the ScalarEvolution class
1886/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001887bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001888 // Integers are always SCEVable.
1889 if (Ty->isInteger())
1890 return true;
1891
1892 // Pointers are SCEVable if TargetData information is available
1893 // to provide pointer size information.
1894 if (isa<PointerType>(Ty))
1895 return TD != NULL;
1896
1897 // Otherwise it's not SCEVable.
1898 return false;
1899}
1900
1901/// getTypeSizeInBits - Return the size in bits of the specified type,
1902/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001903uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001904 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1905
1906 // If we have a TargetData, use it!
1907 if (TD)
1908 return TD->getTypeSizeInBits(Ty);
1909
1910 // Otherwise, we support only integer types.
1911 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1912 return Ty->getPrimitiveSizeInBits();
1913}
1914
1915/// getEffectiveSCEVType - Return a type with the same bitwidth as
1916/// the given type and which represents how SCEV will treat the given
1917/// type, for which isSCEVable must return true. For pointer types,
1918/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001919const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001920 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1921
1922 if (Ty->isInteger())
1923 return Ty;
1924
1925 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1926 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001927}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928
Owen Andersonecd0cd72009-06-22 21:39:50 +00001929const SCEV* ScalarEvolution::getCouldNotCompute() {
Dan Gohman0c850912009-06-06 14:37:11 +00001930 return CouldNotCompute;
Dan Gohman0ad08b02009-04-18 17:58:19 +00001931}
1932
Dan Gohmand83d4af2009-05-04 22:20:30 +00001933/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001934/// computed.
1935bool ScalarEvolution::hasSCEV(Value *V) const {
1936 return Scalars.count(V);
1937}
1938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001939/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1940/// expression and create a new one.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001941const SCEV* ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001942 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001943
Owen Andersonecd0cd72009-06-22 21:39:50 +00001944 std::map<SCEVCallbackVH, const SCEV*>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001945 if (I != Scalars.end()) return I->second;
Owen Andersonecd0cd72009-06-22 21:39:50 +00001946 const SCEV* S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001947 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001948 return S;
1949}
1950
Dan Gohman01c2ee72009-04-16 03:18:22 +00001951/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1952/// specified signed integer value and return a SCEV for the constant.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001953const SCEV* ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001954 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001955 Constant *C;
1956 if (Val == 0)
1957 C = Constant::getNullValue(Ty);
1958 else if (Ty->isFloatingPoint())
1959 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1960 APFloat::IEEEdouble, Val));
1961 else
1962 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001963 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001964}
1965
1966/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1967///
Owen Andersonecd0cd72009-06-22 21:39:50 +00001968const SCEV* ScalarEvolution::getNegativeSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001969 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001970 return getConstant(cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001971
1972 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001973 Ty = getEffectiveSCEVType(Ty);
1974 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001975}
1976
1977/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Owen Andersonecd0cd72009-06-22 21:39:50 +00001978const SCEV* ScalarEvolution::getNotSCEV(const SCEV* V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001979 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman55788cf2009-06-24 00:38:39 +00001980 return getConstant(cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001981
1982 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001983 Ty = getEffectiveSCEVType(Ty);
Owen Andersonecd0cd72009-06-22 21:39:50 +00001984 const SCEV* AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001985 return getMinusSCEV(AllOnes, V);
1986}
1987
1988/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1989///
Owen Andersonecd0cd72009-06-22 21:39:50 +00001990const SCEV* ScalarEvolution::getMinusSCEV(const SCEV* LHS,
1991 const SCEV* RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001992 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001993 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001994}
1995
1996/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1997/// input value to the specified type. If the type must be extended, it is zero
1998/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00001999const SCEV*
2000ScalarEvolution::getTruncateOrZeroExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002001 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002002 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002003 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2004 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002005 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002006 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002007 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002008 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002009 return getTruncateExpr(V, Ty);
2010 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002011}
2012
2013/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
2014/// input value to the specified type. If the type must be extended, it is sign
2015/// extended.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002016const SCEV*
2017ScalarEvolution::getTruncateOrSignExtend(const SCEV* V,
Nick Lewycky37d04642009-04-23 05:15:08 +00002018 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00002019 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002020 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2021 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00002022 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002023 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00002024 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002025 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002026 return getTruncateExpr(V, Ty);
2027 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002028}
2029
Dan Gohmanac959332009-05-13 03:46:30 +00002030/// getNoopOrZeroExtend - Return a SCEV corresponding to a conversion of the
2031/// input value to the specified type. If the type must be extended, it is zero
2032/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002033const SCEV*
2034ScalarEvolution::getNoopOrZeroExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002035 const Type *SrcTy = V->getType();
2036 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2037 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2038 "Cannot noop or zero extend with non-integer arguments!");
2039 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2040 "getNoopOrZeroExtend cannot truncate!");
2041 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2042 return V; // No conversion
2043 return getZeroExtendExpr(V, Ty);
2044}
2045
2046/// getNoopOrSignExtend - Return a SCEV corresponding to a conversion of the
2047/// input value to the specified type. If the type must be extended, it is sign
2048/// extended. The conversion must not be narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002049const SCEV*
2050ScalarEvolution::getNoopOrSignExtend(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002051 const Type *SrcTy = V->getType();
2052 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2053 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2054 "Cannot noop or sign extend with non-integer arguments!");
2055 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2056 "getNoopOrSignExtend cannot truncate!");
2057 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2058 return V; // No conversion
2059 return getSignExtendExpr(V, Ty);
2060}
2061
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002062/// getNoopOrAnyExtend - Return a SCEV corresponding to a conversion of
2063/// the input value to the specified type. If the type must be extended,
2064/// it is extended with unspecified bits. The conversion must not be
2065/// narrowing.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002066const SCEV*
2067ScalarEvolution::getNoopOrAnyExtend(const SCEV* V, const Type *Ty) {
Dan Gohmane1ca7e82009-06-13 15:56:47 +00002068 const Type *SrcTy = V->getType();
2069 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2070 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2071 "Cannot noop or any extend with non-integer arguments!");
2072 assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
2073 "getNoopOrAnyExtend cannot truncate!");
2074 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2075 return V; // No conversion
2076 return getAnyExtendExpr(V, Ty);
2077}
2078
Dan Gohmanac959332009-05-13 03:46:30 +00002079/// getTruncateOrNoop - Return a SCEV corresponding to a conversion of the
2080/// input value to the specified type. The conversion must not be widening.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002081const SCEV*
2082ScalarEvolution::getTruncateOrNoop(const SCEV* V, const Type *Ty) {
Dan Gohmanac959332009-05-13 03:46:30 +00002083 const Type *SrcTy = V->getType();
2084 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
2085 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
2086 "Cannot truncate or noop with non-integer arguments!");
2087 assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
2088 "getTruncateOrNoop cannot extend!");
2089 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
2090 return V; // No conversion
2091 return getTruncateExpr(V, Ty);
2092}
2093
Dan Gohman8e8b5232009-06-22 00:31:57 +00002094/// getUMaxFromMismatchedTypes - Promote the operands to the wider of
2095/// the types using zero-extension, and then perform a umax operation
2096/// with them.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002097const SCEV* ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV* LHS,
2098 const SCEV* RHS) {
2099 const SCEV* PromotedLHS = LHS;
2100 const SCEV* PromotedRHS = RHS;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002101
2102 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2103 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2104 else
2105 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2106
2107 return getUMaxExpr(PromotedLHS, PromotedRHS);
2108}
2109
Dan Gohman9e62bb02009-06-22 15:03:27 +00002110/// getUMinFromMismatchedTypes - Promote the operands to the wider of
2111/// the types using zero-extension, and then perform a umin operation
2112/// with them.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002113const SCEV* ScalarEvolution::getUMinFromMismatchedTypes(const SCEV* LHS,
2114 const SCEV* RHS) {
2115 const SCEV* PromotedLHS = LHS;
2116 const SCEV* PromotedRHS = RHS;
Dan Gohman9e62bb02009-06-22 15:03:27 +00002117
2118 if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
2119 PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
2120 else
2121 PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
2122
2123 return getUMinExpr(PromotedLHS, PromotedRHS);
2124}
2125
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002126/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
2127/// the specified instruction and replaces any references to the symbolic value
2128/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002129void ScalarEvolution::
Owen Andersonecd0cd72009-06-22 21:39:50 +00002130ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEV* SymName,
2131 const SCEV* NewVal) {
2132 std::map<SCEVCallbackVH, const SCEV*>::iterator SI =
Dan Gohmanbff6b582009-05-04 22:30:44 +00002133 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002134 if (SI == Scalars.end()) return;
2135
Owen Andersonecd0cd72009-06-22 21:39:50 +00002136 const SCEV* NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002137 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002138 if (NV == SI->second) return; // No change.
2139
2140 SI->second = NV; // Update the scalars map!
2141
2142 // Any instruction values that use this instruction might also need to be
2143 // updated!
2144 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2145 UI != E; ++UI)
2146 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
2147}
2148
2149/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
2150/// a loop header, making it a potential recurrence, or it doesn't.
2151///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002152const SCEV* ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002153 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002154 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002155 if (L->getHeader() == PN->getParent()) {
2156 // If it lives in the loop header, it has two incoming values, one
2157 // from outside the loop, and one from inside.
2158 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
2159 unsigned BackEdge = IncomingEdge^1;
2160
2161 // While we are analyzing this PHI node, handle its value symbolically.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002162 const SCEV* SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163 assert(Scalars.find(PN) == Scalars.end() &&
2164 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002165 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002166
2167 // Using this symbolic name for the PHI, analyze the value coming around
2168 // the back-edge.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002169 const SCEV* BEValue = getSCEV(PN->getIncomingValue(BackEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002170
2171 // NOTE: If BEValue is loop invariant, we know that the PHI node just
2172 // has a special value for the first iteration of the loop.
2173
2174 // If the value coming around the backedge is an add with the symbolic
2175 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00002176 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002177 // If there is a single occurrence of the symbolic value, replace it
2178 // with a recurrence.
2179 unsigned FoundIndex = Add->getNumOperands();
2180 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2181 if (Add->getOperand(i) == SymbolicName)
2182 if (FoundIndex == e) {
2183 FoundIndex = i;
2184 break;
2185 }
2186
2187 if (FoundIndex != Add->getNumOperands()) {
2188 // Create an add with everything but the specified operand.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002189 SmallVector<const SCEV*, 8> Ops;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002190 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
2191 if (i != FoundIndex)
2192 Ops.push_back(Add->getOperand(i));
Owen Andersonecd0cd72009-06-22 21:39:50 +00002193 const SCEV* Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194
2195 // This is not a valid addrec if the step amount is varying each
2196 // loop iteration, but is not itself an addrec in this loop.
2197 if (Accum->isLoopInvariant(L) ||
2198 (isa<SCEVAddRecExpr>(Accum) &&
2199 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002200 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
2201 const SCEV* PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002202
2203 // Okay, for the entire analysis of this edge we assumed the PHI
2204 // to be symbolic. We now need to go back and update all of the
2205 // entries for the scalars that use the PHI (except for the PHI
2206 // itself) to use the new analyzed value instead of the "symbolic"
2207 // value.
2208 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2209 return PHISCEV;
2210 }
2211 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00002212 } else if (const SCEVAddRecExpr *AddRec =
2213 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002214 // Otherwise, this could be a loop like this:
2215 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
2216 // In this case, j = {1,+,1} and BEValue is j.
2217 // Because the other in-value of i (0) fits the evolution of BEValue
2218 // i really is an addrec evolution.
2219 if (AddRec->getLoop() == L && AddRec->isAffine()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002220 const SCEV* StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221
2222 // If StartVal = j.start - j.stride, we can use StartVal as the
2223 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002224 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00002225 AddRec->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002226 const SCEV* PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002227 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002228
2229 // Okay, for the entire analysis of this edge we assumed the PHI
2230 // to be symbolic. We now need to go back and update all of the
2231 // entries for the scalars that use the PHI (except for the PHI
2232 // itself) to use the new analyzed value instead of the "symbolic"
2233 // value.
2234 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
2235 return PHISCEV;
2236 }
2237 }
2238 }
2239
2240 return SymbolicName;
2241 }
2242
2243 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002244 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002245}
2246
Dan Gohman509cf4d2009-05-08 20:26:55 +00002247/// createNodeForGEP - Expand GEP instructions into add and multiply
2248/// operations. This allows them to be analyzed by regular SCEV code.
2249///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002250const SCEV* ScalarEvolution::createNodeForGEP(User *GEP) {
Dan Gohman509cf4d2009-05-08 20:26:55 +00002251
2252 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002253 Value *Base = GEP->getOperand(0);
Dan Gohmand586a4f2009-05-09 00:14:52 +00002254 // Don't attempt to analyze GEPs over unsized objects.
2255 if (!cast<PointerType>(Base->getType())->getElementType()->isSized())
2256 return getUnknown(GEP);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002257 const SCEV* TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohmanc7034fa2009-05-08 20:36:47 +00002258 gep_type_iterator GTI = gep_type_begin(GEP);
2259 for (GetElementPtrInst::op_iterator I = next(GEP->op_begin()),
2260 E = GEP->op_end();
Dan Gohman509cf4d2009-05-08 20:26:55 +00002261 I != E; ++I) {
2262 Value *Index = *I;
2263 // Compute the (potentially symbolic) offset in bytes for this index.
2264 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2265 // For a struct, add the member offset.
2266 const StructLayout &SL = *TD->getStructLayout(STy);
2267 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2268 uint64_t Offset = SL.getElementOffset(FieldNo);
2269 TotalOffset = getAddExpr(TotalOffset,
2270 getIntegerSCEV(Offset, IntPtrTy));
2271 } else {
2272 // For an array, add the element offset, explicitly scaled.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002273 const SCEV* LocalOffset = getSCEV(Index);
Dan Gohman509cf4d2009-05-08 20:26:55 +00002274 if (!isa<PointerType>(LocalOffset->getType()))
2275 // Getelementptr indicies are signed.
2276 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2277 IntPtrTy);
2278 LocalOffset =
2279 getMulExpr(LocalOffset,
Duncan Sandsec4f97d2009-05-09 07:06:46 +00002280 getIntegerSCEV(TD->getTypeAllocSize(*GTI),
Dan Gohman509cf4d2009-05-08 20:26:55 +00002281 IntPtrTy));
2282 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
2283 }
2284 }
2285 return getAddExpr(getSCEV(Base), TotalOffset);
2286}
2287
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002288/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
2289/// guaranteed to end in (at every loop iteration). It is, at the same time,
2290/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
2291/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohman6e923a72009-06-19 23:29:04 +00002292uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002293ScalarEvolution::GetMinTrailingZeros(const SCEV* S) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00002294 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00002295 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002296
Dan Gohmanc76b5452009-05-04 22:02:23 +00002297 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohman6e923a72009-06-19 23:29:04 +00002298 return std::min(GetMinTrailingZeros(T->getOperand()),
2299 (uint32_t)getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002300
Dan Gohmanc76b5452009-05-04 22:02:23 +00002301 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002302 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2303 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2304 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002305 }
2306
Dan Gohmanc76b5452009-05-04 22:02:23 +00002307 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002308 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
2309 return OpRes == getTypeSizeInBits(E->getOperand()->getType()) ?
2310 getTypeSizeInBits(E->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002311 }
2312
Dan Gohmanc76b5452009-05-04 22:02:23 +00002313 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002314 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002315 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002316 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002317 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002318 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319 }
2320
Dan Gohmanc76b5452009-05-04 22:02:23 +00002321 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002322 // The result is the sum of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002323 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
2324 uint32_t BitWidth = getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002325 for (unsigned i = 1, e = M->getNumOperands();
2326 SumOpRes != BitWidth && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002327 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002328 BitWidth);
2329 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002330 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002331
Dan Gohmanc76b5452009-05-04 22:02:23 +00002332 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002333 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002334 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002335 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002336 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002337 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002339
Dan Gohmanc76b5452009-05-04 22:02:23 +00002340 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00002341 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002342 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewycky711640a2007-11-25 22:41:31 +00002343 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002344 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewycky711640a2007-11-25 22:41:31 +00002345 return MinOpRes;
2346 }
2347
Dan Gohmanc76b5452009-05-04 22:02:23 +00002348 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002349 // The result is the min of all operands results.
Dan Gohman6e923a72009-06-19 23:29:04 +00002350 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002351 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohman6e923a72009-06-19 23:29:04 +00002352 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002353 return MinOpRes;
2354 }
2355
Dan Gohman6e923a72009-06-19 23:29:04 +00002356 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2357 // For a SCEVUnknown, ask ValueTracking.
2358 unsigned BitWidth = getTypeSizeInBits(U->getType());
2359 APInt Mask = APInt::getAllOnesValue(BitWidth);
2360 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2361 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones);
2362 return Zeros.countTrailingOnes();
2363 }
2364
2365 // SCEVUDivExpr
Nick Lewycky4cb604b2007-11-22 07:59:40 +00002366 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002367}
2368
Dan Gohman6e923a72009-06-19 23:29:04 +00002369uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002370ScalarEvolution::GetMinLeadingZeros(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002371 // TODO: Handle other SCEV expression types here.
2372
2373 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
2374 return C->getValue()->getValue().countLeadingZeros();
2375
2376 if (const SCEVZeroExtendExpr *C = dyn_cast<SCEVZeroExtendExpr>(S)) {
2377 // A zero-extension cast adds zero bits.
2378 return GetMinLeadingZeros(C->getOperand()) +
2379 (getTypeSizeInBits(C->getType()) -
2380 getTypeSizeInBits(C->getOperand()->getType()));
2381 }
2382
2383 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2384 // For a SCEVUnknown, ask ValueTracking.
2385 unsigned BitWidth = getTypeSizeInBits(U->getType());
2386 APInt Mask = APInt::getAllOnesValue(BitWidth);
2387 APInt Zeros(BitWidth, 0), Ones(BitWidth, 0);
2388 ComputeMaskedBits(U->getValue(), Mask, Zeros, Ones, TD);
2389 return Zeros.countLeadingOnes();
2390 }
2391
2392 return 1;
2393}
2394
2395uint32_t
Owen Andersonecd0cd72009-06-22 21:39:50 +00002396ScalarEvolution::GetMinSignBits(const SCEV* S) {
Dan Gohman6e923a72009-06-19 23:29:04 +00002397 // TODO: Handle other SCEV expression types here.
2398
2399 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
2400 const APInt &A = C->getValue()->getValue();
2401 return A.isNegative() ? A.countLeadingOnes() :
2402 A.countLeadingZeros();
2403 }
2404
2405 if (const SCEVSignExtendExpr *C = dyn_cast<SCEVSignExtendExpr>(S)) {
2406 // A sign-extension cast adds sign bits.
2407 return GetMinSignBits(C->getOperand()) +
2408 (getTypeSizeInBits(C->getType()) -
2409 getTypeSizeInBits(C->getOperand()->getType()));
2410 }
2411
2412 if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
2413 // For a SCEVUnknown, ask ValueTracking.
2414 return ComputeNumSignBits(U->getValue(), TD);
2415 }
2416
2417 return 1;
2418}
2419
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002420/// createSCEV - We know that there is no SCEV for the specified value.
2421/// Analyze the expression.
2422///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002423const SCEV* ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002424 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002425 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002426
Dan Gohman3996f472008-06-22 19:56:46 +00002427 unsigned Opcode = Instruction::UserOp1;
2428 if (Instruction *I = dyn_cast<Instruction>(V))
2429 Opcode = I->getOpcode();
2430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
2431 Opcode = CE->getOpcode();
2432 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002433 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434
Dan Gohman3996f472008-06-22 19:56:46 +00002435 User *U = cast<User>(V);
2436 switch (Opcode) {
2437 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002438 return getAddExpr(getSCEV(U->getOperand(0)),
2439 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002440 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002441 return getMulExpr(getSCEV(U->getOperand(0)),
2442 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002443 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002444 return getUDivExpr(getSCEV(U->getOperand(0)),
2445 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00002446 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002447 return getMinusSCEV(getSCEV(U->getOperand(0)),
2448 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002449 case Instruction::And:
2450 // For an expression like x&255 that merely masks off the high bits,
2451 // use zext(trunc(x)) as the SCEV expression.
2452 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002453 if (CI->isNullValue())
2454 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00002455 if (CI->isAllOnesValue())
2456 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00002457 const APInt &A = CI->getValue();
Dan Gohmana7726c32009-06-16 19:52:01 +00002458
2459 // Instcombine's ShrinkDemandedConstant may strip bits out of
2460 // constants, obscuring what would otherwise be a low-bits mask.
2461 // Use ComputeMaskedBits to compute what ShrinkDemandedConstant
2462 // knew about to reconstruct a low-bits mask value.
2463 unsigned LZ = A.countLeadingZeros();
2464 unsigned BitWidth = A.getBitWidth();
2465 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2466 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2467 ComputeMaskedBits(U->getOperand(0), AllOnes, KnownZero, KnownOne, TD);
2468
2469 APInt EffectiveMask = APInt::getLowBitsSet(BitWidth, BitWidth - LZ);
2470
Dan Gohmanae1d7dd2009-06-17 23:54:37 +00002471 if (LZ != 0 && !((~A & ~KnownZero) & EffectiveMask))
Dan Gohman53bf64a2009-04-21 02:26:00 +00002472 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002473 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
Dan Gohmana7726c32009-06-16 19:52:01 +00002474 IntegerType::get(BitWidth - LZ)),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002475 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00002476 }
2477 break;
Dan Gohmana7726c32009-06-16 19:52:01 +00002478
Dan Gohman3996f472008-06-22 19:56:46 +00002479 case Instruction::Or:
2480 // If the RHS of the Or is a constant, we may have something like:
2481 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
2482 // optimizations will transparently handle this case.
2483 //
2484 // In order for this transformation to be safe, the LHS must be of the
2485 // form X*(2^n) and the Or constant must be less than 2^n.
2486 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002487 const SCEV* LHS = getSCEV(U->getOperand(0));
Dan Gohman3996f472008-06-22 19:56:46 +00002488 const APInt &CIVal = CI->getValue();
Dan Gohman6e923a72009-06-19 23:29:04 +00002489 if (GetMinTrailingZeros(LHS) >=
Dan Gohman3996f472008-06-22 19:56:46 +00002490 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002491 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002492 }
Dan Gohman3996f472008-06-22 19:56:46 +00002493 break;
2494 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00002495 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00002496 // If the RHS of the xor is a signbit, then this is just an add.
2497 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00002498 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002499 return getAddExpr(getSCEV(U->getOperand(0)),
2500 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002501
2502 // If the RHS of xor is -1, then this is a not operation.
Dan Gohmanc897f752009-05-18 16:17:44 +00002503 if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002504 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohmanfc78cff2009-05-18 16:29:04 +00002505
2506 // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
2507 // This is a variant of the check for xor with -1, and it handles
2508 // the case where instcombine has trimmed non-demanded bits out
2509 // of an xor with -1.
2510 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U->getOperand(0)))
2511 if (ConstantInt *LCI = dyn_cast<ConstantInt>(BO->getOperand(1)))
2512 if (BO->getOpcode() == Instruction::And &&
2513 LCI->getValue() == CI->getValue())
2514 if (const SCEVZeroExtendExpr *Z =
Dan Gohmane49ae432009-06-17 01:22:39 +00002515 dyn_cast<SCEVZeroExtendExpr>(getSCEV(U->getOperand(0)))) {
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002516 const Type *UTy = U->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00002517 const SCEV* Z0 = Z->getOperand();
Dan Gohmaned1d8bb2009-06-18 00:00:20 +00002518 const Type *Z0Ty = Z0->getType();
2519 unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
2520
2521 // If C is a low-bits mask, the zero extend is zerving to
2522 // mask off the high bits. Complement the operand and
2523 // re-apply the zext.
2524 if (APIntOps::isMask(Z0TySize, CI->getValue()))
2525 return getZeroExtendExpr(getNotSCEV(Z0), UTy);
2526
2527 // If C is a single bit, it may be in the sign-bit position
2528 // before the zero-extend. In this case, represent the xor
2529 // using an add, which is equivalent, and re-apply the zext.
2530 APInt Trunc = APInt(CI->getValue()).trunc(Z0TySize);
2531 if (APInt(Trunc).zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
2532 Trunc.isSignBit())
2533 return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
2534 UTy);
Dan Gohmane49ae432009-06-17 01:22:39 +00002535 }
Dan Gohman3996f472008-06-22 19:56:46 +00002536 }
2537 break;
2538
2539 case Instruction::Shl:
2540 // Turn shift left of a constant amount into a multiply.
2541 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2542 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2543 Constant *X = ConstantInt::get(
2544 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002545 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00002546 }
2547 break;
2548
Nick Lewycky7fd27892008-07-07 06:15:49 +00002549 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00002550 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00002551 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
2552 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
2553 Constant *X = ConstantInt::get(
2554 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002555 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00002556 }
2557 break;
2558
Dan Gohman53bf64a2009-04-21 02:26:00 +00002559 case Instruction::AShr:
2560 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
2561 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
2562 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
2563 if (L->getOpcode() == Instruction::Shl &&
2564 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00002565 unsigned BitWidth = getTypeSizeInBits(U->getType());
2566 uint64_t Amt = BitWidth - CI->getZExtValue();
2567 if (Amt == BitWidth)
2568 return getSCEV(L->getOperand(0)); // shift by zero --> noop
2569 if (Amt > BitWidth)
2570 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00002571 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002572 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00002573 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00002574 U->getType());
2575 }
2576 break;
2577
Dan Gohman3996f472008-06-22 19:56:46 +00002578 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002579 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002580
2581 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002582 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002583
2584 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002585 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00002586
2587 case Instruction::BitCast:
2588 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002589 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00002590 return getSCEV(U->getOperand(0));
2591 break;
2592
Dan Gohman01c2ee72009-04-16 03:18:22 +00002593 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002594 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002595 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002596 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002597
2598 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002599 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002600 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2601 U->getType());
2602
Dan Gohman509cf4d2009-05-08 20:26:55 +00002603 case Instruction::GetElementPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002604 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohmanca5a39e2009-05-08 20:58:38 +00002605 return createNodeForGEP(U);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002606
Dan Gohman3996f472008-06-22 19:56:46 +00002607 case Instruction::PHI:
2608 return createNodeForPHI(cast<PHINode>(U));
2609
2610 case Instruction::Select:
2611 // This could be a smax or umax that was lowered earlier.
2612 // Try to recover it.
2613 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2614 Value *LHS = ICI->getOperand(0);
2615 Value *RHS = ICI->getOperand(1);
2616 switch (ICI->getPredicate()) {
2617 case ICmpInst::ICMP_SLT:
2618 case ICmpInst::ICMP_SLE:
2619 std::swap(LHS, RHS);
2620 // fall through
2621 case ICmpInst::ICMP_SGT:
2622 case ICmpInst::ICMP_SGE:
2623 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002624 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002625 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002626 return getSMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002627 break;
2628 case ICmpInst::ICMP_ULT:
2629 case ICmpInst::ICMP_ULE:
2630 std::swap(LHS, RHS);
2631 // fall through
2632 case ICmpInst::ICMP_UGT:
2633 case ICmpInst::ICMP_UGE:
2634 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002635 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002636 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Dan Gohmand01fff82009-06-22 03:18:45 +00002637 return getUMinExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002638 break;
Dan Gohmanf27dc692009-06-18 20:21:07 +00002639 case ICmpInst::ICMP_NE:
2640 // n != 0 ? n : 1 -> umax(n, 1)
2641 if (LHS == U->getOperand(1) &&
2642 isa<ConstantInt>(U->getOperand(2)) &&
2643 cast<ConstantInt>(U->getOperand(2))->isOne() &&
2644 isa<ConstantInt>(RHS) &&
2645 cast<ConstantInt>(RHS)->isZero())
2646 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(2)));
2647 break;
2648 case ICmpInst::ICMP_EQ:
2649 // n == 0 ? 1 : n -> umax(n, 1)
2650 if (LHS == U->getOperand(2) &&
2651 isa<ConstantInt>(U->getOperand(1)) &&
2652 cast<ConstantInt>(U->getOperand(1))->isOne() &&
2653 isa<ConstantInt>(RHS) &&
2654 cast<ConstantInt>(RHS)->isZero())
2655 return getUMaxExpr(getSCEV(LHS), getSCEV(U->getOperand(1)));
2656 break;
Dan Gohman3996f472008-06-22 19:56:46 +00002657 default:
2658 break;
2659 }
2660 }
2661
2662 default: // We cannot analyze this expression.
2663 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 }
2665
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002666 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002667}
2668
2669
2670
2671//===----------------------------------------------------------------------===//
2672// Iteration Count Computation Code
2673//
2674
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002675/// getBackedgeTakenCount - If the specified loop has a predictable
2676/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2677/// object. The backedge-taken count is the number of times the loop header
2678/// will be branched to from within the loop. This is one less than the
2679/// trip count of the loop, since it doesn't count the first iteration,
2680/// when the header is branched to from outside the loop.
2681///
2682/// Note that it is not valid to call this method on a loop without a
2683/// loop-invariant backedge-taken count (see
2684/// hasLoopInvariantBackedgeTakenCount).
2685///
Owen Andersonecd0cd72009-06-22 21:39:50 +00002686const SCEV* ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002687 return getBackedgeTakenInfo(L).Exact;
2688}
2689
2690/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2691/// return the least SCEV value that is known never to be less than the
2692/// actual backedge taken count.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002693const SCEV* ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002694 return getBackedgeTakenInfo(L).Max;
2695}
2696
2697const ScalarEvolution::BackedgeTakenInfo &
2698ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002699 // Initially insert a CouldNotCompute for this loop. If the insertion
2700 // succeeds, procede to actually compute a backedge-taken count and
2701 // update the value. The temporary CouldNotCompute value tells SCEV
2702 // code elsewhere that it shouldn't attempt to request a new
2703 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002704 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002705 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2706 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002707 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
Dan Gohman0c850912009-06-06 14:37:11 +00002708 if (ItCount.Exact != CouldNotCompute) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002709 assert(ItCount.Exact->isLoopInvariant(L) &&
2710 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002711 "Computed trip count isn't loop invariant for loop!");
2712 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002713
Dan Gohmana9dba962009-04-27 20:16:15 +00002714 // Update the value in the map.
2715 Pair.first->second = ItCount;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002716 } else {
2717 if (ItCount.Max != CouldNotCompute)
2718 // Update the value in the map.
2719 Pair.first->second = ItCount;
2720 if (isa<PHINode>(L->getHeader()->begin()))
2721 // Only count loops that have phi nodes as not being computable.
2722 ++NumTripCountsNotComputed;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002724
2725 // Now that we know more about the trip count for this loop, forget any
2726 // existing SCEV values for PHI nodes in this loop since they are only
2727 // conservative estimates made without the benefit
2728 // of trip count information.
2729 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002730 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002732 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733}
2734
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002735/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002736/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002737/// ScalarEvolution's ability to compute a trip count, or if the loop
2738/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002739void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002740 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002741 forgetLoopPHIs(L);
2742}
2743
2744/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2745/// PHI nodes in the given loop. This is used when the trip count of
2746/// the loop may have changed.
2747void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002748 BasicBlock *Header = L->getHeader();
2749
Dan Gohman9fd4a002009-05-12 01:27:58 +00002750 // Push all Loop-header PHIs onto the Worklist stack, except those
2751 // that are presently represented via a SCEVUnknown. SCEVUnknown for
2752 // a PHI either means that it has an unrecognized structure, or it's
2753 // a PHI that's in the progress of being computed by createNodeForPHI.
2754 // In the former case, additional loop trip count information isn't
2755 // going to change anything. In the later case, createNodeForPHI will
2756 // perform the necessary updates on its own when it gets to that point.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002757 SmallVector<Instruction *, 16> Worklist;
2758 for (BasicBlock::iterator I = Header->begin();
Dan Gohman9fd4a002009-05-12 01:27:58 +00002759 PHINode *PN = dyn_cast<PHINode>(I); ++I) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002760 std::map<SCEVCallbackVH, const SCEV*>::iterator It = Scalars.find((Value*)I);
Dan Gohman9fd4a002009-05-12 01:27:58 +00002761 if (It != Scalars.end() && !isa<SCEVUnknown>(It->second))
2762 Worklist.push_back(PN);
2763 }
Dan Gohmanbff6b582009-05-04 22:30:44 +00002764
2765 while (!Worklist.empty()) {
2766 Instruction *I = Worklist.pop_back_val();
2767 if (Scalars.erase(I))
2768 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2769 UI != UE; ++UI)
2770 Worklist.push_back(cast<Instruction>(UI));
2771 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002772}
2773
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002774/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2775/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002776ScalarEvolution::BackedgeTakenInfo
2777ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohman8e8b5232009-06-22 00:31:57 +00002778 SmallVector<BasicBlock*, 8> ExitingBlocks;
2779 L->getExitingBlocks(ExitingBlocks);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780
Dan Gohman8e8b5232009-06-22 00:31:57 +00002781 // Examine all exits and pick the most conservative values.
Owen Andersonecd0cd72009-06-22 21:39:50 +00002782 const SCEV* BECount = CouldNotCompute;
2783 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002784 bool CouldNotComputeBECount = false;
2785 bool CouldNotComputeMaxBECount = false;
2786 for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
2787 BackedgeTakenInfo NewBTI =
2788 ComputeBackedgeTakenCountFromExit(L, ExitingBlocks[i]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002789
Dan Gohman8e8b5232009-06-22 00:31:57 +00002790 if (NewBTI.Exact == CouldNotCompute) {
2791 // We couldn't compute an exact value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002792 // we won't be able to compute an exact value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002793 CouldNotComputeBECount = true;
2794 BECount = CouldNotCompute;
2795 } else if (!CouldNotComputeBECount) {
2796 if (BECount == CouldNotCompute)
2797 BECount = NewBTI.Exact;
2798 else {
2799 // TODO: More analysis could be done here. For example, a
2800 // loop with a short-circuiting && operator has an exact count
2801 // of the min of both sides.
2802 CouldNotComputeBECount = true;
2803 BECount = CouldNotCompute;
2804 }
2805 }
2806 if (NewBTI.Max == CouldNotCompute) {
2807 // We couldn't compute an maximum value for this exit, so
Dan Gohmanc6e8c832009-06-22 21:10:22 +00002808 // we won't be able to compute an maximum value for the loop.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002809 CouldNotComputeMaxBECount = true;
2810 MaxBECount = CouldNotCompute;
2811 } else if (!CouldNotComputeMaxBECount) {
2812 if (MaxBECount == CouldNotCompute)
2813 MaxBECount = NewBTI.Max;
2814 else
2815 MaxBECount = getUMaxFromMismatchedTypes(MaxBECount, NewBTI.Max);
2816 }
2817 }
2818
2819 return BackedgeTakenInfo(BECount, MaxBECount);
2820}
2821
2822/// ComputeBackedgeTakenCountFromExit - Compute the number of times the backedge
2823/// of the specified loop will execute if it exits via the specified block.
2824ScalarEvolution::BackedgeTakenInfo
2825ScalarEvolution::ComputeBackedgeTakenCountFromExit(const Loop *L,
2826 BasicBlock *ExitingBlock) {
2827
2828 // Okay, we've chosen an exiting block. See what condition causes us to
2829 // exit at this block.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002830 //
2831 // FIXME: we should be able to handle switch instructions (with a single exit)
2832 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
Dan Gohman0c850912009-06-06 14:37:11 +00002833 if (ExitBr == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002834 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2835
2836 // At this point, we know we have a conditional branch that determines whether
2837 // the loop is exited. However, we don't know if the branch is executed each
2838 // time through the loop. If not, then the execution count of the branch will
2839 // not be equal to the trip count of the loop.
2840 //
2841 // Currently we check for this by checking to see if the Exit branch goes to
2842 // the loop header. If so, we know it will always execute the same number of
2843 // times as the loop. We also handle the case where the exit block *is* the
Dan Gohman8e8b5232009-06-22 00:31:57 +00002844 // loop header. This is common for un-rotated loops.
2845 //
2846 // If both of those tests fail, walk up the unique predecessor chain to the
2847 // header, stopping if there is an edge that doesn't exit the loop. If the
2848 // header is reached, the execution count of the branch will be equal to the
2849 // trip count of the loop.
2850 //
2851 // More extensive analysis could be done to handle more cases here.
2852 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002853 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2854 ExitBr->getSuccessor(1) != L->getHeader() &&
Dan Gohman8e8b5232009-06-22 00:31:57 +00002855 ExitBr->getParent() != L->getHeader()) {
2856 // The simple checks failed, try climbing the unique predecessor chain
2857 // up to the header.
2858 bool Ok = false;
2859 for (BasicBlock *BB = ExitBr->getParent(); BB; ) {
2860 BasicBlock *Pred = BB->getUniquePredecessor();
2861 if (!Pred)
2862 return CouldNotCompute;
2863 TerminatorInst *PredTerm = Pred->getTerminator();
2864 for (unsigned i = 0, e = PredTerm->getNumSuccessors(); i != e; ++i) {
2865 BasicBlock *PredSucc = PredTerm->getSuccessor(i);
2866 if (PredSucc == BB)
2867 continue;
2868 // If the predecessor has a successor that isn't BB and isn't
2869 // outside the loop, assume the worst.
2870 if (L->contains(PredSucc))
2871 return CouldNotCompute;
2872 }
2873 if (Pred == L->getHeader()) {
2874 Ok = true;
2875 break;
2876 }
2877 BB = Pred;
2878 }
2879 if (!Ok)
2880 return CouldNotCompute;
2881 }
2882
2883 // Procede to the next level to examine the exit condition expression.
2884 return ComputeBackedgeTakenCountFromExitCond(L, ExitBr->getCondition(),
2885 ExitBr->getSuccessor(0),
2886 ExitBr->getSuccessor(1));
2887}
2888
2889/// ComputeBackedgeTakenCountFromExitCond - Compute the number of times the
2890/// backedge of the specified loop will execute if its exit condition
2891/// were a conditional branch of ExitCond, TBB, and FBB.
2892ScalarEvolution::BackedgeTakenInfo
2893ScalarEvolution::ComputeBackedgeTakenCountFromExitCond(const Loop *L,
2894 Value *ExitCond,
2895 BasicBlock *TBB,
2896 BasicBlock *FBB) {
2897 // Check if the controlling expression for this loop is an and or or. In
2898 // such cases, an exact backedge-taken count may be infeasible, but a
2899 // maximum count may still be feasible.
2900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(ExitCond)) {
2901 if (BO->getOpcode() == Instruction::And) {
2902 // Recurse on the operands of the and.
2903 BackedgeTakenInfo BTI0 =
2904 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2905 BackedgeTakenInfo BTI1 =
2906 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002907 const SCEV* BECount = CouldNotCompute;
2908 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002909 if (L->contains(TBB)) {
2910 // Both conditions must be true for the loop to continue executing.
2911 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002912 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2913 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002914 else
2915 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002916 if (BTI0.Max == CouldNotCompute)
2917 MaxBECount = BTI1.Max;
2918 else if (BTI1.Max == CouldNotCompute)
2919 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002920 else
2921 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002922 } else {
2923 // Both conditions must be true for the loop to exit.
2924 assert(L->contains(FBB) && "Loop block has no successor in loop!");
2925 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2926 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2927 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2928 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2929 }
2930
2931 return BackedgeTakenInfo(BECount, MaxBECount);
2932 }
2933 if (BO->getOpcode() == Instruction::Or) {
2934 // Recurse on the operands of the or.
2935 BackedgeTakenInfo BTI0 =
2936 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(0), TBB, FBB);
2937 BackedgeTakenInfo BTI1 =
2938 ComputeBackedgeTakenCountFromExitCond(L, BO->getOperand(1), TBB, FBB);
Owen Andersonecd0cd72009-06-22 21:39:50 +00002939 const SCEV* BECount = CouldNotCompute;
2940 const SCEV* MaxBECount = CouldNotCompute;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002941 if (L->contains(FBB)) {
2942 // Both conditions must be false for the loop to continue executing.
2943 // Choose the less conservative count.
Dan Gohman2cc450e2009-06-22 23:28:56 +00002944 if (BTI0.Exact == CouldNotCompute || BTI1.Exact == CouldNotCompute)
2945 BECount = CouldNotCompute;
Dan Gohmanac958b32009-06-22 15:09:28 +00002946 else
2947 BECount = getUMinFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002948 if (BTI0.Max == CouldNotCompute)
2949 MaxBECount = BTI1.Max;
2950 else if (BTI1.Max == CouldNotCompute)
2951 MaxBECount = BTI0.Max;
Dan Gohmanac958b32009-06-22 15:09:28 +00002952 else
2953 MaxBECount = getUMinFromMismatchedTypes(BTI0.Max, BTI1.Max);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002954 } else {
2955 // Both conditions must be false for the loop to exit.
2956 assert(L->contains(TBB) && "Loop block has no successor in loop!");
2957 if (BTI0.Exact != CouldNotCompute && BTI1.Exact != CouldNotCompute)
2958 BECount = getUMaxFromMismatchedTypes(BTI0.Exact, BTI1.Exact);
2959 if (BTI0.Max != CouldNotCompute && BTI1.Max != CouldNotCompute)
2960 MaxBECount = getUMaxFromMismatchedTypes(BTI0.Max, BTI1.Max);
2961 }
2962
2963 return BackedgeTakenInfo(BECount, MaxBECount);
2964 }
2965 }
2966
2967 // With an icmp, it may be feasible to compute an exact backedge-taken count.
2968 // Procede to the next level to examine the icmp.
2969 if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond))
2970 return ComputeBackedgeTakenCountFromExitCondICmp(L, ExitCondICmp, TBB, FBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002971
Eli Friedman459d7292009-05-09 12:32:42 +00002972 // If it's not an integer or pointer comparison then compute it the hard way.
Dan Gohman8e8b5232009-06-22 00:31:57 +00002973 return ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
2974}
2975
2976/// ComputeBackedgeTakenCountFromExitCondICmp - Compute the number of times the
2977/// backedge of the specified loop will execute if its exit condition
2978/// were a conditional branch of the ICmpInst ExitCond, TBB, and FBB.
2979ScalarEvolution::BackedgeTakenInfo
2980ScalarEvolution::ComputeBackedgeTakenCountFromExitCondICmp(const Loop *L,
2981 ICmpInst *ExitCond,
2982 BasicBlock *TBB,
2983 BasicBlock *FBB) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002984
2985 // If the condition was exit on true, convert the condition to exit on false
2986 ICmpInst::Predicate Cond;
Dan Gohman8e8b5232009-06-22 00:31:57 +00002987 if (!L->contains(FBB))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002988 Cond = ExitCond->getPredicate();
2989 else
2990 Cond = ExitCond->getInversePredicate();
2991
2992 // Handle common loops like: for (X = "string"; *X; ++X)
2993 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2994 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00002995 const SCEV* ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002996 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohman8e8b5232009-06-22 00:31:57 +00002997 if (!isa<SCEVCouldNotCompute>(ItCnt)) {
2998 unsigned BitWidth = getTypeSizeInBits(ItCnt->getType());
2999 return BackedgeTakenInfo(ItCnt,
3000 isa<SCEVConstant>(ItCnt) ? ItCnt :
3001 getConstant(APInt::getMaxValue(BitWidth)-1));
3002 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003003 }
3004
Owen Andersonecd0cd72009-06-22 21:39:50 +00003005 const SCEV* LHS = getSCEV(ExitCond->getOperand(0));
3006 const SCEV* RHS = getSCEV(ExitCond->getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003007
3008 // Try to evaluate any dependencies out of the loop.
Dan Gohmanaff14d62009-05-24 23:25:42 +00003009 LHS = getSCEVAtScope(LHS, L);
3010 RHS = getSCEVAtScope(RHS, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003011
3012 // At this point, we would like to compute how many iterations of the
3013 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00003014 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
3015 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003016 std::swap(LHS, RHS);
3017 Cond = ICmpInst::getSwappedPredicate(Cond);
3018 }
3019
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003020 // If we have a comparison of a chrec against a constant, try to use value
3021 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003022 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
3023 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003024 if (AddRec->getLoop() == L) {
Eli Friedman459d7292009-05-09 12:32:42 +00003025 // Form the constant range.
3026 ConstantRange CompRange(
3027 ICmpInst::makeConstantRange(Cond, RHSC->getValue()->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028
Owen Andersonecd0cd72009-06-22 21:39:50 +00003029 const SCEV* Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Eli Friedman459d7292009-05-09 12:32:42 +00003030 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003031 }
3032
3033 switch (Cond) {
3034 case ICmpInst::ICMP_NE: { // while (X != Y)
3035 // Convert to: while (X-Y != 0)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003036 const SCEV* TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003037 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3038 break;
3039 }
3040 case ICmpInst::ICMP_EQ: {
3041 // Convert to: while (X-Y == 0) // while (X == Y)
Owen Andersonecd0cd72009-06-22 21:39:50 +00003042 const SCEV* TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003043 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
3044 break;
3045 }
3046 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003047 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
3048 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003049 break;
3050 }
3051 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003052 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3053 getNotSCEV(RHS), L, true);
3054 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003055 break;
3056 }
3057 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003058 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
3059 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00003060 break;
3061 }
3062 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003063 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
3064 getNotSCEV(RHS), L, false);
3065 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003066 break;
3067 }
3068 default:
3069#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003070 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003071 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00003072 errs() << "[unsigned] ";
3073 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003074 << Instruction::getOpcodeName(Instruction::ICmp)
3075 << " " << *RHS << "\n";
3076#endif
3077 break;
3078 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003079 return
Dan Gohman8e8b5232009-06-22 00:31:57 +00003080 ComputeBackedgeTakenCountExhaustively(L, ExitCond, !L->contains(TBB));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003081}
3082
3083static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00003084EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
3085 ScalarEvolution &SE) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003086 const SCEV* InVal = SE.getConstant(C);
3087 const SCEV* Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088 assert(isa<SCEVConstant>(Val) &&
3089 "Evaluation of SCEV at constant didn't fold correctly?");
3090 return cast<SCEVConstant>(Val)->getValue();
3091}
3092
3093/// GetAddressedElementFromGlobal - Given a global variable with an initializer
3094/// and a GEP expression (missing the pointer index) indexing into it, return
3095/// the addressed element of the initializer or null if the index expression is
3096/// invalid.
3097static Constant *
3098GetAddressedElementFromGlobal(GlobalVariable *GV,
3099 const std::vector<ConstantInt*> &Indices) {
3100 Constant *Init = GV->getInitializer();
3101 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
3102 uint64_t Idx = Indices[i]->getZExtValue();
3103 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
3104 assert(Idx < CS->getNumOperands() && "Bad struct index!");
3105 Init = cast<Constant>(CS->getOperand(Idx));
3106 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
3107 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
3108 Init = cast<Constant>(CA->getOperand(Idx));
3109 } else if (isa<ConstantAggregateZero>(Init)) {
3110 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
3111 assert(Idx < STy->getNumElements() && "Bad struct index!");
3112 Init = Constant::getNullValue(STy->getElementType(Idx));
3113 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
3114 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
3115 Init = Constant::getNullValue(ATy->getElementType());
3116 } else {
3117 assert(0 && "Unknown constant aggregate type!");
3118 }
3119 return 0;
3120 } else {
3121 return 0; // Unknown initializer type
3122 }
3123 }
3124 return Init;
3125}
3126
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003127/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
3128/// 'icmp op load X, cst', try to see if we can compute the backedge
3129/// execution count.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003130const SCEV* ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003131ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
3132 const Loop *L,
3133 ICmpInst::Predicate predicate) {
Dan Gohman0c850912009-06-06 14:37:11 +00003134 if (LI->isVolatile()) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003135
3136 // Check to see if the loaded pointer is a getelementptr of a global.
3137 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
Dan Gohman0c850912009-06-06 14:37:11 +00003138 if (!GEP) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003139
3140 // Make sure that it is really a constant global we are gepping, with an
3141 // initializer, and make sure the first IDX is really 0.
3142 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
3143 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
3144 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
3145 !cast<Constant>(GEP->getOperand(1))->isNullValue())
Dan Gohman0c850912009-06-06 14:37:11 +00003146 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147
3148 // Okay, we allow one non-constant index into the GEP instruction.
3149 Value *VarIdx = 0;
3150 std::vector<ConstantInt*> Indexes;
3151 unsigned VarIdxNum = 0;
3152 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
3153 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
3154 Indexes.push_back(CI);
3155 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
Dan Gohman0c850912009-06-06 14:37:11 +00003156 if (VarIdx) return CouldNotCompute; // Multiple non-constant idx's.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003157 VarIdx = GEP->getOperand(i);
3158 VarIdxNum = i-2;
3159 Indexes.push_back(0);
3160 }
3161
3162 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
3163 // Check to see if X is a loop variant variable value now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003164 const SCEV* Idx = getSCEV(VarIdx);
Dan Gohmanaff14d62009-05-24 23:25:42 +00003165 Idx = getSCEVAtScope(Idx, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003166
3167 // We can only recognize very limited forms of loop index expressions, in
3168 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00003169 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003170 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
3171 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
3172 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
Dan Gohman0c850912009-06-06 14:37:11 +00003173 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003174
3175 unsigned MaxSteps = MaxBruteForceIterations;
3176 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
3177 ConstantInt *ItCst =
Dan Gohman8fd520a2009-06-15 22:12:54 +00003178 ConstantInt::get(cast<IntegerType>(IdxExpr->getType()), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003179 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003180
3181 // Form the GEP offset.
3182 Indexes[VarIdxNum] = Val;
3183
3184 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
3185 if (Result == 0) break; // Cannot compute!
3186
3187 // Evaluate the condition for this iteration.
3188 Result = ConstantExpr::getICmp(predicate, Result, RHS);
3189 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
3190 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
3191#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003192 errs() << "\n***\n*** Computed loop count " << *ItCst
3193 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
3194 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195#endif
3196 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003197 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003198 }
3199 }
Dan Gohman0c850912009-06-06 14:37:11 +00003200 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003201}
3202
3203
3204/// CanConstantFold - Return true if we can constant fold an instruction of the
3205/// specified type, assuming that all operands were constants.
3206static bool CanConstantFold(const Instruction *I) {
3207 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
3208 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
3209 return true;
3210
3211 if (const CallInst *CI = dyn_cast<CallInst>(I))
3212 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00003213 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003214 return false;
3215}
3216
3217/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
3218/// in the loop that V is derived from. We allow arbitrary operations along the
3219/// way, but the operands of an operation must either be constants or a value
3220/// derived from a constant PHI. If this expression does not fit with these
3221/// constraints, return null.
3222static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
3223 // If this is not an instruction, or if this is an instruction outside of the
3224 // loop, it can't be derived from a loop PHI.
3225 Instruction *I = dyn_cast<Instruction>(V);
3226 if (I == 0 || !L->contains(I->getParent())) return 0;
3227
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003228 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229 if (L->getHeader() == I->getParent())
3230 return PN;
3231 else
3232 // We don't currently keep track of the control flow needed to evaluate
3233 // PHIs, so we cannot handle PHIs inside of loops.
3234 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00003235 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003236
3237 // If we won't be able to constant fold this expression even if the operands
3238 // are constants, return early.
3239 if (!CanConstantFold(I)) return 0;
3240
3241 // Otherwise, we can evaluate this instruction if all of its operands are
3242 // constant or derived from a PHI node themselves.
3243 PHINode *PHI = 0;
3244 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
3245 if (!(isa<Constant>(I->getOperand(Op)) ||
3246 isa<GlobalValue>(I->getOperand(Op)))) {
3247 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
3248 if (P == 0) return 0; // Not evolving from PHI
3249 if (PHI == 0)
3250 PHI = P;
3251 else if (PHI != P)
3252 return 0; // Evolving from multiple different PHIs.
3253 }
3254
3255 // This is a expression evolving from a constant PHI!
3256 return PHI;
3257}
3258
3259/// EvaluateExpression - Given an expression that passes the
3260/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
3261/// in the loop has the value PHIVal. If we can't fold this expression for some
3262/// reason, return null.
3263static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
3264 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003265 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003266 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003267 Instruction *I = cast<Instruction>(V);
3268
3269 std::vector<Constant*> Operands;
3270 Operands.resize(I->getNumOperands());
3271
3272 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3273 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
3274 if (Operands[i] == 0) return 0;
3275 }
3276
Chris Lattnerd6e56912007-12-10 22:53:04 +00003277 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3278 return ConstantFoldCompareInstOperands(CI->getPredicate(),
3279 &Operands[0], Operands.size());
3280 else
3281 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3282 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003283}
3284
3285/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
3286/// in the header of its containing loop, we know the loop executes a
3287/// constant number of times, and the PHI node is just a recurrence
3288/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003289Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003290getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003291 std::map<PHINode*, Constant*>::iterator I =
3292 ConstantEvolutionLoopExitValue.find(PN);
3293 if (I != ConstantEvolutionLoopExitValue.end())
3294 return I->second;
3295
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003296 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003297 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
3298
3299 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
3300
3301 // Since the loop is canonicalized, the PHI node must have two entries. One
3302 // entry must be a constant (coming in from outside of the loop), and the
3303 // second must be derived from the same PHI.
3304 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3305 Constant *StartCST =
3306 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
3307 if (StartCST == 0)
3308 return RetVal = 0; // Must be a constant.
3309
3310 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3311 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
3312 if (PN2 != PN)
3313 return RetVal = 0; // Not derived from same PHI.
3314
3315 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003316 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003317 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
3318
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003319 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003320 unsigned IterationNum = 0;
3321 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
3322 if (IterationNum == NumIterations)
3323 return RetVal = PHIVal; // Got exit value!
3324
3325 // Compute the value of the PHI node for the next iteration.
3326 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3327 if (NextPHI == PHIVal)
3328 return RetVal = NextPHI; // Stopped evolving!
3329 if (NextPHI == 0)
3330 return 0; // Couldn't evaluate!
3331 PHIVal = NextPHI;
3332 }
3333}
3334
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003335/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003336/// constant number of times (the condition evolves only from constants),
3337/// try to evaluate a few iterations of the loop until we get the exit
3338/// condition gets a value of ExitWhen (true or false). If we cannot
Dan Gohman0c850912009-06-06 14:37:11 +00003339/// evaluate the trip count of the loop, return CouldNotCompute.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003340const SCEV* ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003341ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003342 PHINode *PN = getConstantEvolvingPHI(Cond, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003343 if (PN == 0) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003344
3345 // Since the loop is canonicalized, the PHI node must have two entries. One
3346 // entry must be a constant (coming in from outside of the loop), and the
3347 // second must be derived from the same PHI.
3348 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
3349 Constant *StartCST =
3350 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
Dan Gohman0c850912009-06-06 14:37:11 +00003351 if (StartCST == 0) return CouldNotCompute; // Must be a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003352
3353 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
3354 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
Dan Gohman0c850912009-06-06 14:37:11 +00003355 if (PN2 != PN) return CouldNotCompute; // Not derived from same PHI.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356
3357 // Okay, we find a PHI node that defines the trip count of this loop. Execute
3358 // the loop symbolically to determine when the condition gets a value of
3359 // "ExitWhen".
3360 unsigned IterationNum = 0;
3361 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
3362 for (Constant *PHIVal = StartCST;
3363 IterationNum != MaxIterations; ++IterationNum) {
3364 ConstantInt *CondVal =
3365 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
3366
3367 // Couldn't symbolically evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003368 if (!CondVal) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003369
3370 if (CondVal->getValue() == uint64_t(ExitWhen)) {
3371 ConstantEvolutionLoopExitValue[PN] = PHIVal;
3372 ++NumBruteForceTripCountsComputed;
Dan Gohman8fd520a2009-06-15 22:12:54 +00003373 return getConstant(Type::Int32Ty, IterationNum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374 }
3375
3376 // Compute the value of the PHI node for the next iteration.
3377 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
3378 if (NextPHI == 0 || NextPHI == PHIVal)
Dan Gohman0c850912009-06-06 14:37:11 +00003379 return CouldNotCompute; // Couldn't evaluate or not making progress...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003380 PHIVal = NextPHI;
3381 }
3382
3383 // Too many iterations were needed to evaluate.
Dan Gohman0c850912009-06-06 14:37:11 +00003384 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003385}
3386
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003387/// getSCEVAtScope - Return a SCEV expression handle for the specified value
3388/// at the specified scope in the program. The L value specifies a loop
3389/// nest to evaluate the expression at, where null is the top-level or a
3390/// specified loop is immediately inside of the loop.
3391///
3392/// This method can be used to compute the exit value for a variable defined
3393/// in a loop by querying what the value will hold in the parent loop.
3394///
Dan Gohmanaff14d62009-05-24 23:25:42 +00003395/// In the case that a relevant loop exit value cannot be computed, the
3396/// original value V is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003397const SCEV* ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003398 // FIXME: this should be turned into a virtual method on SCEV!
3399
3400 if (isa<SCEVConstant>(V)) return V;
3401
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003402 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003403 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003404 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003406 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003407 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
3408 if (PHINode *PN = dyn_cast<PHINode>(I))
3409 if (PN->getParent() == LI->getHeader()) {
3410 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003411 // to see if the loop that contains it has a known backedge-taken
3412 // count. If so, we may be able to force computation of the exit
3413 // value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003414 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003415 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003416 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 // Okay, we know how many times the containing loop executes. If
3418 // this is a constant evolving PHI node, get the final value at
3419 // the specified iteration number.
3420 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003421 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003422 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003423 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003424 }
3425 }
3426
3427 // Okay, this is an expression that we cannot symbolically evaluate
3428 // into a SCEV. Check to see if it's possible to symbolically evaluate
3429 // the arguments into constants, and if so, try to constant propagate the
3430 // result. This is particularly useful for computing loop exit values.
3431 if (CanConstantFold(I)) {
Dan Gohmanda0071e2009-05-08 20:47:27 +00003432 // Check to see if we've folded this instruction at this loop before.
3433 std::map<const Loop *, Constant *> &Values = ValuesAtScopes[I];
3434 std::pair<std::map<const Loop *, Constant *>::iterator, bool> Pair =
3435 Values.insert(std::make_pair(L, static_cast<Constant *>(0)));
3436 if (!Pair.second)
3437 return Pair.first->second ? &*getUnknown(Pair.first->second) : V;
3438
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003439 std::vector<Constant*> Operands;
3440 Operands.reserve(I->getNumOperands());
3441 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
3442 Value *Op = I->getOperand(i);
3443 if (Constant *C = dyn_cast<Constant>(Op)) {
3444 Operands.push_back(C);
3445 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00003446 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00003447 // non-integer and non-pointer, don't even try to analyze them
3448 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00003449 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00003450 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00003451
Owen Andersonecd0cd72009-06-22 21:39:50 +00003452 const SCEV* OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003453 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003454 Constant *C = SC->getValue();
3455 if (C->getType() != Op->getType())
3456 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3457 Op->getType(),
3458 false),
3459 C, Op->getType());
3460 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00003461 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00003462 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
3463 if (C->getType() != Op->getType())
3464 C =
3465 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
3466 Op->getType(),
3467 false),
3468 C, Op->getType());
3469 Operands.push_back(C);
3470 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003471 return V;
3472 } else {
3473 return V;
3474 }
3475 }
3476 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00003477
3478 Constant *C;
3479 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
3480 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
3481 &Operands[0], Operands.size());
3482 else
3483 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
3484 &Operands[0], Operands.size());
Dan Gohmanda0071e2009-05-08 20:47:27 +00003485 Pair.first->second = C;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003486 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003487 }
3488 }
3489
3490 // This is some other type of SCEVUnknown, just return it.
3491 return V;
3492 }
3493
Dan Gohmanc76b5452009-05-04 22:02:23 +00003494 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003495 // Avoid performing the look-up in the common case where the specified
3496 // expression has no loop-variant portions.
3497 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003498 const SCEV* OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003499 if (OpAtScope != Comm->getOperand(i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003500 // Okay, at least one of these operands is loop variant but might be
3501 // foldable. Build a new instance of the folded commutative expression.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003502 SmallVector<const SCEV*, 8> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003503 NewOps.push_back(OpAtScope);
3504
3505 for (++i; i != e; ++i) {
3506 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507 NewOps.push_back(OpAtScope);
3508 }
3509 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003510 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003511 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003512 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003513 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003514 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00003515 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003516 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00003517 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 }
3519 }
3520 // If we got here, all operands are loop invariant.
3521 return Comm;
3522 }
3523
Dan Gohmanc76b5452009-05-04 22:02:23 +00003524 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003525 const SCEV* LHS = getSCEVAtScope(Div->getLHS(), L);
3526 const SCEV* RHS = getSCEVAtScope(Div->getRHS(), L);
Nick Lewycky35b56022009-01-13 09:18:58 +00003527 if (LHS == Div->getLHS() && RHS == Div->getRHS())
3528 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003529 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003530 }
3531
3532 // If this is a loop recurrence for a loop that does not contain L, then we
3533 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003534 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003535 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
3536 // To evaluate this recurrence, we need to know how many times the AddRec
3537 // loop iterates. Compute this now.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003538 const SCEV* BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
Dan Gohman0c850912009-06-06 14:37:11 +00003539 if (BackedgeTakenCount == CouldNotCompute) return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003540
Eli Friedman7489ec92008-08-04 23:49:06 +00003541 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003542 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543 }
Dan Gohmanaff14d62009-05-24 23:25:42 +00003544 return AddRec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003545 }
3546
Dan Gohmanc76b5452009-05-04 22:02:23 +00003547 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003548 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003549 if (Op == Cast->getOperand())
3550 return Cast; // must be loop invariant
3551 return getZeroExtendExpr(Op, Cast->getType());
3552 }
3553
Dan Gohmanc76b5452009-05-04 22:02:23 +00003554 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003555 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003556 if (Op == Cast->getOperand())
3557 return Cast; // must be loop invariant
3558 return getSignExtendExpr(Op, Cast->getType());
3559 }
3560
Dan Gohmanc76b5452009-05-04 22:02:23 +00003561 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00003562 const SCEV* Op = getSCEVAtScope(Cast->getOperand(), L);
Dan Gohman78d63c82009-04-29 22:29:01 +00003563 if (Op == Cast->getOperand())
3564 return Cast; // must be loop invariant
3565 return getTruncateExpr(Op, Cast->getType());
3566 }
3567
3568 assert(0 && "Unknown SCEV type!");
Daniel Dunbara95d96c2009-05-18 16:43:04 +00003569 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570}
3571
Dan Gohmandd40e9a2009-05-08 20:38:54 +00003572/// getSCEVAtScope - This is a convenience function which does
3573/// getSCEVAtScope(getSCEV(V), L).
Owen Andersonecd0cd72009-06-22 21:39:50 +00003574const SCEV* ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003575 return getSCEVAtScope(getSCEV(V), L);
3576}
3577
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003578/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
3579/// following equation:
3580///
3581/// A * X = B (mod N)
3582///
3583/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
3584/// A and B isn't important.
3585///
3586/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003587static const SCEV* SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003588 ScalarEvolution &SE) {
3589 uint32_t BW = A.getBitWidth();
3590 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
3591 assert(A != 0 && "A must be non-zero.");
3592
3593 // 1. D = gcd(A, N)
3594 //
3595 // The gcd of A and N may have only one prime factor: 2. The number of
3596 // trailing zeros in A is its multiplicity
3597 uint32_t Mult2 = A.countTrailingZeros();
3598 // D = 2^Mult2
3599
3600 // 2. Check if B is divisible by D.
3601 //
3602 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
3603 // is not less than multiplicity of this prime factor for D.
3604 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00003605 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003606
3607 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
3608 // modulo (N / D).
3609 //
3610 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
3611 // bit width during computations.
3612 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
3613 APInt Mod(BW + 1, 0);
3614 Mod.set(BW - Mult2); // Mod = N / D
3615 APInt I = AD.multiplicativeInverse(Mod);
3616
3617 // 4. Compute the minimum unsigned root of the equation:
3618 // I * (B / D) mod (N / D)
3619 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
3620
3621 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
3622 // bits.
3623 return SE.getConstant(Result.trunc(BW));
3624}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003625
3626/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
3627/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
3628/// might be the same) or two SCEVCouldNotCompute objects.
3629///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003630static std::pair<const SCEV*,const SCEV*>
Dan Gohman89f85052007-10-22 18:31:58 +00003631SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003632 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00003633 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
3634 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
3635 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003636
3637 // We currently can only solve this if the coefficients are constants.
3638 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003639 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003640 return std::make_pair(CNC, CNC);
3641 }
3642
3643 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
3644 const APInt &L = LC->getValue()->getValue();
3645 const APInt &M = MC->getValue()->getValue();
3646 const APInt &N = NC->getValue()->getValue();
3647 APInt Two(BitWidth, 2);
3648 APInt Four(BitWidth, 4);
3649
3650 {
3651 using namespace APIntOps;
3652 const APInt& C = L;
3653 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
3654 // The B coefficient is M-N/2
3655 APInt B(M);
3656 B -= sdiv(N,Two);
3657
3658 // The A coefficient is N/2
3659 APInt A(N.sdiv(Two));
3660
3661 // Compute the B^2-4ac term.
3662 APInt SqrtTerm(B);
3663 SqrtTerm *= B;
3664 SqrtTerm -= Four * (A * C);
3665
3666 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
3667 // integer value or else APInt::sqrt() will assert.
3668 APInt SqrtVal(SqrtTerm.sqrt());
3669
3670 // Compute the two solutions for the quadratic formula.
3671 // The divisions must be performed as signed divisions.
3672 APInt NegB(-B);
3673 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00003674 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00003675 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00003676 return std::make_pair(CNC, CNC);
3677 }
3678
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003679 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
3680 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
3681
Dan Gohman89f85052007-10-22 18:31:58 +00003682 return std::make_pair(SE.getConstant(Solution1),
3683 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003684 } // end APIntOps namespace
3685}
3686
3687/// HowFarToZero - Return the number of times a backedge comparing the specified
Dan Gohman0c850912009-06-06 14:37:11 +00003688/// value to zero will execute. If not computable, return CouldNotCompute.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003689const SCEV* ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003690 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00003691 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692 // If the value is already zero, the branch will execute zero times.
3693 if (C->getValue()->isZero()) return C;
Dan Gohman0c850912009-06-06 14:37:11 +00003694 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695 }
3696
Dan Gohmanbff6b582009-05-04 22:30:44 +00003697 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003699 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003700
3701 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003702 // If this is an affine expression, the execution count of this branch is
3703 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003705 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003706 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003707 // equivalent to:
3708 //
3709 // Step*N = -Start (mod 2^BW)
3710 //
3711 // where BW is the common bit width of Start and Step.
3712
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003713 // Get the initial value for the loop.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003714 const SCEV* Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
3715 const SCEV* Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003716
Dan Gohmanc76b5452009-05-04 22:02:23 +00003717 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003718 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003719
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003720 // First, handle unitary steps.
3721 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003722 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003723 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
3724 return Start; // N = Start (as unsigned)
3725
3726 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003727 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00003728 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003729 -StartC->getValue()->getValue(),
3730 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003731 }
3732 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
3733 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
3734 // the quadratic equation to solve it.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003735 std::pair<const SCEV*,const SCEV*> Roots = SolveQuadraticEquation(AddRec,
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003736 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003737 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3738 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003739 if (R1) {
3740#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003741 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3742 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003743#endif
3744 // Pick the smallest positive root value.
3745 if (ConstantInt *CB =
3746 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3747 R1->getValue(), R2->getValue()))) {
3748 if (CB->getZExtValue() == false)
3749 std::swap(R1, R2); // R1 is the minimum root now.
3750
3751 // We can only use this value if the chrec ends up with an exact zero
3752 // value at this index. When solving for "X*X != 5", for example, we
3753 // should not accept a root of 2.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003754 const SCEV* Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003755 if (Val->isZero())
3756 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003757 }
3758 }
3759 }
3760
Dan Gohman0c850912009-06-06 14:37:11 +00003761 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003762}
3763
3764/// HowFarToNonZero - Return the number of times a backedge checking the
3765/// specified value for nonzero will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003766/// CouldNotCompute
Owen Andersonecd0cd72009-06-22 21:39:50 +00003767const SCEV* ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003768 // Loops that look like: while (X == 0) are very strange indeed. We don't
3769 // handle them yet except for the trivial case. This could be expanded in the
3770 // future as needed.
3771
3772 // If the value is a constant, check to see if it is known to be non-zero
3773 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003774 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003775 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003776 return getIntegerSCEV(0, C->getType());
Dan Gohman0c850912009-06-06 14:37:11 +00003777 return CouldNotCompute; // Otherwise it will loop infinitely.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003778 }
3779
3780 // We could implement others, but I really doubt anyone writes loops like
3781 // this, and if they did, they would already be constant folded.
Dan Gohman0c850912009-06-06 14:37:11 +00003782 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003783}
3784
Dan Gohmanab157b22009-05-18 15:36:09 +00003785/// getLoopPredecessor - If the given loop's header has exactly one unique
3786/// predecessor outside the loop, return it. Otherwise return null.
3787///
3788BasicBlock *ScalarEvolution::getLoopPredecessor(const Loop *L) {
3789 BasicBlock *Header = L->getHeader();
3790 BasicBlock *Pred = 0;
3791 for (pred_iterator PI = pred_begin(Header), E = pred_end(Header);
3792 PI != E; ++PI)
3793 if (!L->contains(*PI)) {
3794 if (Pred && Pred != *PI) return 0; // Multiple predecessors.
3795 Pred = *PI;
3796 }
3797 return Pred;
3798}
3799
Dan Gohman1cddf972008-09-15 22:18:04 +00003800/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3801/// (which may not be an immediate predecessor) which has exactly one
3802/// successor from which BB is reachable, or null if no such block is
3803/// found.
3804///
3805BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003806ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003807 // If the block has a unique predecessor, then there is no path from the
3808 // predecessor to the block that does not go through the direct edge
3809 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003810 if (BasicBlock *Pred = BB->getSinglePredecessor())
3811 return Pred;
3812
3813 // A loop's header is defined to be a block that dominates the loop.
Dan Gohmanab157b22009-05-18 15:36:09 +00003814 // If the header has a unique predecessor outside the loop, it must be
3815 // a block that has exactly one successor that can reach the loop.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003816 if (Loop *L = LI->getLoopFor(BB))
Dan Gohmanab157b22009-05-18 15:36:09 +00003817 return getLoopPredecessor(L);
Dan Gohman1cddf972008-09-15 22:18:04 +00003818
3819 return 0;
3820}
3821
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003822/// HasSameValue - SCEV structural equivalence is usually sufficient for
3823/// testing whether two expressions are equal, however for the purposes of
3824/// looking for a condition guarding a loop, it can be useful to be a little
3825/// more general, since a front-end may have replicated the controlling
3826/// expression.
3827///
Owen Andersonecd0cd72009-06-22 21:39:50 +00003828static bool HasSameValue(const SCEV* A, const SCEV* B) {
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003829 // Quick check to see if they are the same SCEV.
3830 if (A == B) return true;
3831
3832 // Otherwise, if they're both SCEVUnknown, it's possible that they hold
3833 // two different instructions with the same value. Check for this case.
3834 if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
3835 if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
3836 if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
3837 if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
3838 if (AI->isIdenticalTo(BI))
3839 return true;
3840
3841 // Otherwise assume they may have a different value.
3842 return false;
3843}
3844
Dan Gohmancacd2012009-02-12 22:19:27 +00003845/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003846/// a conditional between LHS and RHS. This is used to help avoid max
3847/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003848bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003849 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003850 const SCEV *LHS, const SCEV *RHS) {
Dan Gohman8b938182009-05-18 16:03:58 +00003851 // Interpret a null as meaning no loop, where there is obviously no guard
3852 // (interprocedural conditions notwithstanding).
3853 if (!L) return false;
3854
Dan Gohmanab157b22009-05-18 15:36:09 +00003855 BasicBlock *Predecessor = getLoopPredecessor(L);
3856 BasicBlock *PredecessorDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003857
Dan Gohmanab157b22009-05-18 15:36:09 +00003858 // Starting at the loop predecessor, climb up the predecessor chain, as long
3859 // as there are predecessors that can be found that have unique successors
Dan Gohman1cddf972008-09-15 22:18:04 +00003860 // leading to the original header.
Dan Gohmanab157b22009-05-18 15:36:09 +00003861 for (; Predecessor;
3862 PredecessorDest = Predecessor,
3863 Predecessor = getPredecessorWithUniqueSuccessorForBB(Predecessor)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003864
3865 BranchInst *LoopEntryPredicate =
Dan Gohmanab157b22009-05-18 15:36:09 +00003866 dyn_cast<BranchInst>(Predecessor->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003867 if (!LoopEntryPredicate ||
3868 LoopEntryPredicate->isUnconditional())
3869 continue;
3870
3871 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3872 if (!ICI) continue;
3873
3874 // Now that we found a conditional branch that dominates the loop, check to
3875 // see if it is the comparison we are looking for.
3876 Value *PreCondLHS = ICI->getOperand(0);
3877 Value *PreCondRHS = ICI->getOperand(1);
3878 ICmpInst::Predicate Cond;
Dan Gohmanab157b22009-05-18 15:36:09 +00003879 if (LoopEntryPredicate->getSuccessor(0) == PredecessorDest)
Dan Gohmanab678fb2008-08-12 20:17:31 +00003880 Cond = ICI->getPredicate();
3881 else
3882 Cond = ICI->getInversePredicate();
3883
Dan Gohmancacd2012009-02-12 22:19:27 +00003884 if (Cond == Pred)
3885 ; // An exact match.
3886 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3887 ; // The actual condition is beyond sufficient.
3888 else
3889 // Check a few special cases.
3890 switch (Cond) {
3891 case ICmpInst::ICMP_UGT:
3892 if (Pred == ICmpInst::ICMP_ULT) {
3893 std::swap(PreCondLHS, PreCondRHS);
3894 Cond = ICmpInst::ICMP_ULT;
3895 break;
3896 }
3897 continue;
3898 case ICmpInst::ICMP_SGT:
3899 if (Pred == ICmpInst::ICMP_SLT) {
3900 std::swap(PreCondLHS, PreCondRHS);
3901 Cond = ICmpInst::ICMP_SLT;
3902 break;
3903 }
3904 continue;
3905 case ICmpInst::ICMP_NE:
3906 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3907 // so check for this case by checking if the NE is comparing against
3908 // a minimum or maximum constant.
3909 if (!ICmpInst::isTrueWhenEqual(Pred))
3910 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3911 const APInt &A = CI->getValue();
3912 switch (Pred) {
3913 case ICmpInst::ICMP_SLT:
3914 if (A.isMaxSignedValue()) break;
3915 continue;
3916 case ICmpInst::ICMP_SGT:
3917 if (A.isMinSignedValue()) break;
3918 continue;
3919 case ICmpInst::ICMP_ULT:
3920 if (A.isMaxValue()) break;
3921 continue;
3922 case ICmpInst::ICMP_UGT:
3923 if (A.isMinValue()) break;
3924 continue;
3925 default:
3926 continue;
3927 }
3928 Cond = ICmpInst::ICMP_NE;
3929 // NE is symmetric but the original comparison may not be. Swap
3930 // the operands if necessary so that they match below.
3931 if (isa<SCEVConstant>(LHS))
3932 std::swap(PreCondLHS, PreCondRHS);
3933 break;
3934 }
3935 continue;
3936 default:
3937 // We weren't able to reconcile the condition.
3938 continue;
3939 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003940
3941 if (!PreCondLHS->getType()->isInteger()) continue;
3942
Owen Andersonecd0cd72009-06-22 21:39:50 +00003943 const SCEV* PreCondLHSSCEV = getSCEV(PreCondLHS);
3944 const SCEV* PreCondRHSSCEV = getSCEV(PreCondRHS);
Dan Gohmanbc1e3472009-06-20 00:35:32 +00003945 if ((HasSameValue(LHS, PreCondLHSSCEV) &&
3946 HasSameValue(RHS, PreCondRHSSCEV)) ||
3947 (HasSameValue(LHS, getNotSCEV(PreCondRHSSCEV)) &&
3948 HasSameValue(RHS, getNotSCEV(PreCondLHSSCEV))))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003949 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003950 }
3951
Dan Gohmanab678fb2008-08-12 20:17:31 +00003952 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003953}
3954
Dan Gohmand2b62c42009-06-21 23:46:38 +00003955/// getBECount - Subtract the end and start values and divide by the step,
3956/// rounding up, to get the number of times the backedge is executed. Return
3957/// CouldNotCompute if an intermediate computation overflows.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003958const SCEV* ScalarEvolution::getBECount(const SCEV* Start,
3959 const SCEV* End,
3960 const SCEV* Step) {
Dan Gohmand2b62c42009-06-21 23:46:38 +00003961 const Type *Ty = Start->getType();
Owen Andersonecd0cd72009-06-22 21:39:50 +00003962 const SCEV* NegOne = getIntegerSCEV(-1, Ty);
3963 const SCEV* Diff = getMinusSCEV(End, Start);
3964 const SCEV* RoundUp = getAddExpr(Step, NegOne);
Dan Gohmand2b62c42009-06-21 23:46:38 +00003965
3966 // Add an adjustment to the difference between End and Start so that
3967 // the division will effectively round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00003968 const SCEV* Add = getAddExpr(Diff, RoundUp);
Dan Gohmand2b62c42009-06-21 23:46:38 +00003969
3970 // Check Add for unsigned overflow.
3971 // TODO: More sophisticated things could be done here.
3972 const Type *WideTy = IntegerType::get(getTypeSizeInBits(Ty) + 1);
Owen Andersonecd0cd72009-06-22 21:39:50 +00003973 const SCEV* OperandExtendedAdd =
Dan Gohmand2b62c42009-06-21 23:46:38 +00003974 getAddExpr(getZeroExtendExpr(Diff, WideTy),
3975 getZeroExtendExpr(RoundUp, WideTy));
3976 if (getZeroExtendExpr(Add, WideTy) != OperandExtendedAdd)
3977 return CouldNotCompute;
3978
3979 return getUDivExpr(Add, Step);
3980}
3981
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003982/// HowManyLessThans - Return the number of times a backedge containing the
3983/// specified less-than comparison will execute. If not computable, return
Dan Gohman0c850912009-06-06 14:37:11 +00003984/// CouldNotCompute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003985ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003986HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3987 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003988 // Only handle: "ADDREC < LoopInvariant".
Dan Gohman0c850912009-06-06 14:37:11 +00003989 if (!RHS->isLoopInvariant(L)) return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003990
Dan Gohmanbff6b582009-05-04 22:30:44 +00003991 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003992 if (!AddRec || AddRec->getLoop() != L)
Dan Gohman0c850912009-06-06 14:37:11 +00003993 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003994
3995 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003996 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003997 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00003998 const SCEV* Step = AddRec->getStepRecurrence(*this);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003999
4000 // TODO: handle non-constant strides.
4001 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
4002 if (!CStep || CStep->isZero())
Dan Gohman0c850912009-06-06 14:37:11 +00004003 return CouldNotCompute;
Dan Gohmanf8bc8e82009-05-18 15:22:39 +00004004 if (CStep->isOne()) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004005 // With unit stride, the iteration never steps past the limit value.
4006 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
4007 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
4008 // Test whether a positive iteration iteration can step past the limit
4009 // value and past the maximum value for its type in a single step.
4010 if (isSigned) {
4011 APInt Max = APInt::getSignedMaxValue(BitWidth);
4012 if ((Max - CStep->getValue()->getValue())
4013 .slt(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004014 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004015 } else {
4016 APInt Max = APInt::getMaxValue(BitWidth);
4017 if ((Max - CStep->getValue()->getValue())
4018 .ult(CLimit->getValue()->getValue()))
Dan Gohman0c850912009-06-06 14:37:11 +00004019 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004020 }
4021 } else
4022 // TODO: handle non-constant limit values below.
Dan Gohman0c850912009-06-06 14:37:11 +00004023 return CouldNotCompute;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004024 } else
4025 // TODO: handle negative strides below.
Dan Gohman0c850912009-06-06 14:37:11 +00004026 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004027
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004028 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
4029 // m. So, we count the number of iterations in which {n,+,s} < m is true.
4030 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00004031 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004032
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004033 // First, we get the value of the LHS in the first iteration: n
Owen Andersonecd0cd72009-06-22 21:39:50 +00004034 const SCEV* Start = AddRec->getOperand(0);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004035
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004036 // Determine the minimum constant start value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004037 const SCEV* MinStart = isa<SCEVConstant>(Start) ? Start :
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004038 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
4039 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00004040
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004041 // If we know that the condition is true in order to enter the loop,
4042 // then we know that it will run exactly (m-n)/s times. Otherwise, we
Dan Gohmanc8a29272009-05-24 23:45:28 +00004043 // only know that it will execute (max(m,n)-n)/s times. In both cases,
4044 // the division must round up.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004045 const SCEV* End = RHS;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004046 if (!isLoopGuardedByCond(L,
4047 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
4048 getMinusSCEV(Start, Step), RHS))
4049 End = isSigned ? getSMaxExpr(RHS, Start)
4050 : getUMaxExpr(RHS, Start);
4051
4052 // Determine the maximum constant end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004053 const SCEV* MaxEnd =
Dan Gohman92369c32009-06-20 00:32:22 +00004054 isa<SCEVConstant>(End) ? End :
4055 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth)
4056 .ashr(GetMinSignBits(End) - 1) :
4057 APInt::getMaxValue(BitWidth)
4058 .lshr(GetMinLeadingZeros(End)));
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004059
4060 // Finally, we subtract these two values and divide, rounding up, to get
4061 // the number of times the backedge is executed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004062 const SCEV* BECount = getBECount(Start, End, Step);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004063
4064 // The maximum backedge count is similar, except using the minimum start
4065 // value and the maximum end value.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004066 const SCEV* MaxBECount = getBECount(MinStart, MaxEnd, Step);;
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00004067
4068 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004069 }
4070
Dan Gohman0c850912009-06-06 14:37:11 +00004071 return CouldNotCompute;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004072}
4073
4074/// getNumIterationsInRange - Return the number of iterations of this loop that
4075/// produce values in the specified constant range. Another way of looking at
4076/// this is that it returns the first iteration number where the value is not in
4077/// the condition, thus computing the exit count. If the iteration count can't
4078/// be computed, an instance of SCEVCouldNotCompute is returned.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004079const SCEV* SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
Dan Gohman89f85052007-10-22 18:31:58 +00004080 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004081 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004082 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004083
4084 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00004085 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004086 if (!SC->getValue()->isZero()) {
Owen Andersonecd0cd72009-06-22 21:39:50 +00004087 SmallVector<const SCEV*, 4> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004088 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
Owen Andersonecd0cd72009-06-22 21:39:50 +00004089 const SCEV* Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00004090 if (const SCEVAddRecExpr *ShiftedAddRec =
4091 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004092 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00004093 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004094 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00004095 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004096 }
4097
4098 // The only time we can solve this is when we have all constant indices.
4099 // Otherwise, we cannot determine the overflow conditions.
4100 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
4101 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004102 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004103
4104
4105 // Okay at this point we know that all elements of the chrec are constants and
4106 // that the start element is zero.
4107
4108 // First check to see if the range contains zero. If not, the first
4109 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00004110 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00004111 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman8fd520a2009-06-15 22:12:54 +00004112 return SE.getIntegerSCEV(0, getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004113
4114 if (isAffine()) {
4115 // If this is an affine expression then we have this situation:
4116 // Solve {0,+,A} in Range === Ax in Range
4117
4118 // We know that zero is in the range. If A is positive then we know that
4119 // the upper value of the range must be the first possible exit value.
4120 // If A is negative then the lower of the range is the last possible loop
4121 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00004122 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004123 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
4124 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
4125
4126 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00004127 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004128 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
4129
4130 // Evaluate at the exit value. If we really did fall out of the valid
4131 // range, then we computed our trip count, otherwise wrap around or other
4132 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00004133 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004134 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00004135 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004136
4137 // Ensure that the previous value is in the range. This is a sanity check.
4138 assert(Range.contains(
4139 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004140 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004141 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00004142 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143 } else if (isQuadratic()) {
4144 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
4145 // quadratic equation to solve it. To do this, we must frame our problem in
4146 // terms of figuring out when zero is crossed, instead of when
4147 // Range.getUpper() is crossed.
Owen Andersonecd0cd72009-06-22 21:39:50 +00004148 SmallVector<const SCEV*, 4> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00004149 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
Owen Andersonecd0cd72009-06-22 21:39:50 +00004150 const SCEV* NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004151
4152 // Next, solve the constructed addrec
Owen Andersonecd0cd72009-06-22 21:39:50 +00004153 std::pair<const SCEV*,const SCEV*> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00004154 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004155 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
4156 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004157 if (R1) {
4158 // Pick the smallest positive root value.
4159 if (ConstantInt *CB =
4160 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
4161 R1->getValue(), R2->getValue()))) {
4162 if (CB->getZExtValue() == false)
4163 std::swap(R1, R2); // R1 is the minimum root now.
4164
4165 // Make sure the root is not off by one. The returned iteration should
4166 // not be in the range, but the previous one should be. When solving
4167 // for "X*X < 5", for example, we should not return a root of 2.
4168 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00004169 R1->getValue(),
4170 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004171 if (Range.contains(R1Val->getValue())) {
4172 // The next iteration must be out of the range...
4173 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
4174
Dan Gohman89f85052007-10-22 18:31:58 +00004175 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004176 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00004177 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00004178 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004179 }
4180
4181 // If R1 was not in the range, then it is a good return value. Make
4182 // sure that R1-1 WAS in the range though, just in case.
4183 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00004184 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004185 if (Range.contains(R1Val->getValue()))
4186 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00004187 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004188 }
4189 }
4190 }
4191
Dan Gohman0ad08b02009-04-18 17:58:19 +00004192 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004193}
4194
4195
4196
4197//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00004198// SCEVCallbackVH Class Implementation
4199//===----------------------------------------------------------------------===//
4200
Dan Gohman999d14e2009-05-19 19:22:47 +00004201void ScalarEvolution::SCEVCallbackVH::deleted() {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004202 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4203 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
4204 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004205 if (Instruction *I = dyn_cast<Instruction>(getValPtr()))
4206 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004207 SE->Scalars.erase(getValPtr());
4208 // this now dangles!
4209}
4210
Dan Gohman999d14e2009-05-19 19:22:47 +00004211void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00004212 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
4213
4214 // Forget all the expressions associated with users of the old value,
4215 // so that future queries will recompute the expressions using the new
4216 // value.
4217 SmallVector<User *, 16> Worklist;
4218 Value *Old = getValPtr();
4219 bool DeleteOld = false;
4220 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
4221 UI != UE; ++UI)
4222 Worklist.push_back(*UI);
4223 while (!Worklist.empty()) {
4224 User *U = Worklist.pop_back_val();
4225 // Deleting the Old value will cause this to dangle. Postpone
4226 // that until everything else is done.
4227 if (U == Old) {
4228 DeleteOld = true;
4229 continue;
4230 }
4231 if (PHINode *PN = dyn_cast<PHINode>(U))
4232 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004233 if (Instruction *I = dyn_cast<Instruction>(U))
4234 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004235 if (SE->Scalars.erase(U))
4236 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
4237 UI != UE; ++UI)
4238 Worklist.push_back(*UI);
4239 }
4240 if (DeleteOld) {
4241 if (PHINode *PN = dyn_cast<PHINode>(Old))
4242 SE->ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohmanda0071e2009-05-08 20:47:27 +00004243 if (Instruction *I = dyn_cast<Instruction>(Old))
4244 SE->ValuesAtScopes.erase(I);
Dan Gohmanbff6b582009-05-04 22:30:44 +00004245 SE->Scalars.erase(Old);
4246 // this now dangles!
4247 }
4248 // this may dangle!
4249}
4250
Dan Gohman999d14e2009-05-19 19:22:47 +00004251ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
Dan Gohmanbff6b582009-05-04 22:30:44 +00004252 : CallbackVH(V), SE(se) {}
4253
4254//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255// ScalarEvolution Class Implementation
4256//===----------------------------------------------------------------------===//
4257
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004258ScalarEvolution::ScalarEvolution()
Owen Andersonb70139d2009-06-22 21:57:23 +00004259 : FunctionPass(&ID), CouldNotCompute(new SCEVCouldNotCompute()) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004260}
4261
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004262bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004263 this->F = &F;
4264 LI = &getAnalysis<LoopInfo>();
4265 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004266 return false;
4267}
4268
4269void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004270 Scalars.clear();
4271 BackedgeTakenCounts.clear();
4272 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanda0071e2009-05-08 20:47:27 +00004273 ValuesAtScopes.clear();
Owen Andersonc48fbfe2009-06-22 18:25:46 +00004274
4275 for (std::map<ConstantInt*, SCEVConstant*>::iterator
4276 I = SCEVConstants.begin(), E = SCEVConstants.end(); I != E; ++I)
4277 delete I->second;
4278 for (std::map<std::pair<const SCEV*, const Type*>,
4279 SCEVTruncateExpr*>::iterator I = SCEVTruncates.begin(),
4280 E = SCEVTruncates.end(); I != E; ++I)
4281 delete I->second;
4282 for (std::map<std::pair<const SCEV*, const Type*>,
4283 SCEVZeroExtendExpr*>::iterator I = SCEVZeroExtends.begin(),
4284 E = SCEVZeroExtends.end(); I != E; ++I)
4285 delete I->second;
4286 for (std::map<std::pair<unsigned, std::vector<const SCEV*> >,
4287 SCEVCommutativeExpr*>::iterator I = SCEVCommExprs.begin(),
4288 E = SCEVCommExprs.end(); I != E; ++I)
4289 delete I->second;
4290 for (std::map<std::pair<const SCEV*, const SCEV*>, SCEVUDivExpr*>::iterator
4291 I = SCEVUDivs.begin(), E = SCEVUDivs.end(); I != E; ++I)
4292 delete I->second;
4293 for (std::map<std::pair<const SCEV*, const Type*>,
4294 SCEVSignExtendExpr*>::iterator I = SCEVSignExtends.begin(),
4295 E = SCEVSignExtends.end(); I != E; ++I)
4296 delete I->second;
4297 for (std::map<std::pair<const Loop *, std::vector<const SCEV*> >,
4298 SCEVAddRecExpr*>::iterator I = SCEVAddRecExprs.begin(),
4299 E = SCEVAddRecExprs.end(); I != E; ++I)
4300 delete I->second;
4301 for (std::map<Value*, SCEVUnknown*>::iterator I = SCEVUnknowns.begin(),
4302 E = SCEVUnknowns.end(); I != E; ++I)
4303 delete I->second;
4304
4305 SCEVConstants.clear();
4306 SCEVTruncates.clear();
4307 SCEVZeroExtends.clear();
4308 SCEVCommExprs.clear();
4309 SCEVUDivs.clear();
4310 SCEVSignExtends.clear();
4311 SCEVAddRecExprs.clear();
4312 SCEVUnknowns.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313}
4314
4315void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
4316 AU.setPreservesAll();
4317 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00004318}
4319
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004320bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004321 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004322}
4323
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004324static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004325 const Loop *L) {
4326 // Print all inner loops first
4327 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
4328 PrintLoopInfo(OS, SE, *I);
4329
Nick Lewyckye5da1912008-01-02 02:49:20 +00004330 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004331
Devang Patel02451fa2007-08-21 00:31:24 +00004332 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004333 L->getExitBlocks(ExitBlocks);
4334 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00004335 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004336
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004337 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
4338 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004339 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00004340 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004341 }
4342
Nick Lewyckye5da1912008-01-02 02:49:20 +00004343 OS << "\n";
Dan Gohmanb6b9e9e2009-06-24 00:33:16 +00004344 OS << "Loop " << L->getHeader()->getName() << ": ";
4345
4346 if (!isa<SCEVCouldNotCompute>(SE->getMaxBackedgeTakenCount(L))) {
4347 OS << "max backedge-taken count is " << *SE->getMaxBackedgeTakenCount(L);
4348 } else {
4349 OS << "Unpredictable max backedge-taken count. ";
4350 }
4351
4352 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004353}
4354
Dan Gohman13058cc2009-04-21 00:47:46 +00004355void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004356 // ScalarEvolution's implementaiton of the print method is to print
4357 // out SCEV values of all instructions that are interesting. Doing
4358 // this potentially causes it to create new SCEV objects though,
4359 // which technically conflicts with the const qualifier. This isn't
4360 // observable from outside the class though (the hasSCEV function
4361 // notwithstanding), so casting away the const isn't dangerous.
4362 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004363
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004364 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004365 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00004366 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004367 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00004368 OS << " --> ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004369 const SCEV* SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004370 SV->print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004371
Dan Gohman8db598a2009-06-19 17:49:54 +00004372 const Loop *L = LI->getLoopFor((*I).getParent());
4373
Owen Andersonecd0cd72009-06-22 21:39:50 +00004374 const SCEV* AtUse = SE.getSCEVAtScope(SV, L);
Dan Gohman8db598a2009-06-19 17:49:54 +00004375 if (AtUse != SV) {
4376 OS << " --> ";
4377 AtUse->print(OS);
4378 }
4379
4380 if (L) {
Dan Gohmane5b60842009-06-18 00:37:45 +00004381 OS << "\t\t" "Exits: ";
Owen Andersonecd0cd72009-06-22 21:39:50 +00004382 const SCEV* ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
Dan Gohmanaff14d62009-05-24 23:25:42 +00004383 if (!ExitValue->isLoopInvariant(L)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004384 OS << "<<Unknown>>";
4385 } else {
4386 OS << *ExitValue;
4387 }
4388 }
4389
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004390 OS << "\n";
4391 }
4392
Dan Gohmanffd36ba2009-04-21 23:15:49 +00004393 OS << "Determining loop execution counts for: " << F->getName() << "\n";
4394 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
4395 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004396}
Dan Gohman13058cc2009-04-21 00:47:46 +00004397
4398void ScalarEvolution::print(std::ostream &o, const Module *M) const {
4399 raw_os_ostream OS(o);
4400 print(OS, M);
4401}