blob: 1a5ef7ef9589fc5db22e116ded746ac9cc0d82a9 [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
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// 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"
71#include "llvm/Assembly/Writer.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000072#include "llvm/Target/TargetData.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000073#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
Dan Gohman01c2ee72009-04-16 03:18:22 +000076#include "llvm/Support/GetElementPtrTypeIterator.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000077#include "llvm/Support/InstIterator.h"
78#include "llvm/Support/ManagedStatic.h"
79#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 <ostream>
84#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085using namespace llvm;
86
Dan Gohmanf17a25c2007-07-18 16:29:46 +000087STATISTIC(NumArrayLenItCounts,
88 "Number of trip counts computed with array length");
89STATISTIC(NumTripCountsComputed,
90 "Number of loops with predictable loop counts");
91STATISTIC(NumTripCountsNotComputed,
92 "Number of loops without predictable loop counts");
93STATISTIC(NumBruteForceTripCountsComputed,
94 "Number of loops with trip counts computed by force");
95
Dan Gohman089efff2008-05-13 00:00:25 +000096static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000097MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
98 cl::desc("Maximum number of iterations SCEV will "
99 "symbolically execute a constant derived loop"),
100 cl::init(100));
101
Dan Gohman089efff2008-05-13 00:00:25 +0000102static RegisterPass<ScalarEvolution>
103R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000104char ScalarEvolution::ID = 0;
105
106//===----------------------------------------------------------------------===//
107// SCEV class definitions
108//===----------------------------------------------------------------------===//
109
110//===----------------------------------------------------------------------===//
111// Implementation of the SCEV class.
112//
113SCEV::~SCEV() {}
114void SCEV::dump() const {
Dan Gohman13058cc2009-04-21 00:47:46 +0000115 print(errs());
116 errs() << '\n';
117}
118
119void SCEV::print(std::ostream &o) const {
120 raw_os_ostream OS(o);
121 print(OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122}
123
Dan Gohman7b560c42008-06-18 16:23:07 +0000124bool SCEV::isZero() const {
125 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
126 return SC->getValue()->isZero();
127 return false;
128}
129
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000130
131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
Dan Gohmanffd36ba2009-04-21 23:15:49 +0000132SCEVCouldNotCompute::~SCEVCouldNotCompute() {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133
134bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
135 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
136 return false;
137}
138
139const Type *SCEVCouldNotCompute::getType() const {
140 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
141 return 0;
142}
143
144bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
145 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
146 return false;
147}
148
149SCEVHandle SCEVCouldNotCompute::
150replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000151 const SCEVHandle &Conc,
152 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 return this;
154}
155
Dan Gohman13058cc2009-04-21 00:47:46 +0000156void SCEVCouldNotCompute::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 OS << "***COULDNOTCOMPUTE***";
158}
159
160bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
162}
163
164
165// SCEVConstants - Only allow the creation of one SCEVConstant for any
166// particular value. Don't use a SCEVHandle here, or else the object will
167// never be deleted!
168static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
169
170
171SCEVConstant::~SCEVConstant() {
172 SCEVConstants->erase(V);
173}
174
Dan Gohman89f85052007-10-22 18:31:58 +0000175SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 SCEVConstant *&R = (*SCEVConstants)[V];
177 if (R == 0) R = new SCEVConstant(V);
178 return R;
179}
180
Dan Gohman89f85052007-10-22 18:31:58 +0000181SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
182 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183}
184
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185const Type *SCEVConstant::getType() const { return V->getType(); }
186
Dan Gohman13058cc2009-04-21 00:47:46 +0000187void SCEVConstant::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 WriteAsOperand(OS, V, false);
189}
190
Dan Gohman2a381532009-04-21 01:25:57 +0000191SCEVCastExpr::SCEVCastExpr(unsigned SCEVTy,
192 const SCEVHandle &op, const Type *ty)
193 : SCEV(SCEVTy), Op(op), Ty(ty) {}
194
195SCEVCastExpr::~SCEVCastExpr() {}
196
197bool SCEVCastExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
198 return Op->dominates(BB, DT);
199}
200
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000204static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000205 SCEVTruncateExpr*> > SCEVTruncates;
206
207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000208 : SCEVCastExpr(scTruncate, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000209 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
210 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000211 "Cannot truncate non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000212}
213
214SCEVTruncateExpr::~SCEVTruncateExpr() {
215 SCEVTruncates->erase(std::make_pair(Op, Ty));
216}
217
Dan Gohman13058cc2009-04-21 00:47:46 +0000218void SCEVTruncateExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000219 OS << "(trunc " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220}
221
222// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
223// particular input. Don't use a SCEVHandle here, or else the object will never
224// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000225static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 SCEVZeroExtendExpr*> > SCEVZeroExtends;
227
228SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000229 : 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
235SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
236 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
237}
238
Dan Gohman13058cc2009-04-21 00:47:46 +0000239void SCEVZeroExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000240 OS << "(zext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000241}
242
243// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
244// particular input. Don't use a SCEVHandle here, or else the object will never
245// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000246static ManagedStatic<std::map<std::pair<const SCEV*, const Type*>,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000247 SCEVSignExtendExpr*> > SCEVSignExtends;
248
249SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
Dan Gohman2a381532009-04-21 01:25:57 +0000250 : SCEVCastExpr(scSignExtend, op, ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +0000251 assert((Op->getType()->isInteger() || isa<PointerType>(Op->getType())) &&
252 (Ty->isInteger() || isa<PointerType>(Ty)) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253 "Cannot sign extend non-integer value!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254}
255
256SCEVSignExtendExpr::~SCEVSignExtendExpr() {
257 SCEVSignExtends->erase(std::make_pair(Op, Ty));
258}
259
Dan Gohman13058cc2009-04-21 00:47:46 +0000260void SCEVSignExtendExpr::print(raw_ostream &OS) const {
Dan Gohmanc9119222009-04-29 20:27:52 +0000261 OS << "(sext " << *Op->getType() << " " << *Op << " to " << *Ty << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000262}
263
264// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
265// particular input. Don't use a SCEVHandle here, or else the object will never
266// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000267static ManagedStatic<std::map<std::pair<unsigned, std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000268 SCEVCommutativeExpr*> > SCEVCommExprs;
269
270SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000271 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
272 SCEVCommExprs->erase(std::make_pair(getSCEVType(), SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273}
274
Dan Gohman13058cc2009-04-21 00:47:46 +0000275void SCEVCommutativeExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
277 const char *OpStr = getOperationStr();
278 OS << "(" << *Operands[0];
279 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
280 OS << OpStr << *Operands[i];
281 OS << ")";
282}
283
284SCEVHandle SCEVCommutativeExpr::
285replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000286 const SCEVHandle &Conc,
287 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000289 SCEVHandle H =
290 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291 if (H != getOperand(i)) {
292 std::vector<SCEVHandle> NewOps;
293 NewOps.reserve(getNumOperands());
294 for (unsigned j = 0; j != i; ++j)
295 NewOps.push_back(getOperand(j));
296 NewOps.push_back(H);
297 for (++i; i != e; ++i)
298 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000299 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300
301 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000302 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000303 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000304 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000305 else if (isa<SCEVSMaxExpr>(this))
306 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000307 else if (isa<SCEVUMaxExpr>(this))
308 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000309 else
310 assert(0 && "Unknown commutative expr!");
311 }
312 }
313 return this;
314}
315
Dan Gohman72a8a022009-05-07 14:00:19 +0000316bool SCEVNAryExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
Evan Cheng98c073b2009-02-17 00:13:06 +0000317 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
318 if (!getOperand(i)->dominates(BB, DT))
319 return false;
320 }
321 return true;
322}
323
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000325// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000326// input. Don't use a SCEVHandle here, or else the object will never be
327// deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000328static ManagedStatic<std::map<std::pair<const SCEV*, const SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000329 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000331SCEVUDivExpr::~SCEVUDivExpr() {
332 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333}
334
Evan Cheng98c073b2009-02-17 00:13:06 +0000335bool SCEVUDivExpr::dominates(BasicBlock *BB, DominatorTree *DT) const {
336 return LHS->dominates(BB, DT) && RHS->dominates(BB, DT);
337}
338
Dan Gohman13058cc2009-04-21 00:47:46 +0000339void SCEVUDivExpr::print(raw_ostream &OS) const {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000340 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341}
342
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000343const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 return LHS->getType();
345}
346
347// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
348// particular input. Don't use a SCEVHandle here, or else the object will never
349// be deleted!
Dan Gohmanbff6b582009-05-04 22:30:44 +0000350static ManagedStatic<std::map<std::pair<const Loop *,
351 std::vector<const SCEV*> >,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000352 SCEVAddRecExpr*> > SCEVAddRecExprs;
353
354SCEVAddRecExpr::~SCEVAddRecExpr() {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000355 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
356 SCEVAddRecExprs->erase(std::make_pair(L, SCEVOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357}
358
359SCEVHandle SCEVAddRecExpr::
360replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000361 const SCEVHandle &Conc,
362 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000363 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000364 SCEVHandle H =
365 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000366 if (H != getOperand(i)) {
367 std::vector<SCEVHandle> NewOps;
368 NewOps.reserve(getNumOperands());
369 for (unsigned j = 0; j != i; ++j)
370 NewOps.push_back(getOperand(j));
371 NewOps.push_back(H);
372 for (++i; i != e; ++i)
373 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000374 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375
Dan Gohman89f85052007-10-22 18:31:58 +0000376 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377 }
378 }
379 return this;
380}
381
382
383bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
384 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
385 // contain L and if the start is invariant.
386 return !QueryLoop->contains(L->getHeader()) &&
387 getOperand(0)->isLoopInvariant(QueryLoop);
388}
389
390
Dan Gohman13058cc2009-04-21 00:47:46 +0000391void SCEVAddRecExpr::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 OS << "{" << *Operands[0];
393 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
394 OS << ",+," << *Operands[i];
395 OS << "}<" << L->getHeader()->getName() + ">";
396}
397
398// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
399// value. Don't use a SCEVHandle here, or else the object will never be
400// deleted!
401static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
402
403SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
404
405bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
406 // All non-instruction values are loop invariant. All instructions are loop
407 // invariant if they are not contained in the specified loop.
408 if (Instruction *I = dyn_cast<Instruction>(V))
409 return !L->contains(I->getParent());
410 return true;
411}
412
Evan Cheng98c073b2009-02-17 00:13:06 +0000413bool SCEVUnknown::dominates(BasicBlock *BB, DominatorTree *DT) const {
414 if (Instruction *I = dyn_cast<Instruction>(getValue()))
415 return DT->dominates(I->getParent(), BB);
416 return true;
417}
418
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000419const Type *SCEVUnknown::getType() const {
420 return V->getType();
421}
422
Dan Gohman13058cc2009-04-21 00:47:46 +0000423void SCEVUnknown::print(raw_ostream &OS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 WriteAsOperand(OS, V, false);
425}
426
427//===----------------------------------------------------------------------===//
428// SCEV Utilities
429//===----------------------------------------------------------------------===//
430
431namespace {
432 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
433 /// than the complexity of the RHS. This comparator is used to canonicalize
434 /// expressions.
Dan Gohman5d486452009-05-07 14:39:04 +0000435 class VISIBILITY_HIDDEN SCEVComplexityCompare {
436 LoopInfo *LI;
437 public:
438 explicit SCEVComplexityCompare(LoopInfo *li) : LI(li) {}
439
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000440 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohman5d486452009-05-07 14:39:04 +0000441 // Primarily, sort the SCEVs by their getSCEVType().
442 if (LHS->getSCEVType() != RHS->getSCEVType())
443 return LHS->getSCEVType() < RHS->getSCEVType();
444
445 // Aside from the getSCEVType() ordering, the particular ordering
446 // isn't very important except that it's beneficial to be consistent,
447 // so that (a + b) and (b + a) don't end up as different expressions.
448
449 // Sort SCEVUnknown values with some loose heuristics. TODO: This is
450 // not as complete as it could be.
451 if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS)) {
452 const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
453
454 // Compare getValueID values.
455 if (LU->getValue()->getValueID() != RU->getValue()->getValueID())
456 return LU->getValue()->getValueID() < RU->getValue()->getValueID();
457
458 // Sort arguments by their position.
459 if (const Argument *LA = dyn_cast<Argument>(LU->getValue())) {
460 const Argument *RA = cast<Argument>(RU->getValue());
461 return LA->getArgNo() < RA->getArgNo();
462 }
463
464 // For instructions, compare their loop depth, and their opcode.
465 // This is pretty loose.
466 if (Instruction *LV = dyn_cast<Instruction>(LU->getValue())) {
467 Instruction *RV = cast<Instruction>(RU->getValue());
468
469 // Compare loop depths.
470 if (LI->getLoopDepth(LV->getParent()) !=
471 LI->getLoopDepth(RV->getParent()))
472 return LI->getLoopDepth(LV->getParent()) <
473 LI->getLoopDepth(RV->getParent());
474
475 // Compare opcodes.
476 if (LV->getOpcode() != RV->getOpcode())
477 return LV->getOpcode() < RV->getOpcode();
478
479 // Compare the number of operands.
480 if (LV->getNumOperands() != RV->getNumOperands())
481 return LV->getNumOperands() < RV->getNumOperands();
482 }
483
484 return false;
485 }
486
487 // Constant sorting doesn't matter since they'll be folded.
488 if (isa<SCEVConstant>(LHS))
489 return false;
490
491 // Lexicographically compare n-ary expressions.
492 if (const SCEVNAryExpr *LC = dyn_cast<SCEVNAryExpr>(LHS)) {
493 const SCEVNAryExpr *RC = cast<SCEVNAryExpr>(RHS);
494 for (unsigned i = 0, e = LC->getNumOperands(); i != e; ++i) {
495 if (i >= RC->getNumOperands())
496 return false;
497 if (operator()(LC->getOperand(i), RC->getOperand(i)))
498 return true;
499 if (operator()(RC->getOperand(i), LC->getOperand(i)))
500 return false;
501 }
502 return LC->getNumOperands() < RC->getNumOperands();
503 }
504
505 // Compare cast expressions by operand.
506 if (const SCEVCastExpr *LC = dyn_cast<SCEVCastExpr>(LHS)) {
507 const SCEVCastExpr *RC = cast<SCEVCastExpr>(RHS);
508 return operator()(LC->getOperand(), RC->getOperand());
509 }
510
511 assert(0 && "Unknown SCEV kind!");
512 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 }
514 };
515}
516
517/// GroupByComplexity - Given a list of SCEV objects, order them by their
518/// complexity, and group objects of the same complexity together by value.
519/// When this routine is finished, we know that any duplicates in the vector are
520/// consecutive and that complexity is monotonically increasing.
521///
522/// Note that we go take special precautions to ensure that we get determinstic
523/// results from this routine. In other words, we don't want the results of
524/// this to depend on where the addresses of various SCEV objects happened to
525/// land in memory.
526///
Dan Gohman5d486452009-05-07 14:39:04 +0000527static void GroupByComplexity(std::vector<SCEVHandle> &Ops,
528 LoopInfo *LI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000529 if (Ops.size() < 2) return; // Noop
530 if (Ops.size() == 2) {
531 // This is the common case, which also happens to be trivially simple.
532 // Special case it.
Dan Gohman5d486452009-05-07 14:39:04 +0000533 if (SCEVComplexityCompare(LI)(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000534 std::swap(Ops[0], Ops[1]);
535 return;
536 }
537
538 // Do the rough sort by complexity.
Dan Gohman5d486452009-05-07 14:39:04 +0000539 std::stable_sort(Ops.begin(), Ops.end(), SCEVComplexityCompare(LI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000540
541 // Now that we are sorted by complexity, group elements of the same
542 // complexity. Note that this is, at worst, N^2, but the vector is likely to
543 // be extremely short in practice. Note that we take this approach because we
544 // do not want to depend on the addresses of the objects we are grouping.
545 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000546 const SCEV *S = Ops[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 unsigned Complexity = S->getSCEVType();
548
549 // If there are any objects of the same complexity and same value as this
550 // one, group them.
551 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
552 if (Ops[j] == S) { // Found a duplicate.
553 // Move it to immediately after i'th element.
554 std::swap(Ops[i+1], Ops[j]);
555 ++i; // no need to rescan it.
556 if (i == e-2) return; // Done!
557 }
558 }
559 }
560}
561
562
563
564//===----------------------------------------------------------------------===//
565// Simple SCEV method implementations
566//===----------------------------------------------------------------------===//
567
Eli Friedman7489ec92008-08-04 23:49:06 +0000568/// BinomialCoefficient - Compute BC(It, K). The result has width W.
569// Assume, K > 0.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000570static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
Eli Friedman7489ec92008-08-04 23:49:06 +0000571 ScalarEvolution &SE,
Dan Gohman01c2ee72009-04-16 03:18:22 +0000572 const Type* ResultTy) {
Eli Friedman7489ec92008-08-04 23:49:06 +0000573 // Handle the simplest case efficiently.
574 if (K == 1)
575 return SE.getTruncateOrZeroExtend(It, ResultTy);
576
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000577 // We are using the following formula for BC(It, K):
578 //
579 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
580 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000581 // Suppose, W is the bitwidth of the return value. We must be prepared for
582 // overflow. Hence, we must assure that the result of our computation is
583 // equal to the accurate one modulo 2^W. Unfortunately, division isn't
584 // safe in modular arithmetic.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000585 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000586 // However, this code doesn't use exactly that formula; the formula it uses
587 // is something like the following, where T is the number of factors of 2 in
588 // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
589 // exponentiation:
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000590 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000591 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000592 //
Eli Friedman7489ec92008-08-04 23:49:06 +0000593 // This formula is trivially equivalent to the previous formula. However,
594 // this formula can be implemented much more efficiently. The trick is that
595 // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
596 // arithmetic. To do exact division in modular arithmetic, all we have
597 // to do is multiply by the inverse. Therefore, this step can be done at
598 // width W.
599 //
600 // The next issue is how to safely do the division by 2^T. The way this
601 // is done is by doing the multiplication step at a width of at least W + T
602 // bits. This way, the bottom W+T bits of the product are accurate. Then,
603 // when we perform the division by 2^T (which is equivalent to a right shift
604 // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
605 // truncated out after the division by 2^T.
606 //
607 // In comparison to just directly using the first formula, this technique
608 // is much more efficient; using the first formula requires W * K bits,
609 // but this formula less than W + K bits. Also, the first formula requires
610 // a division step, whereas this formula only requires multiplies and shifts.
611 //
612 // It doesn't matter whether the subtraction step is done in the calculation
613 // width or the input iteration count's width; if the subtraction overflows,
614 // the result must be zero anyway. We prefer here to do it in the width of
615 // the induction variable because it helps a lot for certain cases; CodeGen
616 // isn't smart enough to ignore the overflow, which leads to much less
617 // efficient code if the width of the subtraction is wider than the native
618 // register width.
619 //
620 // (It's possible to not widen at all by pulling out factors of 2 before
621 // the multiplication; for example, K=2 can be calculated as
622 // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
623 // extra arithmetic, so it's not an obvious win, and it gets
624 // much more complicated for K > 3.)
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000625
Eli Friedman7489ec92008-08-04 23:49:06 +0000626 // Protection from insane SCEVs; this bound is conservative,
627 // but it probably doesn't matter.
628 if (K > 1000)
Dan Gohman0ad08b02009-04-18 17:58:19 +0000629 return SE.getCouldNotCompute();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000630
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000631 unsigned W = SE.getTypeSizeInBits(ResultTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000632
Eli Friedman7489ec92008-08-04 23:49:06 +0000633 // Calculate K! / 2^T and T; we divide out the factors of two before
634 // multiplying for calculating K! / 2^T to avoid overflow.
635 // Other overflow doesn't matter because we only care about the bottom
636 // W bits of the result.
637 APInt OddFactorial(W, 1);
638 unsigned T = 1;
639 for (unsigned i = 3; i <= K; ++i) {
640 APInt Mult(W, i);
641 unsigned TwoFactors = Mult.countTrailingZeros();
642 T += TwoFactors;
643 Mult = Mult.lshr(TwoFactors);
644 OddFactorial *= Mult;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000645 }
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000646
Eli Friedman7489ec92008-08-04 23:49:06 +0000647 // We need at least W + T bits for the multiplication step
nicholas9e3e5fd2009-01-25 08:16:27 +0000648 unsigned CalculationBits = W + T;
Eli Friedman7489ec92008-08-04 23:49:06 +0000649
650 // Calcuate 2^T, at width T+W.
651 APInt DivFactor = APInt(CalculationBits, 1).shl(T);
652
653 // Calculate the multiplicative inverse of K! / 2^T;
654 // this multiplication factor will perform the exact division by
655 // K! / 2^T.
656 APInt Mod = APInt::getSignedMinValue(W+1);
657 APInt MultiplyFactor = OddFactorial.zext(W+1);
658 MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
659 MultiplyFactor = MultiplyFactor.trunc(W);
660
661 // Calculate the product, at width T+W
662 const IntegerType *CalculationTy = IntegerType::get(CalculationBits);
663 SCEVHandle Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
664 for (unsigned i = 1; i != K; ++i) {
665 SCEVHandle S = SE.getMinusSCEV(It, SE.getIntegerSCEV(i, It->getType()));
666 Dividend = SE.getMulExpr(Dividend,
667 SE.getTruncateOrZeroExtend(S, CalculationTy));
668 }
669
670 // Divide by 2^T
671 SCEVHandle DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
672
673 // Truncate the result, and divide by K! / 2^T.
674
675 return SE.getMulExpr(SE.getConstant(MultiplyFactor),
676 SE.getTruncateOrZeroExtend(DivResult, ResultTy));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000677}
678
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000679/// evaluateAtIteration - Return the value of this chain of recurrences at
680/// the specified iteration number. We can evaluate this recurrence by
681/// multiplying each element in the chain by the binomial coefficient
682/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
683///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000684/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000686/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687///
Dan Gohman89f85052007-10-22 18:31:58 +0000688SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
689 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000690 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000691 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000692 // The computation is correct in the face of overflow provided that the
693 // multiplication is performed _after_ the evaluation of the binomial
694 // coefficient.
Dan Gohman01c2ee72009-04-16 03:18:22 +0000695 SCEVHandle Coeff = BinomialCoefficient(It, i, SE, getType());
Nick Lewyckyb6218e02008-10-13 03:58:02 +0000696 if (isa<SCEVCouldNotCompute>(Coeff))
697 return Coeff;
698
699 Result = SE.getAddExpr(Result, SE.getMulExpr(getOperand(i), Coeff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000700 }
701 return Result;
702}
703
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704//===----------------------------------------------------------------------===//
705// SCEV Expression folder implementations
706//===----------------------------------------------------------------------===//
707
Dan Gohman9c8abcc2009-05-01 16:44:56 +0000708SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op,
709 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000710 assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000711 "This is not a truncating conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000712 assert(isSCEVable(Ty) &&
713 "This is not a conversion to a SCEVable type!");
714 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000715
Dan Gohmanc76b5452009-05-04 22:02:23 +0000716 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000717 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000718 ConstantExpr::getTrunc(SC->getValue(), Ty));
719
Dan Gohman1a5c4992009-04-22 16:20:48 +0000720 // trunc(trunc(x)) --> trunc(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000721 if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000722 return getTruncateExpr(ST->getOperand(), Ty);
723
Nick Lewycky37d04642009-04-23 05:15:08 +0000724 // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000725 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000726 return getTruncateOrSignExtend(SS->getOperand(), Ty);
727
728 // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
Dan Gohmanc76b5452009-05-04 22:02:23 +0000729 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Nick Lewycky37d04642009-04-23 05:15:08 +0000730 return getTruncateOrZeroExtend(SZ->getOperand(), Ty);
731
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000732 // If the input value is a chrec scev made out of constants, truncate
733 // all of the constants.
Dan Gohmanc76b5452009-05-04 22:02:23 +0000734 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 std::vector<SCEVHandle> Operands;
736 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
737 // FIXME: This should allow truncation of other expression types!
738 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000739 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 else
741 break;
742 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000743 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000744 }
745
746 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
747 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
748 return Result;
749}
750
Dan Gohman36d40922009-04-16 19:25:55 +0000751SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op,
752 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000753 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohman36d40922009-04-16 19:25:55 +0000754 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000755 assert(isSCEVable(Ty) &&
756 "This is not a conversion to a SCEVable type!");
757 Ty = getEffectiveSCEVType(Ty);
Dan Gohman36d40922009-04-16 19:25:55 +0000758
Dan Gohmanc76b5452009-05-04 22:02:23 +0000759 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000760 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000761 Constant *C = ConstantExpr::getZExt(SC->getValue(), IntTy);
762 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
763 return getUnknown(C);
764 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000765
Dan Gohman1a5c4992009-04-22 16:20:48 +0000766 // zext(zext(x)) --> zext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000767 if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000768 return getZeroExtendExpr(SZ->getOperand(), Ty);
769
Dan Gohmana9dba962009-04-27 20:16:15 +0000770 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000771 // did not overflow the old, smaller, value, we can zero extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000772 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000774 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000775 if (AR->isAffine()) {
776 // Check whether the backedge-taken count is SCEVCouldNotCompute.
777 // Note that this serves two purposes: It filters out loops that are
778 // simply not analyzable, and it covers the case where this code is
779 // being called from within backedge-taken count analysis, such that
780 // attempting to ask for the backedge-taken count would likely result
781 // in infinite recursion. In the later case, the analysis code will
782 // cope with a conservative value, and it will take care to purge
783 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000784 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
785 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000786 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000787 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000788 SCEVHandle Start = AR->getStart();
789 SCEVHandle Step = AR->getStepRecurrence(*this);
790
791 // Check whether the backedge-taken count can be losslessly casted to
792 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000793 SCEVHandle CastedMaxBECount =
794 getTruncateOrZeroExtend(MaxBECount, Start->getType());
795 if (MaxBECount ==
796 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
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.
Dan Gohmana9dba962009-04-27 20:16:15 +0000800 SCEVHandle ZMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000801 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000802 getTruncateOrZeroExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000803 SCEVHandle Add = getAddExpr(Start, ZMul);
804 if (getZeroExtendExpr(Add, WideTy) ==
805 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000806 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000807 getZeroExtendExpr(Step, WideTy))))
808 // Return the expression with the addrec on the outside.
809 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
810 getZeroExtendExpr(Step, Ty),
811 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000812
813 // Similar to above, only this time treat the step value as signed.
814 // This covers loops that count down.
815 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000816 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000817 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000818 Add = getAddExpr(Start, SMul);
819 if (getZeroExtendExpr(Add, WideTy) ==
820 getAddExpr(getZeroExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000821 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000822 getSignExtendExpr(Step, WideTy))))
823 // Return the expression with the addrec on the outside.
824 return getAddRecExpr(getZeroExtendExpr(Start, Ty),
825 getSignExtendExpr(Step, Ty),
826 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000827 }
828 }
829 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830
831 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
832 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
833 return Result;
834}
835
Dan Gohmana9dba962009-04-27 20:16:15 +0000836SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op,
837 const Type *Ty) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000838 assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000839 "This is not an extending conversion!");
Dan Gohman13a51e22009-05-01 16:44:18 +0000840 assert(isSCEVable(Ty) &&
841 "This is not a conversion to a SCEVable type!");
842 Ty = getEffectiveSCEVType(Ty);
Dan Gohmanf62cfe52009-04-21 00:55:22 +0000843
Dan Gohmanc76b5452009-05-04 22:02:23 +0000844 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +0000845 const Type *IntTy = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +0000846 Constant *C = ConstantExpr::getSExt(SC->getValue(), IntTy);
847 if (IntTy != Ty) C = ConstantExpr::getIntToPtr(C, Ty);
848 return getUnknown(C);
849 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000850
Dan Gohman1a5c4992009-04-22 16:20:48 +0000851 // sext(sext(x)) --> sext(x)
Dan Gohmanc76b5452009-05-04 22:02:23 +0000852 if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
Dan Gohman1a5c4992009-04-22 16:20:48 +0000853 return getSignExtendExpr(SS->getOperand(), Ty);
854
Dan Gohmana9dba962009-04-27 20:16:15 +0000855 // If the input value is a chrec scev, and we can prove that the value
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 // did not overflow the old, smaller, value, we can sign extend all of the
Dan Gohmana9dba962009-04-27 20:16:15 +0000857 // operands (often constants). This allows analysis of something like
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
Dan Gohmanc76b5452009-05-04 22:02:23 +0000859 if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
Dan Gohmana9dba962009-04-27 20:16:15 +0000860 if (AR->isAffine()) {
861 // Check whether the backedge-taken count is SCEVCouldNotCompute.
862 // Note that this serves two purposes: It filters out loops that are
863 // simply not analyzable, and it covers the case where this code is
864 // being called from within backedge-taken count analysis, such that
865 // attempting to ask for the backedge-taken count would likely result
866 // in infinite recursion. In the later case, the analysis code will
867 // cope with a conservative value, and it will take care to purge
868 // that value once it has finished.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000869 SCEVHandle MaxBECount = getMaxBackedgeTakenCount(AR->getLoop());
870 if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
Dan Gohman4ada77f2009-04-29 01:54:20 +0000871 // Manually compute the final value for AR, checking for
Dan Gohman3ded5b22009-04-29 22:28:28 +0000872 // overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000873 SCEVHandle Start = AR->getStart();
874 SCEVHandle Step = AR->getStepRecurrence(*this);
875
876 // Check whether the backedge-taken count can be losslessly casted to
Dan Gohman3ded5b22009-04-29 22:28:28 +0000877 // the addrec's type. The count is always unsigned.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000878 SCEVHandle CastedMaxBECount =
879 getTruncateOrZeroExtend(MaxBECount, Start->getType());
880 if (MaxBECount ==
881 getTruncateOrZeroExtend(CastedMaxBECount, MaxBECount->getType())) {
Dan Gohmana9dba962009-04-27 20:16:15 +0000882 const Type *WideTy =
883 IntegerType::get(getTypeSizeInBits(Start->getType()) * 2);
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000884 // Check whether Start+Step*MaxBECount has no signed overflow.
Dan Gohmana9dba962009-04-27 20:16:15 +0000885 SCEVHandle SMul =
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000886 getMulExpr(CastedMaxBECount,
Dan Gohmana9dba962009-04-27 20:16:15 +0000887 getTruncateOrSignExtend(Step, Start->getType()));
Dan Gohman3ded5b22009-04-29 22:28:28 +0000888 SCEVHandle Add = getAddExpr(Start, SMul);
889 if (getSignExtendExpr(Add, WideTy) ==
890 getAddExpr(getSignExtendExpr(Start, WideTy),
Dan Gohmanf7d3d25542009-04-30 20:47:05 +0000891 getMulExpr(getZeroExtendExpr(CastedMaxBECount, WideTy),
Dan Gohman3ded5b22009-04-29 22:28:28 +0000892 getSignExtendExpr(Step, WideTy))))
893 // Return the expression with the addrec on the outside.
894 return getAddRecExpr(getSignExtendExpr(Start, Ty),
895 getSignExtendExpr(Step, Ty),
896 AR->getLoop());
Dan Gohmana9dba962009-04-27 20:16:15 +0000897 }
898 }
899 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000900
901 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
902 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
903 return Result;
904}
905
906// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000907SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000908 assert(!Ops.empty() && "Cannot get empty add!");
909 if (Ops.size() == 1) return Ops[0];
910
911 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +0000912 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913
914 // If there are any constants, fold them together.
915 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000916 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000917 ++Idx;
918 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +0000919 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000920 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000921 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
922 RHSC->getValue()->getValue());
923 Ops[0] = getConstant(Fold);
924 Ops.erase(Ops.begin()+1); // Erase the folded element
925 if (Ops.size() == 1) return Ops[0];
926 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 }
928
929 // If we are left with a constant zero being added, strip it off.
930 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
931 Ops.erase(Ops.begin());
932 --Idx;
933 }
934 }
935
936 if (Ops.size() == 1) return Ops[0];
937
938 // Okay, check to see if the same value occurs in the operand list twice. If
939 // so, merge them together into an multiply expression. Since we sorted the
940 // list, these values are required to be adjacent.
941 const Type *Ty = Ops[0]->getType();
942 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
943 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
944 // Found a match, merge the two values into a multiply, and add any
945 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000946 SCEVHandle Two = getIntegerSCEV(2, Ty);
947 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 if (Ops.size() == 2)
949 return Mul;
950 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
951 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000952 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 }
954
955 // Now we know the first non-constant operand. Skip past any cast SCEVs.
956 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
957 ++Idx;
958
959 // If there are add operands they would be next.
960 if (Idx < Ops.size()) {
961 bool DeletedAdd = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +0000962 while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 // If we have an add, expand the add operands onto the end of the operands
964 // list.
965 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
966 Ops.erase(Ops.begin()+Idx);
967 DeletedAdd = true;
968 }
969
970 // If we deleted at least one add, we added operands to the end of the list,
971 // and they are not necessarily sorted. Recurse to resort and resimplify
972 // any operands we just aquired.
973 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000974 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 }
976
977 // Skip over the add expression until we get to a multiply.
978 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
979 ++Idx;
980
981 // If we are adding something to a multiply expression, make sure the
982 // something is not already an operand of the multiply. If so, merge it into
983 // the multiply.
984 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000985 const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
Dan Gohmanbff6b582009-05-04 22:30:44 +0000987 const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
989 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
990 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
991 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
992 if (Mul->getNumOperands() != 2) {
993 // If the multiply has more than two operands, we must get the
994 // Y*Z term.
995 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
996 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000997 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000998 }
Dan Gohman89f85052007-10-22 18:31:58 +0000999 SCEVHandle One = getIntegerSCEV(1, Ty);
1000 SCEVHandle AddOne = getAddExpr(InnerMul, One);
1001 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 if (Ops.size() == 2) return OuterMul;
1003 if (AddOp < Idx) {
1004 Ops.erase(Ops.begin()+AddOp);
1005 Ops.erase(Ops.begin()+Idx-1);
1006 } else {
1007 Ops.erase(Ops.begin()+Idx);
1008 Ops.erase(Ops.begin()+AddOp-1);
1009 }
1010 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001011 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001012 }
1013
1014 // Check this multiply against other multiplies being added together.
1015 for (unsigned OtherMulIdx = Idx+1;
1016 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
1017 ++OtherMulIdx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001018 const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001019 // If MulOp occurs in OtherMul, we can fold the two multiplies
1020 // together.
1021 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
1022 OMulOp != e; ++OMulOp)
1023 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
1024 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
1025 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
1026 if (Mul->getNumOperands() != 2) {
1027 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
1028 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001029 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001030 }
1031 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
1032 if (OtherMul->getNumOperands() != 2) {
1033 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
1034 OtherMul->op_end());
1035 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +00001036 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 }
Dan Gohman89f85052007-10-22 18:31:58 +00001038 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
1039 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001040 if (Ops.size() == 2) return OuterMul;
1041 Ops.erase(Ops.begin()+Idx);
1042 Ops.erase(Ops.begin()+OtherMulIdx-1);
1043 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +00001044 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001045 }
1046 }
1047 }
1048 }
1049
1050 // If there are any add recurrences in the operands list, see if any other
1051 // added values are loop invariant. If so, we can fold them into the
1052 // recurrence.
1053 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1054 ++Idx;
1055
1056 // Scan over all recurrences, trying to fold loop invariants into them.
1057 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1058 // Scan all of the other operands to this add and add them to the vector if
1059 // they are loop invariant w.r.t. the recurrence.
1060 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001061 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001062 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1063 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1064 LIOps.push_back(Ops[i]);
1065 Ops.erase(Ops.begin()+i);
1066 --i; --e;
1067 }
1068
1069 // If we found some loop invariants, fold them into the recurrence.
1070 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001071 // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072 LIOps.push_back(AddRec->getStart());
1073
1074 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001075 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076
Dan Gohman89f85052007-10-22 18:31:58 +00001077 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 // If all of the other operands were loop invariant, we are done.
1079 if (Ops.size() == 1) return NewRec;
1080
1081 // Otherwise, add the folded AddRec by the non-liv parts.
1082 for (unsigned i = 0;; ++i)
1083 if (Ops[i] == AddRec) {
1084 Ops[i] = NewRec;
1085 break;
1086 }
Dan Gohman89f85052007-10-22 18:31:58 +00001087 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001088 }
1089
1090 // Okay, if there weren't any loop invariants to be folded, check to see if
1091 // there are multiple AddRec's with the same loop induction variable being
1092 // added together. If so, we can fold them.
1093 for (unsigned OtherIdx = Idx+1;
1094 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1095 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001096 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1098 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
1099 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
1100 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
1101 if (i >= NewOps.size()) {
1102 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
1103 OtherAddRec->op_end());
1104 break;
1105 }
Dan Gohman89f85052007-10-22 18:31:58 +00001106 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107 }
Dan Gohman89f85052007-10-22 18:31:58 +00001108 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001109
1110 if (Ops.size() == 2) return NewAddRec;
1111
1112 Ops.erase(Ops.begin()+Idx);
1113 Ops.erase(Ops.begin()+OtherIdx-1);
1114 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001115 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 }
1117 }
1118
1119 // Otherwise couldn't fold anything into this recurrence. Move onto the
1120 // next one.
1121 }
1122
1123 // Okay, it looks like we really DO need an add expr. Check to see if we
1124 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001125 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001126 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
1127 SCEVOps)];
1128 if (Result == 0) Result = new SCEVAddExpr(Ops);
1129 return Result;
1130}
1131
1132
Dan Gohman89f85052007-10-22 18:31:58 +00001133SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001134 assert(!Ops.empty() && "Cannot get empty mul!");
1135
1136 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001137 GroupByComplexity(Ops, LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138
1139 // If there are any constants, fold them together.
1140 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001141 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001142
1143 // C1*(C2+V) -> C1*C2 + C1*V
1144 if (Ops.size() == 2)
Dan Gohmanc76b5452009-05-04 22:02:23 +00001145 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 if (Add->getNumOperands() == 2 &&
1147 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +00001148 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
1149 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001150
1151
1152 ++Idx;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001153 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001155 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
1156 RHSC->getValue()->getValue());
1157 Ops[0] = getConstant(Fold);
1158 Ops.erase(Ops.begin()+1); // Erase the folded element
1159 if (Ops.size() == 1) return Ops[0];
1160 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001161 }
1162
1163 // If we are left with a constant one being multiplied, strip it off.
1164 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
1165 Ops.erase(Ops.begin());
1166 --Idx;
1167 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
1168 // If we have a multiply of zero, it will always be zero.
1169 return Ops[0];
1170 }
1171 }
1172
1173 // Skip over the add expression until we get to a multiply.
1174 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
1175 ++Idx;
1176
1177 if (Ops.size() == 1)
1178 return Ops[0];
1179
1180 // If there are mul operands inline them all into this expression.
1181 if (Idx < Ops.size()) {
1182 bool DeletedMul = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001183 while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001184 // If we have an mul, expand the mul operands onto the end of the operands
1185 // list.
1186 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
1187 Ops.erase(Ops.begin()+Idx);
1188 DeletedMul = true;
1189 }
1190
1191 // If we deleted at least one mul, we added operands to the end of the list,
1192 // and they are not necessarily sorted. Recurse to resort and resimplify
1193 // any operands we just aquired.
1194 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001195 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001196 }
1197
1198 // If there are any add recurrences in the operands list, see if any other
1199 // added values are loop invariant. If so, we can fold them into the
1200 // recurrence.
1201 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1202 ++Idx;
1203
1204 // Scan over all recurrences, trying to fold loop invariants into them.
1205 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1206 // Scan all of the other operands to this mul and add them to the vector if
1207 // they are loop invariant w.r.t. the recurrence.
1208 std::vector<SCEVHandle> LIOps;
Dan Gohmanbff6b582009-05-04 22:30:44 +00001209 const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001210 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1211 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1212 LIOps.push_back(Ops[i]);
1213 Ops.erase(Ops.begin()+i);
1214 --i; --e;
1215 }
1216
1217 // If we found some loop invariants, fold them into the recurrence.
1218 if (!LIOps.empty()) {
Dan Gohmanabe991f2008-09-14 17:21:12 +00001219 // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001220 std::vector<SCEVHandle> NewOps;
1221 NewOps.reserve(AddRec->getNumOperands());
1222 if (LIOps.size() == 1) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001223 const SCEV *Scale = LIOps[0];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001224 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001225 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001226 } else {
1227 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1228 std::vector<SCEVHandle> MulOps(LIOps);
1229 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001230 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001231 }
1232 }
1233
Dan Gohman89f85052007-10-22 18:31:58 +00001234 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001235
1236 // If all of the other operands were loop invariant, we are done.
1237 if (Ops.size() == 1) return NewRec;
1238
1239 // Otherwise, multiply the folded AddRec by the non-liv parts.
1240 for (unsigned i = 0;; ++i)
1241 if (Ops[i] == AddRec) {
1242 Ops[i] = NewRec;
1243 break;
1244 }
Dan Gohman89f85052007-10-22 18:31:58 +00001245 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001246 }
1247
1248 // Okay, if there weren't any loop invariants to be folded, check to see if
1249 // there are multiple AddRec's with the same loop induction variable being
1250 // multiplied together. If so, we can fold them.
1251 for (unsigned OtherIdx = Idx+1;
1252 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1253 if (OtherIdx != Idx) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001254 const SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001255 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1256 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
Dan Gohmanbff6b582009-05-04 22:30:44 +00001257 const SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001258 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001259 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001260 SCEVHandle B = F->getStepRecurrence(*this);
1261 SCEVHandle D = G->getStepRecurrence(*this);
1262 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1263 getMulExpr(G, B),
1264 getMulExpr(B, D));
1265 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1266 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001267 if (Ops.size() == 2) return NewAddRec;
1268
1269 Ops.erase(Ops.begin()+Idx);
1270 Ops.erase(Ops.begin()+OtherIdx-1);
1271 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001272 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001273 }
1274 }
1275
1276 // Otherwise couldn't fold anything into this recurrence. Move onto the
1277 // next one.
1278 }
1279
1280 // Okay, it looks like we really DO need an mul expr. Check to see if we
1281 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001282 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001283 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1284 SCEVOps)];
1285 if (Result == 0)
1286 Result = new SCEVMulExpr(Ops);
1287 return Result;
1288}
1289
Dan Gohman77841cd2009-05-04 22:23:18 +00001290SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS,
1291 const SCEVHandle &RHS) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001292 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 if (RHSC->getValue()->equalsInt(1))
Nick Lewycky35b56022009-01-13 09:18:58 +00001294 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295
Dan Gohmanc76b5452009-05-04 22:02:23 +00001296 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001297 Constant *LHSCV = LHSC->getValue();
1298 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001299 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001300 }
1301 }
1302
Nick Lewycky35b56022009-01-13 09:18:58 +00001303 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1304
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001305 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1306 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 return Result;
1308}
1309
1310
1311/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1312/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001313SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 const SCEVHandle &Step, const Loop *L) {
1315 std::vector<SCEVHandle> Operands;
1316 Operands.push_back(Start);
Dan Gohmanc76b5452009-05-04 22:02:23 +00001317 if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001318 if (StepChrec->getLoop() == L) {
1319 Operands.insert(Operands.end(), StepChrec->op_begin(),
1320 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001321 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001322 }
1323
1324 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001325 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001326}
1327
1328/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1329/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001330SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Nick Lewycky37d04642009-04-23 05:15:08 +00001331 const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001332 if (Operands.size() == 1) return Operands[0];
1333
Dan Gohman7b560c42008-06-18 16:23:07 +00001334 if (Operands.back()->isZero()) {
1335 Operands.pop_back();
Dan Gohmanabe991f2008-09-14 17:21:12 +00001336 return getAddRecExpr(Operands, L); // {X,+,0} --> X
Dan Gohman7b560c42008-06-18 16:23:07 +00001337 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001338
Dan Gohman42936882008-08-08 18:33:12 +00001339 // Canonicalize nested AddRecs in by nesting them in order of loop depth.
Dan Gohmanc76b5452009-05-04 22:02:23 +00001340 if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
Dan Gohman42936882008-08-08 18:33:12 +00001341 const Loop* NestedLoop = NestedAR->getLoop();
1342 if (L->getLoopDepth() < NestedLoop->getLoopDepth()) {
1343 std::vector<SCEVHandle> NestedOperands(NestedAR->op_begin(),
1344 NestedAR->op_end());
1345 SCEVHandle NestedARHandle(NestedAR);
1346 Operands[0] = NestedAR->getStart();
1347 NestedOperands[0] = getAddRecExpr(Operands, L);
1348 return getAddRecExpr(NestedOperands, NestedLoop);
1349 }
1350 }
1351
Dan Gohmanbff6b582009-05-04 22:30:44 +00001352 std::vector<const SCEV*> SCEVOps(Operands.begin(), Operands.end());
1353 SCEVAddRecExpr *&Result = (*SCEVAddRecExprs)[std::make_pair(L, SCEVOps)];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001354 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1355 return Result;
1356}
1357
Nick Lewycky711640a2007-11-25 22:41:31 +00001358SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1359 const SCEVHandle &RHS) {
1360 std::vector<SCEVHandle> Ops;
1361 Ops.push_back(LHS);
1362 Ops.push_back(RHS);
1363 return getSMaxExpr(Ops);
1364}
1365
1366SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1367 assert(!Ops.empty() && "Cannot get empty smax!");
1368 if (Ops.size() == 1) return Ops[0];
1369
1370 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001371 GroupByComplexity(Ops, LI);
Nick Lewycky711640a2007-11-25 22:41:31 +00001372
1373 // If there are any constants, fold them together.
1374 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001375 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001376 ++Idx;
1377 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001378 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001379 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001380 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001381 APIntOps::smax(LHSC->getValue()->getValue(),
1382 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001383 Ops[0] = getConstant(Fold);
1384 Ops.erase(Ops.begin()+1); // Erase the folded element
1385 if (Ops.size() == 1) return Ops[0];
1386 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001387 }
1388
1389 // If we are left with a constant -inf, strip it off.
1390 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1391 Ops.erase(Ops.begin());
1392 --Idx;
1393 }
1394 }
1395
1396 if (Ops.size() == 1) return Ops[0];
1397
1398 // Find the first SMax
1399 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1400 ++Idx;
1401
1402 // Check to see if one of the operands is an SMax. If so, expand its operands
1403 // onto our operand list, and recurse to simplify.
1404 if (Idx < Ops.size()) {
1405 bool DeletedSMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001406 while (const SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001407 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1408 Ops.erase(Ops.begin()+Idx);
1409 DeletedSMax = true;
1410 }
1411
1412 if (DeletedSMax)
1413 return getSMaxExpr(Ops);
1414 }
1415
1416 // Okay, check to see if the same value occurs in the operand list twice. If
1417 // so, delete one. Since we sorted the list, these values are required to
1418 // be adjacent.
1419 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1420 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1421 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1422 --i; --e;
1423 }
1424
1425 if (Ops.size() == 1) return Ops[0];
1426
1427 assert(!Ops.empty() && "Reduced smax down to nothing!");
1428
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001429 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001430 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001431 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewycky711640a2007-11-25 22:41:31 +00001432 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1433 SCEVOps)];
1434 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1435 return Result;
1436}
1437
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001438SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1439 const SCEVHandle &RHS) {
1440 std::vector<SCEVHandle> Ops;
1441 Ops.push_back(LHS);
1442 Ops.push_back(RHS);
1443 return getUMaxExpr(Ops);
1444}
1445
1446SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1447 assert(!Ops.empty() && "Cannot get empty umax!");
1448 if (Ops.size() == 1) return Ops[0];
1449
1450 // Sort by complexity, this groups all similar expression types together.
Dan Gohman5d486452009-05-07 14:39:04 +00001451 GroupByComplexity(Ops, LI);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001452
1453 // If there are any constants, fold them together.
1454 unsigned Idx = 0;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001455 if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001456 ++Idx;
1457 assert(Idx < Ops.size());
Dan Gohmanc76b5452009-05-04 22:02:23 +00001458 while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001459 // We found two constants, fold them together!
1460 ConstantInt *Fold = ConstantInt::get(
1461 APIntOps::umax(LHSC->getValue()->getValue(),
1462 RHSC->getValue()->getValue()));
1463 Ops[0] = getConstant(Fold);
1464 Ops.erase(Ops.begin()+1); // Erase the folded element
1465 if (Ops.size() == 1) return Ops[0];
1466 LHSC = cast<SCEVConstant>(Ops[0]);
1467 }
1468
1469 // If we are left with a constant zero, strip it off.
1470 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1471 Ops.erase(Ops.begin());
1472 --Idx;
1473 }
1474 }
1475
1476 if (Ops.size() == 1) return Ops[0];
1477
1478 // Find the first UMax
1479 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1480 ++Idx;
1481
1482 // Check to see if one of the operands is a UMax. If so, expand its operands
1483 // onto our operand list, and recurse to simplify.
1484 if (Idx < Ops.size()) {
1485 bool DeletedUMax = false;
Dan Gohmanc76b5452009-05-04 22:02:23 +00001486 while (const SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001487 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1488 Ops.erase(Ops.begin()+Idx);
1489 DeletedUMax = true;
1490 }
1491
1492 if (DeletedUMax)
1493 return getUMaxExpr(Ops);
1494 }
1495
1496 // Okay, check to see if the same value occurs in the operand list twice. If
1497 // so, delete one. Since we sorted the list, these values are required to
1498 // be adjacent.
1499 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1500 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1501 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1502 --i; --e;
1503 }
1504
1505 if (Ops.size() == 1) return Ops[0];
1506
1507 assert(!Ops.empty() && "Reduced umax down to nothing!");
1508
1509 // Okay, it looks like we really DO need a umax expr. Check to see if we
1510 // already have one, otherwise create a new one.
Dan Gohmanbff6b582009-05-04 22:30:44 +00001511 std::vector<const SCEV*> SCEVOps(Ops.begin(), Ops.end());
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001512 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1513 SCEVOps)];
1514 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1515 return Result;
1516}
1517
Dan Gohman89f85052007-10-22 18:31:58 +00001518SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001519 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001520 return getConstant(CI);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001521 if (isa<ConstantPointerNull>(V))
1522 return getIntegerSCEV(0, V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001523 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1524 if (Result == 0) Result = new SCEVUnknown(V);
1525 return Result;
1526}
1527
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001529// Basic SCEV Analysis and PHI Idiom Recognition Code
1530//
1531
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001532/// isSCEVable - Test if values of the given type are analyzable within
1533/// the SCEV framework. This primarily includes integer types, and it
1534/// can optionally include pointer types if the ScalarEvolution class
1535/// has access to target-specific information.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001536bool ScalarEvolution::isSCEVable(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001537 // Integers are always SCEVable.
1538 if (Ty->isInteger())
1539 return true;
1540
1541 // Pointers are SCEVable if TargetData information is available
1542 // to provide pointer size information.
1543 if (isa<PointerType>(Ty))
1544 return TD != NULL;
1545
1546 // Otherwise it's not SCEVable.
1547 return false;
1548}
1549
1550/// getTypeSizeInBits - Return the size in bits of the specified type,
1551/// for which isSCEVable must return true.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001552uint64_t ScalarEvolution::getTypeSizeInBits(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001553 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1554
1555 // If we have a TargetData, use it!
1556 if (TD)
1557 return TD->getTypeSizeInBits(Ty);
1558
1559 // Otherwise, we support only integer types.
1560 assert(Ty->isInteger() && "isSCEVable permitted a non-SCEVable type!");
1561 return Ty->getPrimitiveSizeInBits();
1562}
1563
1564/// getEffectiveSCEVType - Return a type with the same bitwidth as
1565/// the given type and which represents how SCEV will treat the given
1566/// type, for which isSCEVable must return true. For pointer types,
1567/// this is the pointer-sized integer type.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001568const Type *ScalarEvolution::getEffectiveSCEVType(const Type *Ty) const {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001569 assert(isSCEVable(Ty) && "Type is not SCEVable!");
1570
1571 if (Ty->isInteger())
1572 return Ty;
1573
1574 assert(isa<PointerType>(Ty) && "Unexpected non-pointer non-integer type!");
1575 return TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00001576}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001577
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001578SCEVHandle ScalarEvolution::getCouldNotCompute() {
Dan Gohman0ad08b02009-04-18 17:58:19 +00001579 return UnknownValue;
1580}
1581
Dan Gohmand83d4af2009-05-04 22:20:30 +00001582/// hasSCEV - Return true if the SCEV for this value has already been
Edwin Török0e828d62009-05-01 08:33:47 +00001583/// computed.
1584bool ScalarEvolution::hasSCEV(Value *V) const {
1585 return Scalars.count(V);
1586}
1587
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1589/// expression and create a new one.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001590SCEVHandle ScalarEvolution::getSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001591 assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001592
Dan Gohmanbff6b582009-05-04 22:30:44 +00001593 std::map<SCEVCallbackVH, SCEVHandle>::iterator I = Scalars.find(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001594 if (I != Scalars.end()) return I->second;
1595 SCEVHandle S = createSCEV(V);
Dan Gohmanbff6b582009-05-04 22:30:44 +00001596 Scalars.insert(std::make_pair(SCEVCallbackVH(V, this), S));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001597 return S;
1598}
1599
Dan Gohman01c2ee72009-04-16 03:18:22 +00001600/// getIntegerSCEV - Given an integer or FP type, create a constant for the
1601/// specified signed integer value and return a SCEV for the constant.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001602SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
1603 Ty = getEffectiveSCEVType(Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001604 Constant *C;
1605 if (Val == 0)
1606 C = Constant::getNullValue(Ty);
1607 else if (Ty->isFloatingPoint())
1608 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
1609 APFloat::IEEEdouble, Val));
1610 else
1611 C = ConstantInt::get(Ty, Val);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001612 return getUnknown(C);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001613}
1614
1615/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
1616///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001617SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001618 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001619 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001620
1621 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001622 Ty = getEffectiveSCEVType(Ty);
1623 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(Ty)));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001624}
1625
1626/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001627SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001628 if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001629 return getUnknown(ConstantExpr::getNot(VC->getValue()));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001630
1631 const Type *Ty = V->getType();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001632 Ty = getEffectiveSCEVType(Ty);
1633 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(Ty));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001634 return getMinusSCEV(AllOnes, V);
1635}
1636
1637/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
1638///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001639SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
Nick Lewycky37d04642009-04-23 05:15:08 +00001640 const SCEVHandle &RHS) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001641 // X - Y --> X + -Y
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001642 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohman01c2ee72009-04-16 03:18:22 +00001643}
1644
1645/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
1646/// input value to the specified type. If the type must be extended, it is zero
1647/// extended.
1648SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001649ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001650 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001651 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001652 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1653 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001654 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001655 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001656 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001657 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001658 return getTruncateExpr(V, Ty);
1659 return getZeroExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001660}
1661
1662/// getTruncateOrSignExtend - Return a SCEV corresponding to a conversion of the
1663/// input value to the specified type. If the type must be extended, it is sign
1664/// extended.
1665SCEVHandle
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001666ScalarEvolution::getTruncateOrSignExtend(const SCEVHandle &V,
Nick Lewycky37d04642009-04-23 05:15:08 +00001667 const Type *Ty) {
Dan Gohman01c2ee72009-04-16 03:18:22 +00001668 const Type *SrcTy = V->getType();
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001669 assert((SrcTy->isInteger() || (TD && isa<PointerType>(SrcTy))) &&
1670 (Ty->isInteger() || (TD && isa<PointerType>(Ty))) &&
Dan Gohman01c2ee72009-04-16 03:18:22 +00001671 "Cannot truncate or zero extend with non-integer arguments!");
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001672 if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
Dan Gohman01c2ee72009-04-16 03:18:22 +00001673 return V; // No conversion
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001674 if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001675 return getTruncateExpr(V, Ty);
1676 return getSignExtendExpr(V, Ty);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001677}
1678
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1680/// the specified instruction and replaces any references to the symbolic value
1681/// SymName with the specified value. This is used during PHI resolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001682void ScalarEvolution::
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1684 const SCEVHandle &NewVal) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00001685 std::map<SCEVCallbackVH, SCEVHandle>::iterator SI =
1686 Scalars.find(SCEVCallbackVH(I, this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 if (SI == Scalars.end()) return;
1688
1689 SCEVHandle NV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001690 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691 if (NV == SI->second) return; // No change.
1692
1693 SI->second = NV; // Update the scalars map!
1694
1695 // Any instruction values that use this instruction might also need to be
1696 // updated!
1697 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1698 UI != E; ++UI)
1699 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1700}
1701
1702/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1703/// a loop header, making it a potential recurrence, or it doesn't.
1704///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001705SCEVHandle ScalarEvolution::createNodeForPHI(PHINode *PN) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001706 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001707 if (const Loop *L = LI->getLoopFor(PN->getParent()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001708 if (L->getHeader() == PN->getParent()) {
1709 // If it lives in the loop header, it has two incoming values, one
1710 // from outside the loop, and one from inside.
1711 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1712 unsigned BackEdge = IncomingEdge^1;
1713
1714 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001715 SCEVHandle SymbolicName = getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001716 assert(Scalars.find(PN) == Scalars.end() &&
1717 "PHI node already processed?");
Dan Gohmanbff6b582009-05-04 22:30:44 +00001718 Scalars.insert(std::make_pair(SCEVCallbackVH(PN, this), SymbolicName));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719
1720 // Using this symbolic name for the PHI, analyze the value coming around
1721 // the back-edge.
1722 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1723
1724 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1725 // has a special value for the first iteration of the loop.
1726
1727 // If the value coming around the backedge is an add with the symbolic
1728 // value we just inserted, then we found a simple induction variable!
Dan Gohmanc76b5452009-05-04 22:02:23 +00001729 if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001730 // If there is a single occurrence of the symbolic value, replace it
1731 // with a recurrence.
1732 unsigned FoundIndex = Add->getNumOperands();
1733 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1734 if (Add->getOperand(i) == SymbolicName)
1735 if (FoundIndex == e) {
1736 FoundIndex = i;
1737 break;
1738 }
1739
1740 if (FoundIndex != Add->getNumOperands()) {
1741 // Create an add with everything but the specified operand.
1742 std::vector<SCEVHandle> Ops;
1743 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1744 if (i != FoundIndex)
1745 Ops.push_back(Add->getOperand(i));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001746 SCEVHandle Accum = getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001747
1748 // This is not a valid addrec if the step amount is varying each
1749 // loop iteration, but is not itself an addrec in this loop.
1750 if (Accum->isLoopInvariant(L) ||
1751 (isa<SCEVAddRecExpr>(Accum) &&
1752 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1753 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001754 SCEVHandle PHISCEV = getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755
1756 // Okay, for the entire analysis of this edge we assumed the PHI
1757 // to be symbolic. We now need to go back and update all of the
1758 // entries for the scalars that use the PHI (except for the PHI
1759 // itself) to use the new analyzed value instead of the "symbolic"
1760 // value.
1761 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1762 return PHISCEV;
1763 }
1764 }
Dan Gohmanc76b5452009-05-04 22:02:23 +00001765 } else if (const SCEVAddRecExpr *AddRec =
1766 dyn_cast<SCEVAddRecExpr>(BEValue)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767 // Otherwise, this could be a loop like this:
1768 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1769 // In this case, j = {1,+,1} and BEValue is j.
1770 // Because the other in-value of i (0) fits the evolution of BEValue
1771 // i really is an addrec evolution.
1772 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1773 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1774
1775 // If StartVal = j.start - j.stride, we can use StartVal as the
1776 // initial step of the addrec evolution.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001777 if (StartVal == getMinusSCEV(AddRec->getOperand(0),
Dan Gohman89f85052007-10-22 18:31:58 +00001778 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779 SCEVHandle PHISCEV =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001780 getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781
1782 // Okay, for the entire analysis of this edge we assumed the PHI
1783 // to be symbolic. We now need to go back and update all of the
1784 // entries for the scalars that use the PHI (except for the PHI
1785 // itself) to use the new analyzed value instead of the "symbolic"
1786 // value.
1787 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1788 return PHISCEV;
1789 }
1790 }
1791 }
1792
1793 return SymbolicName;
1794 }
1795
1796 // If it's not a loop phi, we can't handle it yet.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001797 return getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001798}
1799
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001800/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1801/// guaranteed to end in (at every loop iteration). It is, at the same time,
1802/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1803/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001804static uint32_t GetMinTrailingZeros(SCEVHandle S, const ScalarEvolution &SE) {
Dan Gohmanc76b5452009-05-04 22:02:23 +00001805 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001806 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001807
Dan Gohmanc76b5452009-05-04 22:02:23 +00001808 if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001809 return std::min(GetMinTrailingZeros(T->getOperand(), SE),
1810 (uint32_t)SE.getTypeSizeInBits(T->getType()));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001811
Dan Gohmanc76b5452009-05-04 22:02:23 +00001812 if (const SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001813 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1814 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1815 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001816 }
1817
Dan Gohmanc76b5452009-05-04 22:02:23 +00001818 if (const SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001819 uint32_t OpRes = GetMinTrailingZeros(E->getOperand(), SE);
1820 return OpRes == SE.getTypeSizeInBits(E->getOperand()->getType()) ?
1821 SE.getTypeSizeInBits(E->getOperand()->getType()) : OpRes;
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001822 }
1823
Dan Gohmanc76b5452009-05-04 22:02:23 +00001824 if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001825 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001826 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001827 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001828 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001829 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001830 }
1831
Dan Gohmanc76b5452009-05-04 22:02:23 +00001832 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001833 // The result is the sum of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001834 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
1835 uint32_t BitWidth = SE.getTypeSizeInBits(M->getType());
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001836 for (unsigned i = 1, e = M->getNumOperands();
1837 SumOpRes != BitWidth && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001838 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i), SE),
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001839 BitWidth);
1840 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001841 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001842
Dan Gohmanc76b5452009-05-04 22:02:23 +00001843 if (const SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001844 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001845 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0), SE);
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001846 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001847 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i), SE));
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001848 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001850
Dan Gohmanc76b5452009-05-04 22:02:23 +00001851 if (const SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
Nick Lewycky711640a2007-11-25 22:41:31 +00001852 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001853 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewycky711640a2007-11-25 22:41:31 +00001854 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001855 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewycky711640a2007-11-25 22:41:31 +00001856 return MinOpRes;
1857 }
1858
Dan Gohmanc76b5452009-05-04 22:02:23 +00001859 if (const SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001860 // The result is the min of all operands results.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001861 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0), SE);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001862 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001863 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i), SE));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001864 return MinOpRes;
1865 }
1866
Nick Lewycky35b56022009-01-13 09:18:58 +00001867 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001868 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001869}
1870
1871/// createSCEV - We know that there is no SCEV for the specified value.
1872/// Analyze the expression.
1873///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001874SCEVHandle ScalarEvolution::createSCEV(Value *V) {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001875 if (!isSCEVable(V->getType()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001876 return getUnknown(V);
Dan Gohman01c2ee72009-04-16 03:18:22 +00001877
Dan Gohman3996f472008-06-22 19:56:46 +00001878 unsigned Opcode = Instruction::UserOp1;
1879 if (Instruction *I = dyn_cast<Instruction>(V))
1880 Opcode = I->getOpcode();
1881 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1882 Opcode = CE->getOpcode();
1883 else
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001884 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001885
Dan Gohman3996f472008-06-22 19:56:46 +00001886 User *U = cast<User>(V);
1887 switch (Opcode) {
1888 case Instruction::Add:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001889 return getAddExpr(getSCEV(U->getOperand(0)),
1890 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001891 case Instruction::Mul:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001892 return getMulExpr(getSCEV(U->getOperand(0)),
1893 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001894 case Instruction::UDiv:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001895 return getUDivExpr(getSCEV(U->getOperand(0)),
1896 getSCEV(U->getOperand(1)));
Dan Gohman3996f472008-06-22 19:56:46 +00001897 case Instruction::Sub:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001898 return getMinusSCEV(getSCEV(U->getOperand(0)),
1899 getSCEV(U->getOperand(1)));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001900 case Instruction::And:
1901 // For an expression like x&255 that merely masks off the high bits,
1902 // use zext(trunc(x)) as the SCEV expression.
1903 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001904 if (CI->isNullValue())
1905 return getSCEV(U->getOperand(1));
Dan Gohmanc7ebba12009-04-27 01:41:10 +00001906 if (CI->isAllOnesValue())
1907 return getSCEV(U->getOperand(0));
Dan Gohman53bf64a2009-04-21 02:26:00 +00001908 const APInt &A = CI->getValue();
1909 unsigned Ones = A.countTrailingOnes();
1910 if (APIntOps::isMask(Ones, A))
1911 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001912 getZeroExtendExpr(getTruncateExpr(getSCEV(U->getOperand(0)),
1913 IntegerType::get(Ones)),
1914 U->getType());
Dan Gohman53bf64a2009-04-21 02:26:00 +00001915 }
1916 break;
Dan Gohman3996f472008-06-22 19:56:46 +00001917 case Instruction::Or:
1918 // If the RHS of the Or is a constant, we may have something like:
1919 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1920 // optimizations will transparently handle this case.
1921 //
1922 // In order for this transformation to be safe, the LHS must be of the
1923 // form X*(2^n) and the Or constant must be less than 2^n.
1924 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1925 SCEVHandle LHS = getSCEV(U->getOperand(0));
1926 const APInt &CIVal = CI->getValue();
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001927 if (GetMinTrailingZeros(LHS, *this) >=
Dan Gohman3996f472008-06-22 19:56:46 +00001928 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001929 return getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001930 }
Dan Gohman3996f472008-06-22 19:56:46 +00001931 break;
1932 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001933 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001934 // If the RHS of the xor is a signbit, then this is just an add.
1935 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001936 if (CI->getValue().isSignBit())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001937 return getAddExpr(getSCEV(U->getOperand(0)),
1938 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001939
1940 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001941 else if (CI->isAllOnesValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001942 return getNotSCEV(getSCEV(U->getOperand(0)));
Dan Gohman3996f472008-06-22 19:56:46 +00001943 }
1944 break;
1945
1946 case Instruction::Shl:
1947 // Turn shift left of a constant amount into a multiply.
1948 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1949 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1950 Constant *X = ConstantInt::get(
1951 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001952 return getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Dan Gohman3996f472008-06-22 19:56:46 +00001953 }
1954 break;
1955
Nick Lewycky7fd27892008-07-07 06:15:49 +00001956 case Instruction::LShr:
Nick Lewycky35b56022009-01-13 09:18:58 +00001957 // Turn logical shift right of a constant into a unsigned divide.
Nick Lewycky7fd27892008-07-07 06:15:49 +00001958 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1959 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1960 Constant *X = ConstantInt::get(
1961 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001962 return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001963 }
1964 break;
1965
Dan Gohman53bf64a2009-04-21 02:26:00 +00001966 case Instruction::AShr:
1967 // For a two-shift sext-inreg, use sext(trunc(x)) as the SCEV expression.
1968 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1)))
1969 if (Instruction *L = dyn_cast<Instruction>(U->getOperand(0)))
1970 if (L->getOpcode() == Instruction::Shl &&
1971 L->getOperand(1) == U->getOperand(1)) {
Dan Gohman91ae1e72009-04-25 17:05:40 +00001972 unsigned BitWidth = getTypeSizeInBits(U->getType());
1973 uint64_t Amt = BitWidth - CI->getZExtValue();
1974 if (Amt == BitWidth)
1975 return getSCEV(L->getOperand(0)); // shift by zero --> noop
1976 if (Amt > BitWidth)
1977 return getIntegerSCEV(0, U->getType()); // value is undefined
Dan Gohman53bf64a2009-04-21 02:26:00 +00001978 return
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001979 getSignExtendExpr(getTruncateExpr(getSCEV(L->getOperand(0)),
Dan Gohman91ae1e72009-04-25 17:05:40 +00001980 IntegerType::get(Amt)),
Dan Gohman53bf64a2009-04-21 02:26:00 +00001981 U->getType());
1982 }
1983 break;
1984
Dan Gohman3996f472008-06-22 19:56:46 +00001985 case Instruction::Trunc:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001986 return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001987
1988 case Instruction::ZExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001989 return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001990
1991 case Instruction::SExt:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00001992 return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
Dan Gohman3996f472008-06-22 19:56:46 +00001993
1994 case Instruction::BitCast:
1995 // BitCasts are no-op casts so we just eliminate the cast.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00001996 if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
Dan Gohman3996f472008-06-22 19:56:46 +00001997 return getSCEV(U->getOperand(0));
1998 break;
1999
Dan Gohman01c2ee72009-04-16 03:18:22 +00002000 case Instruction::IntToPtr:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002001 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002002 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002003 TD->getIntPtrType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00002004
2005 case Instruction::PtrToInt:
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002006 if (!TD) break; // Without TD we can't analyze pointers.
Dan Gohman01c2ee72009-04-16 03:18:22 +00002007 return getTruncateOrZeroExtend(getSCEV(U->getOperand(0)),
2008 U->getType());
2009
2010 case Instruction::GetElementPtr: {
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002011 if (!TD) break; // Without TD we can't analyze pointers.
2012 const Type *IntPtrTy = TD->getIntPtrType();
Dan Gohman01c2ee72009-04-16 03:18:22 +00002013 Value *Base = U->getOperand(0);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002014 SCEVHandle TotalOffset = getIntegerSCEV(0, IntPtrTy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002015 gep_type_iterator GTI = gep_type_begin(U);
2016 for (GetElementPtrInst::op_iterator I = next(U->op_begin()),
2017 E = U->op_end();
2018 I != E; ++I) {
2019 Value *Index = *I;
2020 // Compute the (potentially symbolic) offset in bytes for this index.
2021 if (const StructType *STy = dyn_cast<StructType>(*GTI++)) {
2022 // For a struct, add the member offset.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00002023 const StructLayout &SL = *TD->getStructLayout(STy);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002024 unsigned FieldNo = cast<ConstantInt>(Index)->getZExtValue();
2025 uint64_t Offset = SL.getElementOffset(FieldNo);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002026 TotalOffset = getAddExpr(TotalOffset,
2027 getIntegerSCEV(Offset, IntPtrTy));
Dan Gohman01c2ee72009-04-16 03:18:22 +00002028 } else {
2029 // For an array, add the element offset, explicitly scaled.
2030 SCEVHandle LocalOffset = getSCEV(Index);
2031 if (!isa<PointerType>(LocalOffset->getType()))
2032 // Getelementptr indicies are signed.
2033 LocalOffset = getTruncateOrSignExtend(LocalOffset,
2034 IntPtrTy);
2035 LocalOffset =
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002036 getMulExpr(LocalOffset,
2037 getIntegerSCEV(TD->getTypePaddedSize(*GTI),
2038 IntPtrTy));
2039 TotalOffset = getAddExpr(TotalOffset, LocalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002040 }
2041 }
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002042 return getAddExpr(getSCEV(Base), TotalOffset);
Dan Gohman01c2ee72009-04-16 03:18:22 +00002043 }
2044
Dan Gohman3996f472008-06-22 19:56:46 +00002045 case Instruction::PHI:
2046 return createNodeForPHI(cast<PHINode>(U));
2047
2048 case Instruction::Select:
2049 // This could be a smax or umax that was lowered earlier.
2050 // Try to recover it.
2051 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
2052 Value *LHS = ICI->getOperand(0);
2053 Value *RHS = ICI->getOperand(1);
2054 switch (ICI->getPredicate()) {
2055 case ICmpInst::ICMP_SLT:
2056 case ICmpInst::ICMP_SLE:
2057 std::swap(LHS, RHS);
2058 // fall through
2059 case ICmpInst::ICMP_SGT:
2060 case ICmpInst::ICMP_SGE:
2061 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002062 return getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002063 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
Eli Friedman8e2fd032008-07-30 04:36:32 +00002064 // ~smax(~x, ~y) == smin(x, y).
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002065 return getNotSCEV(getSMaxExpr(
2066 getNotSCEV(getSCEV(LHS)),
2067 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002068 break;
2069 case ICmpInst::ICMP_ULT:
2070 case ICmpInst::ICMP_ULE:
2071 std::swap(LHS, RHS);
2072 // fall through
2073 case ICmpInst::ICMP_UGT:
2074 case ICmpInst::ICMP_UGE:
2075 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002076 return getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
Dan Gohman3996f472008-06-22 19:56:46 +00002077 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
2078 // ~umax(~x, ~y) == umin(x, y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002079 return getNotSCEV(getUMaxExpr(getNotSCEV(getSCEV(LHS)),
2080 getNotSCEV(getSCEV(RHS))));
Dan Gohman3996f472008-06-22 19:56:46 +00002081 break;
2082 default:
2083 break;
2084 }
2085 }
2086
2087 default: // We cannot analyze this expression.
2088 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002089 }
2090
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002091 return getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002092}
2093
2094
2095
2096//===----------------------------------------------------------------------===//
2097// Iteration Count Computation Code
2098//
2099
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002100/// getBackedgeTakenCount - If the specified loop has a predictable
2101/// backedge-taken count, return it, otherwise return a SCEVCouldNotCompute
2102/// object. The backedge-taken count is the number of times the loop header
2103/// will be branched to from within the loop. This is one less than the
2104/// trip count of the loop, since it doesn't count the first iteration,
2105/// when the header is branched to from outside the loop.
2106///
2107/// Note that it is not valid to call this method on a loop without a
2108/// loop-invariant backedge-taken count (see
2109/// hasLoopInvariantBackedgeTakenCount).
2110///
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002111SCEVHandle ScalarEvolution::getBackedgeTakenCount(const Loop *L) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002112 return getBackedgeTakenInfo(L).Exact;
2113}
2114
2115/// getMaxBackedgeTakenCount - Similar to getBackedgeTakenCount, except
2116/// return the least SCEV value that is known never to be less than the
2117/// actual backedge taken count.
2118SCEVHandle ScalarEvolution::getMaxBackedgeTakenCount(const Loop *L) {
2119 return getBackedgeTakenInfo(L).Max;
2120}
2121
2122const ScalarEvolution::BackedgeTakenInfo &
2123ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
Dan Gohmana9dba962009-04-27 20:16:15 +00002124 // Initially insert a CouldNotCompute for this loop. If the insertion
2125 // succeeds, procede to actually compute a backedge-taken count and
2126 // update the value. The temporary CouldNotCompute value tells SCEV
2127 // code elsewhere that it shouldn't attempt to request a new
2128 // backedge-taken count, which could result in infinite recursion.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002129 std::pair<std::map<const Loop*, BackedgeTakenInfo>::iterator, bool> Pair =
Dan Gohmana9dba962009-04-27 20:16:15 +00002130 BackedgeTakenCounts.insert(std::make_pair(L, getCouldNotCompute()));
2131 if (Pair.second) {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002132 BackedgeTakenInfo ItCount = ComputeBackedgeTakenCount(L);
2133 if (ItCount.Exact != UnknownValue) {
2134 assert(ItCount.Exact->isLoopInvariant(L) &&
2135 ItCount.Max->isLoopInvariant(L) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002136 "Computed trip count isn't loop invariant for loop!");
2137 ++NumTripCountsComputed;
Dan Gohmana9dba962009-04-27 20:16:15 +00002138
Dan Gohmana9dba962009-04-27 20:16:15 +00002139 // Update the value in the map.
2140 Pair.first->second = ItCount;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002141 } else if (isa<PHINode>(L->getHeader()->begin())) {
2142 // Only count loops that have phi nodes as not being computable.
2143 ++NumTripCountsNotComputed;
2144 }
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002145
2146 // Now that we know more about the trip count for this loop, forget any
2147 // existing SCEV values for PHI nodes in this loop since they are only
2148 // conservative estimates made without the benefit
2149 // of trip count information.
2150 if (ItCount.hasAnyInfo())
Dan Gohman94623022009-05-02 17:43:35 +00002151 forgetLoopPHIs(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152 }
Dan Gohmana9dba962009-04-27 20:16:15 +00002153 return Pair.first->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002154}
2155
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002156/// forgetLoopBackedgeTakenCount - This method should be called by the
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002157/// client when it has changed a loop in a way that may effect
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002158/// ScalarEvolution's ability to compute a trip count, or if the loop
2159/// is deleted.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002160void ScalarEvolution::forgetLoopBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002161 BackedgeTakenCounts.erase(L);
Dan Gohman94623022009-05-02 17:43:35 +00002162 forgetLoopPHIs(L);
2163}
2164
2165/// forgetLoopPHIs - Delete the memoized SCEVs associated with the
2166/// PHI nodes in the given loop. This is used when the trip count of
2167/// the loop may have changed.
2168void ScalarEvolution::forgetLoopPHIs(const Loop *L) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002169 BasicBlock *Header = L->getHeader();
2170
2171 SmallVector<Instruction *, 16> Worklist;
2172 for (BasicBlock::iterator I = Header->begin();
Dan Gohman94623022009-05-02 17:43:35 +00002173 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Dan Gohmanbff6b582009-05-04 22:30:44 +00002174 Worklist.push_back(PN);
2175
2176 while (!Worklist.empty()) {
2177 Instruction *I = Worklist.pop_back_val();
2178 if (Scalars.erase(I))
2179 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
2180 UI != UE; ++UI)
2181 Worklist.push_back(cast<Instruction>(UI));
2182 }
Dan Gohmanf3a060a2009-02-17 20:49:49 +00002183}
2184
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002185/// ComputeBackedgeTakenCount - Compute the number of times the backedge
2186/// of the specified loop will execute.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002187ScalarEvolution::BackedgeTakenInfo
2188ScalarEvolution::ComputeBackedgeTakenCount(const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00002190 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002191 L->getExitBlocks(ExitBlocks);
2192 if (ExitBlocks.size() != 1) return UnknownValue;
2193
2194 // Okay, there is one exit block. Try to find the condition that causes the
2195 // loop to be exited.
2196 BasicBlock *ExitBlock = ExitBlocks[0];
2197
2198 BasicBlock *ExitingBlock = 0;
2199 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
2200 PI != E; ++PI)
2201 if (L->contains(*PI)) {
2202 if (ExitingBlock == 0)
2203 ExitingBlock = *PI;
2204 else
2205 return UnknownValue; // More than one block exiting!
2206 }
2207 assert(ExitingBlock && "No exits from loop, something is broken!");
2208
2209 // Okay, we've computed the exiting block. See what condition causes us to
2210 // exit.
2211 //
2212 // FIXME: we should be able to handle switch instructions (with a single exit)
2213 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
2214 if (ExitBr == 0) return UnknownValue;
2215 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
2216
2217 // At this point, we know we have a conditional branch that determines whether
2218 // the loop is exited. However, we don't know if the branch is executed each
2219 // time through the loop. If not, then the execution count of the branch will
2220 // not be equal to the trip count of the loop.
2221 //
2222 // Currently we check for this by checking to see if the Exit branch goes to
2223 // the loop header. If so, we know it will always execute the same number of
2224 // times as the loop. We also handle the case where the exit block *is* the
2225 // loop header. This is common for un-rotated loops. More extensive analysis
2226 // could be done to handle more cases here.
2227 if (ExitBr->getSuccessor(0) != L->getHeader() &&
2228 ExitBr->getSuccessor(1) != L->getHeader() &&
2229 ExitBr->getParent() != L->getHeader())
2230 return UnknownValue;
2231
2232 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
2233
Nick Lewyckyb3d24332008-02-21 08:34:02 +00002234 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002235 // Note that ICmpInst deals with pointer comparisons too so we must check
2236 // the type of the operand.
2237 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002238 return ComputeBackedgeTakenCountExhaustively(L, ExitBr->getCondition(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002239 ExitBr->getSuccessor(0) == ExitBlock);
2240
2241 // If the condition was exit on true, convert the condition to exit on false
2242 ICmpInst::Predicate Cond;
2243 if (ExitBr->getSuccessor(1) == ExitBlock)
2244 Cond = ExitCond->getPredicate();
2245 else
2246 Cond = ExitCond->getInversePredicate();
2247
2248 // Handle common loops like: for (X = "string"; *X; ++X)
2249 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
2250 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
2251 SCEVHandle ItCnt =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002252 ComputeLoadConstantCompareBackedgeTakenCount(LI, RHS, L, Cond);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002253 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
2254 }
2255
2256 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
2257 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
2258
2259 // Try to evaluate any dependencies out of the loop.
2260 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
2261 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
2262 Tmp = getSCEVAtScope(RHS, L);
2263 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
2264
2265 // At this point, we would like to compute how many iterations of the
2266 // loop the predicate will return true for these inputs.
Dan Gohman2d96e352008-09-16 18:52:57 +00002267 if (LHS->isLoopInvariant(L) && !RHS->isLoopInvariant(L)) {
2268 // If there is a loop-invariant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002269 std::swap(LHS, RHS);
2270 Cond = ICmpInst::getSwappedPredicate(Cond);
2271 }
2272
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002273 // If we have a comparison of a chrec against a constant, try to use value
2274 // ranges to answer this query.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002275 if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
2276 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277 if (AddRec->getLoop() == L) {
2278 // Form the comparison range using the constant of the correct type so
2279 // that the ConstantRange class knows to do a signed or unsigned
2280 // comparison.
2281 ConstantInt *CompVal = RHSC->getValue();
2282 const Type *RealTy = ExitCond->getOperand(0)->getType();
2283 CompVal = dyn_cast<ConstantInt>(
2284 ConstantExpr::getBitCast(CompVal, RealTy));
2285 if (CompVal) {
2286 // Form the constant range.
2287 ConstantRange CompRange(
2288 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
2289
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002290 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
2292 }
2293 }
2294
2295 switch (Cond) {
2296 case ICmpInst::ICMP_NE: { // while (X != Y)
2297 // Convert to: while (X-Y != 0)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002298 SCEVHandle TC = HowFarToZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002299 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2300 break;
2301 }
2302 case ICmpInst::ICMP_EQ: {
2303 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002304 SCEVHandle TC = HowFarToNonZero(getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
2306 break;
2307 }
2308 case ICmpInst::ICMP_SLT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002309 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, true);
2310 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002311 break;
2312 }
2313 case ICmpInst::ICMP_SGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002314 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2315 getNotSCEV(RHS), L, true);
2316 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002317 break;
2318 }
2319 case ICmpInst::ICMP_ULT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002320 BackedgeTakenInfo BTI = HowManyLessThans(LHS, RHS, L, false);
2321 if (BTI.hasAnyInfo()) return BTI;
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002322 break;
2323 }
2324 case ICmpInst::ICMP_UGT: {
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00002325 BackedgeTakenInfo BTI = HowManyLessThans(getNotSCEV(LHS),
2326 getNotSCEV(RHS), L, false);
2327 if (BTI.hasAnyInfo()) return BTI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002328 break;
2329 }
2330 default:
2331#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002332 errs() << "ComputeBackedgeTakenCount ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002333 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Dan Gohman13058cc2009-04-21 00:47:46 +00002334 errs() << "[unsigned] ";
2335 errs() << *LHS << " "
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002336 << Instruction::getOpcodeName(Instruction::ICmp)
2337 << " " << *RHS << "\n";
2338#endif
2339 break;
2340 }
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002341 return
2342 ComputeBackedgeTakenCountExhaustively(L, ExitCond,
2343 ExitBr->getSuccessor(0) == ExitBlock);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344}
2345
2346static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002347EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2348 ScalarEvolution &SE) {
2349 SCEVHandle InVal = SE.getConstant(C);
2350 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002351 assert(isa<SCEVConstant>(Val) &&
2352 "Evaluation of SCEV at constant didn't fold correctly?");
2353 return cast<SCEVConstant>(Val)->getValue();
2354}
2355
2356/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2357/// and a GEP expression (missing the pointer index) indexing into it, return
2358/// the addressed element of the initializer or null if the index expression is
2359/// invalid.
2360static Constant *
2361GetAddressedElementFromGlobal(GlobalVariable *GV,
2362 const std::vector<ConstantInt*> &Indices) {
2363 Constant *Init = GV->getInitializer();
2364 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2365 uint64_t Idx = Indices[i]->getZExtValue();
2366 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2367 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2368 Init = cast<Constant>(CS->getOperand(Idx));
2369 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2370 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2371 Init = cast<Constant>(CA->getOperand(Idx));
2372 } else if (isa<ConstantAggregateZero>(Init)) {
2373 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2374 assert(Idx < STy->getNumElements() && "Bad struct index!");
2375 Init = Constant::getNullValue(STy->getElementType(Idx));
2376 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2377 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2378 Init = Constant::getNullValue(ATy->getElementType());
2379 } else {
2380 assert(0 && "Unknown constant aggregate type!");
2381 }
2382 return 0;
2383 } else {
2384 return 0; // Unknown initializer type
2385 }
2386 }
2387 return Init;
2388}
2389
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002390/// ComputeLoadConstantCompareBackedgeTakenCount - Given an exit condition of
2391/// 'icmp op load X, cst', try to see if we can compute the backedge
2392/// execution count.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002393SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002394ComputeLoadConstantCompareBackedgeTakenCount(LoadInst *LI, Constant *RHS,
2395 const Loop *L,
2396 ICmpInst::Predicate predicate) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002397 if (LI->isVolatile()) return UnknownValue;
2398
2399 // Check to see if the loaded pointer is a getelementptr of a global.
2400 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2401 if (!GEP) return UnknownValue;
2402
2403 // Make sure that it is really a constant global we are gepping, with an
2404 // initializer, and make sure the first IDX is really 0.
2405 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2406 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2407 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2408 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2409 return UnknownValue;
2410
2411 // Okay, we allow one non-constant index into the GEP instruction.
2412 Value *VarIdx = 0;
2413 std::vector<ConstantInt*> Indexes;
2414 unsigned VarIdxNum = 0;
2415 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2416 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2417 Indexes.push_back(CI);
2418 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2419 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2420 VarIdx = GEP->getOperand(i);
2421 VarIdxNum = i-2;
2422 Indexes.push_back(0);
2423 }
2424
2425 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2426 // Check to see if X is a loop variant variable value now.
2427 SCEVHandle Idx = getSCEV(VarIdx);
2428 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2429 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2430
2431 // We can only recognize very limited forms of loop index expressions, in
2432 // particular, only affine AddRec's like {C1,+,C2}.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002433 const SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002434 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2435 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2436 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2437 return UnknownValue;
2438
2439 unsigned MaxSteps = MaxBruteForceIterations;
2440 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2441 ConstantInt *ItCst =
2442 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002443 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002444
2445 // Form the GEP offset.
2446 Indexes[VarIdxNum] = Val;
2447
2448 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2449 if (Result == 0) break; // Cannot compute!
2450
2451 // Evaluate the condition for this iteration.
2452 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2453 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2454 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2455#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00002456 errs() << "\n***\n*** Computed loop count " << *ItCst
2457 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2458 << "***\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002459#endif
2460 ++NumArrayLenItCounts;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002461 return getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002462 }
2463 }
2464 return UnknownValue;
2465}
2466
2467
2468/// CanConstantFold - Return true if we can constant fold an instruction of the
2469/// specified type, assuming that all operands were constants.
2470static bool CanConstantFold(const Instruction *I) {
2471 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2472 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2473 return true;
2474
2475 if (const CallInst *CI = dyn_cast<CallInst>(I))
2476 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002477 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002478 return false;
2479}
2480
2481/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2482/// in the loop that V is derived from. We allow arbitrary operations along the
2483/// way, but the operands of an operation must either be constants or a value
2484/// derived from a constant PHI. If this expression does not fit with these
2485/// constraints, return null.
2486static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2487 // If this is not an instruction, or if this is an instruction outside of the
2488 // loop, it can't be derived from a loop PHI.
2489 Instruction *I = dyn_cast<Instruction>(V);
2490 if (I == 0 || !L->contains(I->getParent())) return 0;
2491
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002492 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002493 if (L->getHeader() == I->getParent())
2494 return PN;
2495 else
2496 // We don't currently keep track of the control flow needed to evaluate
2497 // PHIs, so we cannot handle PHIs inside of loops.
2498 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002499 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002500
2501 // If we won't be able to constant fold this expression even if the operands
2502 // are constants, return early.
2503 if (!CanConstantFold(I)) return 0;
2504
2505 // Otherwise, we can evaluate this instruction if all of its operands are
2506 // constant or derived from a PHI node themselves.
2507 PHINode *PHI = 0;
2508 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2509 if (!(isa<Constant>(I->getOperand(Op)) ||
2510 isa<GlobalValue>(I->getOperand(Op)))) {
2511 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2512 if (P == 0) return 0; // Not evolving from PHI
2513 if (PHI == 0)
2514 PHI = P;
2515 else if (PHI != P)
2516 return 0; // Evolving from multiple different PHIs.
2517 }
2518
2519 // This is a expression evolving from a constant PHI!
2520 return PHI;
2521}
2522
2523/// EvaluateExpression - Given an expression that passes the
2524/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2525/// in the loop has the value PHIVal. If we can't fold this expression for some
2526/// reason, return null.
2527static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2528 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002529 if (Constant *C = dyn_cast<Constant>(V)) return C;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002530 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) return GV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002531 Instruction *I = cast<Instruction>(V);
2532
2533 std::vector<Constant*> Operands;
2534 Operands.resize(I->getNumOperands());
2535
2536 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2537 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2538 if (Operands[i] == 0) return 0;
2539 }
2540
Chris Lattnerd6e56912007-12-10 22:53:04 +00002541 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2542 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2543 &Operands[0], Operands.size());
2544 else
2545 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2546 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002547}
2548
2549/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2550/// in the header of its containing loop, we know the loop executes a
2551/// constant number of times, and the PHI node is just a recurrence
2552/// involving constants, fold it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002553Constant *ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002554getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& BEs, const Loop *L){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002555 std::map<PHINode*, Constant*>::iterator I =
2556 ConstantEvolutionLoopExitValue.find(PN);
2557 if (I != ConstantEvolutionLoopExitValue.end())
2558 return I->second;
2559
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002560 if (BEs.ugt(APInt(BEs.getBitWidth(),MaxBruteForceIterations)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002561 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2562
2563 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2564
2565 // Since the loop is canonicalized, the PHI node must have two entries. One
2566 // entry must be a constant (coming in from outside of the loop), and the
2567 // second must be derived from the same PHI.
2568 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2569 Constant *StartCST =
2570 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2571 if (StartCST == 0)
2572 return RetVal = 0; // Must be a constant.
2573
2574 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2575 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2576 if (PN2 != PN)
2577 return RetVal = 0; // Not derived from same PHI.
2578
2579 // Execute the loop symbolically to determine the exit value.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002580 if (BEs.getActiveBits() >= 32)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002581 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2582
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002583 unsigned NumIterations = BEs.getZExtValue(); // must be in range
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002584 unsigned IterationNum = 0;
2585 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2586 if (IterationNum == NumIterations)
2587 return RetVal = PHIVal; // Got exit value!
2588
2589 // Compute the value of the PHI node for the next iteration.
2590 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2591 if (NextPHI == PHIVal)
2592 return RetVal = NextPHI; // Stopped evolving!
2593 if (NextPHI == 0)
2594 return 0; // Couldn't evaluate!
2595 PHIVal = NextPHI;
2596 }
2597}
2598
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002599/// ComputeBackedgeTakenCountExhaustively - If the trip is known to execute a
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002600/// constant number of times (the condition evolves only from constants),
2601/// try to evaluate a few iterations of the loop until we get the exit
2602/// condition gets a value of ExitWhen (true or false). If we cannot
2603/// evaluate the trip count of the loop, return UnknownValue.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002604SCEVHandle ScalarEvolution::
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002605ComputeBackedgeTakenCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002606 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2607 if (PN == 0) return UnknownValue;
2608
2609 // Since the loop is canonicalized, the PHI node must have two entries. One
2610 // entry must be a constant (coming in from outside of the loop), and the
2611 // second must be derived from the same PHI.
2612 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2613 Constant *StartCST =
2614 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2615 if (StartCST == 0) return UnknownValue; // Must be a constant.
2616
2617 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2618 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2619 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2620
2621 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2622 // the loop symbolically to determine when the condition gets a value of
2623 // "ExitWhen".
2624 unsigned IterationNum = 0;
2625 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2626 for (Constant *PHIVal = StartCST;
2627 IterationNum != MaxIterations; ++IterationNum) {
2628 ConstantInt *CondVal =
2629 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2630
2631 // Couldn't symbolically evaluate.
2632 if (!CondVal) return UnknownValue;
2633
2634 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2635 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2636 ++NumBruteForceTripCountsComputed;
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002637 return getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002638 }
2639
2640 // Compute the value of the PHI node for the next iteration.
2641 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2642 if (NextPHI == 0 || NextPHI == PHIVal)
2643 return UnknownValue; // Couldn't evaluate or not making progress...
2644 PHIVal = NextPHI;
2645 }
2646
2647 // Too many iterations were needed to evaluate.
2648 return UnknownValue;
2649}
2650
2651/// getSCEVAtScope - Compute the value of the specified expression within the
2652/// indicated loop (which may be null to indicate in no loop). If the
2653/// expression cannot be evaluated, return UnknownValue.
Dan Gohmanbff6b582009-05-04 22:30:44 +00002654SCEVHandle ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002655 // FIXME: this should be turned into a virtual method on SCEV!
2656
2657 if (isa<SCEVConstant>(V)) return V;
2658
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002659 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002660 // exit value from the loop without using SCEVs.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002661 if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002662 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002663 const Loop *LI = (*this->LI)[I->getParent()];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2665 if (PHINode *PN = dyn_cast<PHINode>(I))
2666 if (PN->getParent() == LI->getHeader()) {
2667 // Okay, there is no closed form solution for the PHI node. Check
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002668 // to see if the loop that contains it has a known backedge-taken
2669 // count. If so, we may be able to force computation of the exit
2670 // value.
2671 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(LI);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002672 if (const SCEVConstant *BTCC =
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002673 dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674 // Okay, we know how many times the containing loop executes. If
2675 // this is a constant evolving PHI node, get the final value at
2676 // the specified iteration number.
2677 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002678 BTCC->getValue()->getValue(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002679 LI);
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002680 if (RV) return getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681 }
2682 }
2683
2684 // Okay, this is an expression that we cannot symbolically evaluate
2685 // into a SCEV. Check to see if it's possible to symbolically evaluate
2686 // the arguments into constants, and if so, try to constant propagate the
2687 // result. This is particularly useful for computing loop exit values.
2688 if (CanConstantFold(I)) {
2689 std::vector<Constant*> Operands;
2690 Operands.reserve(I->getNumOperands());
2691 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2692 Value *Op = I->getOperand(i);
2693 if (Constant *C = dyn_cast<Constant>(Op)) {
2694 Operands.push_back(C);
2695 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002696 // If any of the operands is non-constant and if they are
Dan Gohman01c2ee72009-04-16 03:18:22 +00002697 // non-integer and non-pointer, don't even try to analyze them
2698 // with scev techniques.
Dan Gohman5e4eb762009-04-30 16:40:30 +00002699 if (!isSCEVable(Op->getType()))
Chris Lattner3fff4642007-11-23 08:46:22 +00002700 return V;
Dan Gohman01c2ee72009-04-16 03:18:22 +00002701
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002702 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002703 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002704 Constant *C = SC->getValue();
2705 if (C->getType() != Op->getType())
2706 C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2707 Op->getType(),
2708 false),
2709 C, Op->getType());
2710 Operands.push_back(C);
Dan Gohmanc76b5452009-05-04 22:02:23 +00002711 } else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
Dan Gohman5e4eb762009-04-30 16:40:30 +00002712 if (Constant *C = dyn_cast<Constant>(SU->getValue())) {
2713 if (C->getType() != Op->getType())
2714 C =
2715 ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
2716 Op->getType(),
2717 false),
2718 C, Op->getType());
2719 Operands.push_back(C);
2720 } else
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002721 return V;
2722 } else {
2723 return V;
2724 }
2725 }
2726 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002727
2728 Constant *C;
2729 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2730 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2731 &Operands[0], Operands.size());
2732 else
2733 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2734 &Operands[0], Operands.size());
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002735 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002736 }
2737 }
2738
2739 // This is some other type of SCEVUnknown, just return it.
2740 return V;
2741 }
2742
Dan Gohmanc76b5452009-05-04 22:02:23 +00002743 if (const SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002744 // Avoid performing the look-up in the common case where the specified
2745 // expression has no loop-variant portions.
2746 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2747 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2748 if (OpAtScope != Comm->getOperand(i)) {
2749 if (OpAtScope == UnknownValue) return UnknownValue;
2750 // Okay, at least one of these operands is loop variant but might be
2751 // foldable. Build a new instance of the folded commutative expression.
2752 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2753 NewOps.push_back(OpAtScope);
2754
2755 for (++i; i != e; ++i) {
2756 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2757 if (OpAtScope == UnknownValue) return UnknownValue;
2758 NewOps.push_back(OpAtScope);
2759 }
2760 if (isa<SCEVAddExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002761 return getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002762 if (isa<SCEVMulExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002763 return getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002764 if (isa<SCEVSMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002765 return getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002766 if (isa<SCEVUMaxExpr>(Comm))
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002767 return getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002768 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002769 }
2770 }
2771 // If we got here, all operands are loop invariant.
2772 return Comm;
2773 }
2774
Dan Gohmanc76b5452009-05-04 22:02:23 +00002775 if (const SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Nick Lewycky35b56022009-01-13 09:18:58 +00002776 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002777 if (LHS == UnknownValue) return LHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002778 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779 if (RHS == UnknownValue) return RHS;
Nick Lewycky35b56022009-01-13 09:18:58 +00002780 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2781 return Div; // must be loop invariant
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002782 return getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002783 }
2784
2785 // If this is a loop recurrence for a loop that does not contain L, then we
2786 // are dealing with the final value computed by the loop.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002787 if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2789 // To evaluate this recurrence, we need to know how many times the AddRec
2790 // loop iterates. Compute this now.
Dan Gohman76d5a0d2009-02-24 18:55:53 +00002791 SCEVHandle BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
2792 if (BackedgeTakenCount == UnknownValue) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002793
Eli Friedman7489ec92008-08-04 23:49:06 +00002794 // Then, evaluate the AddRec.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002795 return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002796 }
2797 return UnknownValue;
2798 }
2799
Dan Gohmanc76b5452009-05-04 22:02:23 +00002800 if (const SCEVZeroExtendExpr *Cast = dyn_cast<SCEVZeroExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002801 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2802 if (Op == UnknownValue) return Op;
2803 if (Op == Cast->getOperand())
2804 return Cast; // must be loop invariant
2805 return getZeroExtendExpr(Op, Cast->getType());
2806 }
2807
Dan Gohmanc76b5452009-05-04 22:02:23 +00002808 if (const SCEVSignExtendExpr *Cast = dyn_cast<SCEVSignExtendExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002809 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2810 if (Op == UnknownValue) return Op;
2811 if (Op == Cast->getOperand())
2812 return Cast; // must be loop invariant
2813 return getSignExtendExpr(Op, Cast->getType());
2814 }
2815
Dan Gohmanc76b5452009-05-04 22:02:23 +00002816 if (const SCEVTruncateExpr *Cast = dyn_cast<SCEVTruncateExpr>(V)) {
Dan Gohman78d63c82009-04-29 22:29:01 +00002817 SCEVHandle Op = getSCEVAtScope(Cast->getOperand(), L);
2818 if (Op == UnknownValue) return Op;
2819 if (Op == Cast->getOperand())
2820 return Cast; // must be loop invariant
2821 return getTruncateExpr(Op, Cast->getType());
2822 }
2823
2824 assert(0 && "Unknown SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002825}
2826
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002827/// getSCEVAtScope - Return a SCEV expression handle for the specified value
2828/// at the specified scope in the program. The L value specifies a loop
2829/// nest to evaluate the expression at, where null is the top-level or a
2830/// specified loop is immediately inside of the loop.
2831///
2832/// This method can be used to compute the exit value for a variable defined
2833/// in a loop by querying what the value will hold in the parent loop.
2834///
2835/// If this value is not computable at this scope, a SCEVCouldNotCompute
2836/// object is returned.
2837SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
2838 return getSCEVAtScope(getSCEV(V), L);
2839}
2840
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002841/// SolveLinEquationWithOverflow - Finds the minimum unsigned root of the
2842/// following equation:
2843///
2844/// A * X = B (mod N)
2845///
2846/// where N = 2^BW and BW is the common bit width of A and B. The signedness of
2847/// A and B isn't important.
2848///
2849/// If the equation does not have a solution, SCEVCouldNotCompute is returned.
2850static SCEVHandle SolveLinEquationWithOverflow(const APInt &A, const APInt &B,
2851 ScalarEvolution &SE) {
2852 uint32_t BW = A.getBitWidth();
2853 assert(BW == B.getBitWidth() && "Bit widths must be the same.");
2854 assert(A != 0 && "A must be non-zero.");
2855
2856 // 1. D = gcd(A, N)
2857 //
2858 // The gcd of A and N may have only one prime factor: 2. The number of
2859 // trailing zeros in A is its multiplicity
2860 uint32_t Mult2 = A.countTrailingZeros();
2861 // D = 2^Mult2
2862
2863 // 2. Check if B is divisible by D.
2864 //
2865 // B is divisible by D if and only if the multiplicity of prime factor 2 for B
2866 // is not less than multiplicity of this prime factor for D.
2867 if (B.countTrailingZeros() < Mult2)
Dan Gohman0ad08b02009-04-18 17:58:19 +00002868 return SE.getCouldNotCompute();
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002869
2870 // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
2871 // modulo (N / D).
2872 //
2873 // (N / D) may need BW+1 bits in its representation. Hence, we'll use this
2874 // bit width during computations.
2875 APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
2876 APInt Mod(BW + 1, 0);
2877 Mod.set(BW - Mult2); // Mod = N / D
2878 APInt I = AD.multiplicativeInverse(Mod);
2879
2880 // 4. Compute the minimum unsigned root of the equation:
2881 // I * (B / D) mod (N / D)
2882 APInt Result = (I * B.lshr(Mult2).zext(BW + 1)).urem(Mod);
2883
2884 // The result is guaranteed to be less than 2^BW so we may truncate it to BW
2885 // bits.
2886 return SE.getConstant(Result.trunc(BW));
2887}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888
2889/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2890/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2891/// might be the same) or two SCEVCouldNotCompute objects.
2892///
2893static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002894SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002895 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Dan Gohmanbff6b582009-05-04 22:30:44 +00002896 const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2897 const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2898 const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002899
2900 // We currently can only solve this if the coefficients are constants.
2901 if (!LC || !MC || !NC) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002902 const SCEV *CNC = SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002903 return std::make_pair(CNC, CNC);
2904 }
2905
2906 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2907 const APInt &L = LC->getValue()->getValue();
2908 const APInt &M = MC->getValue()->getValue();
2909 const APInt &N = NC->getValue()->getValue();
2910 APInt Two(BitWidth, 2);
2911 APInt Four(BitWidth, 4);
2912
2913 {
2914 using namespace APIntOps;
2915 const APInt& C = L;
2916 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2917 // The B coefficient is M-N/2
2918 APInt B(M);
2919 B -= sdiv(N,Two);
2920
2921 // The A coefficient is N/2
2922 APInt A(N.sdiv(Two));
2923
2924 // Compute the B^2-4ac term.
2925 APInt SqrtTerm(B);
2926 SqrtTerm *= B;
2927 SqrtTerm -= Four * (A * C);
2928
2929 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2930 // integer value or else APInt::sqrt() will assert.
2931 APInt SqrtVal(SqrtTerm.sqrt());
2932
2933 // Compute the two solutions for the quadratic formula.
2934 // The divisions must be performed as signed divisions.
2935 APInt NegB(-B);
2936 APInt TwoA( A << 1 );
Nick Lewycky35776692008-11-03 02:43:49 +00002937 if (TwoA.isMinValue()) {
Dan Gohmanbff6b582009-05-04 22:30:44 +00002938 const SCEV *CNC = SE.getCouldNotCompute();
Nick Lewycky35776692008-11-03 02:43:49 +00002939 return std::make_pair(CNC, CNC);
2940 }
2941
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002942 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2943 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2944
Dan Gohman89f85052007-10-22 18:31:58 +00002945 return std::make_pair(SE.getConstant(Solution1),
2946 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002947 } // end APIntOps namespace
2948}
2949
2950/// HowFarToZero - Return the number of times a backedge comparing the specified
2951/// value to zero will execute. If not computable, return UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00002952SCEVHandle ScalarEvolution::HowFarToZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002953 // If the value is a constant
Dan Gohmanc76b5452009-05-04 22:02:23 +00002954 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002955 // If the value is already zero, the branch will execute zero times.
2956 if (C->getValue()->isZero()) return C;
2957 return UnknownValue; // Otherwise it will loop infinitely.
2958 }
2959
Dan Gohmanbff6b582009-05-04 22:30:44 +00002960 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002961 if (!AddRec || AddRec->getLoop() != L)
2962 return UnknownValue;
2963
2964 if (AddRec->isAffine()) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002965 // If this is an affine expression, the execution count of this branch is
2966 // the minimum unsigned root of the following equation:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002968 // Start + Step*N = 0 (mod 2^BW)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 //
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002970 // equivalent to:
2971 //
2972 // Step*N = -Start (mod 2^BW)
2973 //
2974 // where BW is the common bit width of Start and Step.
2975
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976 // Get the initial value for the loop.
2977 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2978 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002979
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002980 SCEVHandle Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002981
Dan Gohmanc76b5452009-05-04 22:02:23 +00002982 if (const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002983 // For now we handle only constant steps.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002984
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002985 // First, handle unitary steps.
2986 if (StepC->getValue()->equalsInt(1)) // 1*N = -Start (mod 2^BW), so:
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002987 return getNegativeSCEV(Start); // N = -Start (as unsigned)
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002988 if (StepC->getValue()->isAllOnesValue()) // -1*N = -Start (mod 2^BW), so:
2989 return Start; // N = Start (as unsigned)
2990
2991 // Then, try to solve the above equation provided that Start is constant.
Dan Gohmanc76b5452009-05-04 22:02:23 +00002992 if (const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start))
Wojciech Matyjewicz961b34c2008-07-20 15:55:14 +00002993 return SolveLinEquationWithOverflow(StepC->getValue()->getValue(),
Dan Gohmanffd36ba2009-04-21 23:15:49 +00002994 -StartC->getValue()->getValue(),
2995 *this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002996 }
2997 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2998 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2999 // the quadratic equation to solve it.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003000 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec,
3001 *this);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003002 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3003 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003004 if (R1) {
3005#if 0
Dan Gohman13058cc2009-04-21 00:47:46 +00003006 errs() << "HFTZ: " << *V << " - sol#1: " << *R1
3007 << " sol#2: " << *R2 << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003008#endif
3009 // Pick the smallest positive root value.
3010 if (ConstantInt *CB =
3011 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3012 R1->getValue(), R2->getValue()))) {
3013 if (CB->getZExtValue() == false)
3014 std::swap(R1, R2); // R1 is the minimum root now.
3015
3016 // We can only use this value if the chrec ends up with an exact zero
3017 // value at this index. When solving for "X*X != 5", for example, we
3018 // should not accept a root of 2.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003019 SCEVHandle Val = AddRec->evaluateAtIteration(R1, *this);
Dan Gohman7b560c42008-06-18 16:23:07 +00003020 if (Val->isZero())
3021 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022 }
3023 }
3024 }
3025
3026 return UnknownValue;
3027}
3028
3029/// HowFarToNonZero - Return the number of times a backedge checking the
3030/// specified value for nonzero will execute. If not computable, return
3031/// UnknownValue
Dan Gohmanbff6b582009-05-04 22:30:44 +00003032SCEVHandle ScalarEvolution::HowFarToNonZero(const SCEV *V, const Loop *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003033 // Loops that look like: while (X == 0) are very strange indeed. We don't
3034 // handle them yet except for the trivial case. This could be expanded in the
3035 // future as needed.
3036
3037 // If the value is a constant, check to see if it is known to be non-zero
3038 // already. If so, the backedge will execute zero times.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003039 if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00003040 if (!C->getValue()->isNullValue())
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003041 return getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003042 return UnknownValue; // Otherwise it will loop infinitely.
3043 }
3044
3045 // We could implement others, but I really doubt anyone writes loops like
3046 // this, and if they did, they would already be constant folded.
3047 return UnknownValue;
3048}
3049
Dan Gohman1cddf972008-09-15 22:18:04 +00003050/// getPredecessorWithUniqueSuccessorForBB - Return a predecessor of BB
3051/// (which may not be an immediate predecessor) which has exactly one
3052/// successor from which BB is reachable, or null if no such block is
3053/// found.
3054///
3055BasicBlock *
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003056ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(BasicBlock *BB) {
Dan Gohman1116ea72009-04-30 20:48:53 +00003057 // If the block has a unique predecessor, then there is no path from the
3058 // predecessor to the block that does not go through the direct edge
3059 // from the predecessor to the block.
Dan Gohman1cddf972008-09-15 22:18:04 +00003060 if (BasicBlock *Pred = BB->getSinglePredecessor())
3061 return Pred;
3062
3063 // A loop's header is defined to be a block that dominates the loop.
3064 // If the loop has a preheader, it must be a block that has exactly
3065 // one successor that can reach BB. This is slightly more strict
3066 // than necessary, but works if critical edges are split.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003067 if (Loop *L = LI->getLoopFor(BB))
Dan Gohman1cddf972008-09-15 22:18:04 +00003068 return L->getLoopPreheader();
3069
3070 return 0;
3071}
3072
Dan Gohmancacd2012009-02-12 22:19:27 +00003073/// isLoopGuardedByCond - Test whether entry to the loop is protected by
Dan Gohman1116ea72009-04-30 20:48:53 +00003074/// a conditional between LHS and RHS. This is used to help avoid max
3075/// expressions in loop trip counts.
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003076bool ScalarEvolution::isLoopGuardedByCond(const Loop *L,
Dan Gohman1116ea72009-04-30 20:48:53 +00003077 ICmpInst::Predicate Pred,
Dan Gohmanbff6b582009-05-04 22:30:44 +00003078 const SCEV *LHS, const SCEV *RHS) {
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003079 BasicBlock *Preheader = L->getLoopPreheader();
3080 BasicBlock *PreheaderDest = L->getHeader();
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003081
Dan Gohmanab678fb2008-08-12 20:17:31 +00003082 // Starting at the preheader, climb up the predecessor chain, as long as
Dan Gohman1cddf972008-09-15 22:18:04 +00003083 // there are predecessors that can be found that have unique successors
3084 // leading to the original header.
3085 for (; Preheader;
3086 PreheaderDest = Preheader,
3087 Preheader = getPredecessorWithUniqueSuccessorForBB(Preheader)) {
Dan Gohmanab678fb2008-08-12 20:17:31 +00003088
3089 BranchInst *LoopEntryPredicate =
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003090 dyn_cast<BranchInst>(Preheader->getTerminator());
Dan Gohmanab678fb2008-08-12 20:17:31 +00003091 if (!LoopEntryPredicate ||
3092 LoopEntryPredicate->isUnconditional())
3093 continue;
3094
3095 ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition());
3096 if (!ICI) continue;
3097
3098 // Now that we found a conditional branch that dominates the loop, check to
3099 // see if it is the comparison we are looking for.
3100 Value *PreCondLHS = ICI->getOperand(0);
3101 Value *PreCondRHS = ICI->getOperand(1);
3102 ICmpInst::Predicate Cond;
3103 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
3104 Cond = ICI->getPredicate();
3105 else
3106 Cond = ICI->getInversePredicate();
3107
Dan Gohmancacd2012009-02-12 22:19:27 +00003108 if (Cond == Pred)
3109 ; // An exact match.
3110 else if (!ICmpInst::isTrueWhenEqual(Cond) && Pred == ICmpInst::ICMP_NE)
3111 ; // The actual condition is beyond sufficient.
3112 else
3113 // Check a few special cases.
3114 switch (Cond) {
3115 case ICmpInst::ICMP_UGT:
3116 if (Pred == ICmpInst::ICMP_ULT) {
3117 std::swap(PreCondLHS, PreCondRHS);
3118 Cond = ICmpInst::ICMP_ULT;
3119 break;
3120 }
3121 continue;
3122 case ICmpInst::ICMP_SGT:
3123 if (Pred == ICmpInst::ICMP_SLT) {
3124 std::swap(PreCondLHS, PreCondRHS);
3125 Cond = ICmpInst::ICMP_SLT;
3126 break;
3127 }
3128 continue;
3129 case ICmpInst::ICMP_NE:
3130 // Expressions like (x >u 0) are often canonicalized to (x != 0),
3131 // so check for this case by checking if the NE is comparing against
3132 // a minimum or maximum constant.
3133 if (!ICmpInst::isTrueWhenEqual(Pred))
3134 if (ConstantInt *CI = dyn_cast<ConstantInt>(PreCondRHS)) {
3135 const APInt &A = CI->getValue();
3136 switch (Pred) {
3137 case ICmpInst::ICMP_SLT:
3138 if (A.isMaxSignedValue()) break;
3139 continue;
3140 case ICmpInst::ICMP_SGT:
3141 if (A.isMinSignedValue()) break;
3142 continue;
3143 case ICmpInst::ICMP_ULT:
3144 if (A.isMaxValue()) break;
3145 continue;
3146 case ICmpInst::ICMP_UGT:
3147 if (A.isMinValue()) break;
3148 continue;
3149 default:
3150 continue;
3151 }
3152 Cond = ICmpInst::ICMP_NE;
3153 // NE is symmetric but the original comparison may not be. Swap
3154 // the operands if necessary so that they match below.
3155 if (isa<SCEVConstant>(LHS))
3156 std::swap(PreCondLHS, PreCondRHS);
3157 break;
3158 }
3159 continue;
3160 default:
3161 // We weren't able to reconcile the condition.
3162 continue;
3163 }
Dan Gohmanab678fb2008-08-12 20:17:31 +00003164
3165 if (!PreCondLHS->getType()->isInteger()) continue;
3166
3167 SCEVHandle PreCondLHSSCEV = getSCEV(PreCondLHS);
3168 SCEVHandle PreCondRHSSCEV = getSCEV(PreCondRHS);
3169 if ((LHS == PreCondLHSSCEV && RHS == PreCondRHSSCEV) ||
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003170 (LHS == getNotSCEV(PreCondRHSSCEV) &&
3171 RHS == getNotSCEV(PreCondLHSSCEV)))
Dan Gohmanab678fb2008-08-12 20:17:31 +00003172 return true;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003173 }
3174
Dan Gohmanab678fb2008-08-12 20:17:31 +00003175 return false;
Nick Lewycky1b020bf2008-07-12 07:41:32 +00003176}
3177
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003178/// HowManyLessThans - Return the number of times a backedge containing the
3179/// specified less-than comparison will execute. If not computable, return
3180/// UnknownValue.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003181ScalarEvolution::BackedgeTakenInfo ScalarEvolution::
Dan Gohmanbff6b582009-05-04 22:30:44 +00003182HowManyLessThans(const SCEV *LHS, const SCEV *RHS,
3183 const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003184 // Only handle: "ADDREC < LoopInvariant".
3185 if (!RHS->isLoopInvariant(L)) return UnknownValue;
3186
Dan Gohmanbff6b582009-05-04 22:30:44 +00003187 const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 if (!AddRec || AddRec->getLoop() != L)
3189 return UnknownValue;
3190
3191 if (AddRec->isAffine()) {
Nick Lewycky35b56022009-01-13 09:18:58 +00003192 // FORNOW: We only support unit strides.
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003193 unsigned BitWidth = getTypeSizeInBits(AddRec->getType());
3194 SCEVHandle Step = AddRec->getStepRecurrence(*this);
3195 SCEVHandle NegOne = getIntegerSCEV(-1, AddRec->getType());
3196
3197 // TODO: handle non-constant strides.
3198 const SCEVConstant *CStep = dyn_cast<SCEVConstant>(Step);
3199 if (!CStep || CStep->isZero())
3200 return UnknownValue;
3201 if (CStep->getValue()->getValue() == 1) {
3202 // With unit stride, the iteration never steps past the limit value.
3203 } else if (CStep->getValue()->getValue().isStrictlyPositive()) {
3204 if (const SCEVConstant *CLimit = dyn_cast<SCEVConstant>(RHS)) {
3205 // Test whether a positive iteration iteration can step past the limit
3206 // value and past the maximum value for its type in a single step.
3207 if (isSigned) {
3208 APInt Max = APInt::getSignedMaxValue(BitWidth);
3209 if ((Max - CStep->getValue()->getValue())
3210 .slt(CLimit->getValue()->getValue()))
3211 return UnknownValue;
3212 } else {
3213 APInt Max = APInt::getMaxValue(BitWidth);
3214 if ((Max - CStep->getValue()->getValue())
3215 .ult(CLimit->getValue()->getValue()))
3216 return UnknownValue;
3217 }
3218 } else
3219 // TODO: handle non-constant limit values below.
3220 return UnknownValue;
3221 } else
3222 // TODO: handle negative strides below.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003223 return UnknownValue;
3224
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003225 // We know the LHS is of the form {n,+,s} and the RHS is some loop-invariant
3226 // m. So, we count the number of iterations in which {n,+,s} < m is true.
3227 // Note that we cannot simply return max(m-n,0)/s because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00003228 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003229
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003230 // First, we get the value of the LHS in the first iteration: n
3231 SCEVHandle Start = AddRec->getOperand(0);
3232
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003233 // Determine the minimum constant start value.
3234 SCEVHandle MinStart = isa<SCEVConstant>(Start) ? Start :
3235 getConstant(isSigned ? APInt::getSignedMinValue(BitWidth) :
3236 APInt::getMinValue(BitWidth));
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00003237
Dan Gohmanf7d3d25542009-04-30 20:47:05 +00003238 // If we know that the condition is true in order to enter the loop,
3239 // then we know that it will run exactly (m-n)/s times. Otherwise, we
3240 // only know if will execute (max(m,n)-n)/s times. In both cases, the
3241 // division must round up.
3242 SCEVHandle End = RHS;
3243 if (!isLoopGuardedByCond(L,
3244 isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
3245 getMinusSCEV(Start, Step), RHS))
3246 End = isSigned ? getSMaxExpr(RHS, Start)
3247 : getUMaxExpr(RHS, Start);
3248
3249 // Determine the maximum constant end value.
3250 SCEVHandle MaxEnd = isa<SCEVConstant>(End) ? End :
3251 getConstant(isSigned ? APInt::getSignedMaxValue(BitWidth) :
3252 APInt::getMaxValue(BitWidth));
3253
3254 // Finally, we subtract these two values and divide, rounding up, to get
3255 // the number of times the backedge is executed.
3256 SCEVHandle BECount = getUDivExpr(getAddExpr(getMinusSCEV(End, Start),
3257 getAddExpr(Step, NegOne)),
3258 Step);
3259
3260 // The maximum backedge count is similar, except using the minimum start
3261 // value and the maximum end value.
3262 SCEVHandle MaxBECount = getUDivExpr(getAddExpr(getMinusSCEV(MaxEnd,
3263 MinStart),
3264 getAddExpr(Step, NegOne)),
3265 Step);
3266
3267 return BackedgeTakenInfo(BECount, MaxBECount);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003268 }
3269
3270 return UnknownValue;
3271}
3272
3273/// getNumIterationsInRange - Return the number of iterations of this loop that
3274/// produce values in the specified constant range. Another way of looking at
3275/// this is that it returns the first iteration number where the value is not in
3276/// the condition, thus computing the exit count. If the iteration count can't
3277/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00003278SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
3279 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003280 if (Range.isFullSet()) // Infinite loop.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003281 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003282
3283 // If the start is a non-zero constant, shift the range to simplify things.
Dan Gohmanc76b5452009-05-04 22:02:23 +00003284 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003285 if (!SC->getValue()->isZero()) {
3286 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003287 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
3288 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanc76b5452009-05-04 22:02:23 +00003289 if (const SCEVAddRecExpr *ShiftedAddRec =
3290 dyn_cast<SCEVAddRecExpr>(Shifted))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003291 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00003292 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003293 // This is strange and shouldn't happen.
Dan Gohman0ad08b02009-04-18 17:58:19 +00003294 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003295 }
3296
3297 // The only time we can solve this is when we have all constant indices.
3298 // Otherwise, we cannot determine the overflow conditions.
3299 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
3300 if (!isa<SCEVConstant>(getOperand(i)))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003301 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003302
3303
3304 // Okay at this point we know that all elements of the chrec are constants and
3305 // that the start element is zero.
3306
3307 // First check to see if the range contains zero. If not, the first
3308 // iteration exits.
Dan Gohmanb98c1a32009-04-21 01:07:12 +00003309 unsigned BitWidth = SE.getTypeSizeInBits(getType());
Dan Gohman01c2ee72009-04-16 03:18:22 +00003310 if (!Range.contains(APInt(BitWidth, 0)))
Dan Gohman89f85052007-10-22 18:31:58 +00003311 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003312
3313 if (isAffine()) {
3314 // If this is an affine expression then we have this situation:
3315 // Solve {0,+,A} in Range === Ax in Range
3316
3317 // We know that zero is in the range. If A is positive then we know that
3318 // the upper value of the range must be the first possible exit value.
3319 // If A is negative then the lower of the range is the last possible loop
3320 // value. Also note that we already checked for a full range.
Dan Gohman01c2ee72009-04-16 03:18:22 +00003321 APInt One(BitWidth,1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003322 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
3323 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
3324
3325 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00003326 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003327 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
3328
3329 // Evaluate at the exit value. If we really did fall out of the valid
3330 // range, then we computed our trip count, otherwise wrap around or other
3331 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00003332 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003333 if (Range.contains(Val->getValue()))
Dan Gohman0ad08b02009-04-18 17:58:19 +00003334 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003335
3336 // Ensure that the previous value is in the range. This is a sanity check.
3337 assert(Range.contains(
3338 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003339 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003340 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00003341 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003342 } else if (isQuadratic()) {
3343 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
3344 // quadratic equation to solve it. To do this, we must frame our problem in
3345 // terms of figuring out when zero is crossed, instead of when
3346 // Range.getUpper() is crossed.
3347 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00003348 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
3349 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003350
3351 // Next, solve the constructed addrec
3352 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00003353 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanbff6b582009-05-04 22:30:44 +00003354 const SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
3355 const SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003356 if (R1) {
3357 // Pick the smallest positive root value.
3358 if (ConstantInt *CB =
3359 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
3360 R1->getValue(), R2->getValue()))) {
3361 if (CB->getZExtValue() == false)
3362 std::swap(R1, R2); // R1 is the minimum root now.
3363
3364 // Make sure the root is not off by one. The returned iteration should
3365 // not be in the range, but the previous one should be. When solving
3366 // for "X*X < 5", for example, we should not return a root of 2.
3367 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00003368 R1->getValue(),
3369 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003370 if (Range.contains(R1Val->getValue())) {
3371 // The next iteration must be out of the range...
3372 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
3373
Dan Gohman89f85052007-10-22 18:31:58 +00003374 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003375 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00003376 return SE.getConstant(NextVal);
Dan Gohman0ad08b02009-04-18 17:58:19 +00003377 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003378 }
3379
3380 // If R1 was not in the range, then it is a good return value. Make
3381 // sure that R1-1 WAS in the range though, just in case.
3382 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00003383 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003384 if (Range.contains(R1Val->getValue()))
3385 return R1;
Dan Gohman0ad08b02009-04-18 17:58:19 +00003386 return SE.getCouldNotCompute(); // Something strange happened
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003387 }
3388 }
3389 }
3390
Dan Gohman0ad08b02009-04-18 17:58:19 +00003391 return SE.getCouldNotCompute();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003392}
3393
3394
3395
3396//===----------------------------------------------------------------------===//
Dan Gohmanbff6b582009-05-04 22:30:44 +00003397// SCEVCallbackVH Class Implementation
3398//===----------------------------------------------------------------------===//
3399
3400void SCEVCallbackVH::deleted() {
3401 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3402 if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
3403 SE->ConstantEvolutionLoopExitValue.erase(PN);
3404 SE->Scalars.erase(getValPtr());
3405 // this now dangles!
3406}
3407
3408void SCEVCallbackVH::allUsesReplacedWith(Value *) {
3409 assert(SE && "SCEVCallbackVH called with a non-null ScalarEvolution!");
3410
3411 // Forget all the expressions associated with users of the old value,
3412 // so that future queries will recompute the expressions using the new
3413 // value.
3414 SmallVector<User *, 16> Worklist;
3415 Value *Old = getValPtr();
3416 bool DeleteOld = false;
3417 for (Value::use_iterator UI = Old->use_begin(), UE = Old->use_end();
3418 UI != UE; ++UI)
3419 Worklist.push_back(*UI);
3420 while (!Worklist.empty()) {
3421 User *U = Worklist.pop_back_val();
3422 // Deleting the Old value will cause this to dangle. Postpone
3423 // that until everything else is done.
3424 if (U == Old) {
3425 DeleteOld = true;
3426 continue;
3427 }
3428 if (PHINode *PN = dyn_cast<PHINode>(U))
3429 SE->ConstantEvolutionLoopExitValue.erase(PN);
3430 if (SE->Scalars.erase(U))
3431 for (Value::use_iterator UI = U->use_begin(), UE = U->use_end();
3432 UI != UE; ++UI)
3433 Worklist.push_back(*UI);
3434 }
3435 if (DeleteOld) {
3436 if (PHINode *PN = dyn_cast<PHINode>(Old))
3437 SE->ConstantEvolutionLoopExitValue.erase(PN);
3438 SE->Scalars.erase(Old);
3439 // this now dangles!
3440 }
3441 // this may dangle!
3442}
3443
3444SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
3445 : CallbackVH(V), SE(se) {}
3446
3447//===----------------------------------------------------------------------===//
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003448// ScalarEvolution Class Implementation
3449//===----------------------------------------------------------------------===//
3450
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003451ScalarEvolution::ScalarEvolution()
3452 : FunctionPass(&ID), UnknownValue(new SCEVCouldNotCompute()) {
3453}
3454
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003456 this->F = &F;
3457 LI = &getAnalysis<LoopInfo>();
3458 TD = getAnalysisIfAvailable<TargetData>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003459 return false;
3460}
3461
3462void ScalarEvolution::releaseMemory() {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003463 Scalars.clear();
3464 BackedgeTakenCounts.clear();
3465 ConstantEvolutionLoopExitValue.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003466}
3467
3468void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
3469 AU.setPreservesAll();
3470 AU.addRequiredTransitive<LoopInfo>();
Dan Gohman01c2ee72009-04-16 03:18:22 +00003471}
3472
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003473bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003474 return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003475}
3476
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003477static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478 const Loop *L) {
3479 // Print all inner loops first
3480 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
3481 PrintLoopInfo(OS, SE, *I);
3482
Nick Lewyckye5da1912008-01-02 02:49:20 +00003483 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003484
Devang Patel02451fa2007-08-21 00:31:24 +00003485 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003486 L->getExitBlocks(ExitBlocks);
3487 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00003488 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003489
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003490 if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
3491 OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003492 } else {
Dan Gohman76d5a0d2009-02-24 18:55:53 +00003493 OS << "Unpredictable backedge-taken count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003494 }
3495
Nick Lewyckye5da1912008-01-02 02:49:20 +00003496 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003497}
3498
Dan Gohman13058cc2009-04-21 00:47:46 +00003499void ScalarEvolution::print(raw_ostream &OS, const Module* ) const {
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003500 // ScalarEvolution's implementaiton of the print method is to print
3501 // out SCEV values of all instructions that are interesting. Doing
3502 // this potentially causes it to create new SCEV objects though,
3503 // which technically conflicts with the const qualifier. This isn't
3504 // observable from outside the class though (the hasSCEV function
3505 // notwithstanding), so casting away the const isn't dangerous.
3506 ScalarEvolution &SE = *const_cast<ScalarEvolution*>(this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003508 OS << "Classifying expressions for: " << F->getName() << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003509 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Dan Gohman43d37e92009-04-30 01:30:18 +00003510 if (isSCEVable(I->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003511 OS << *I;
Dan Gohmanabe991f2008-09-14 17:21:12 +00003512 OS << " --> ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003513 SCEVHandle SV = SE.getSCEV(&*I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514 SV->print(OS);
3515 OS << "\t\t";
3516
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003517 if (const Loop *L = LI->getLoopFor((*I).getParent())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 OS << "Exits: ";
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003519 SCEVHandle ExitValue = SE.getSCEVAtScope(&*I, L->getParentLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003520 if (isa<SCEVCouldNotCompute>(ExitValue)) {
3521 OS << "<<Unknown>>";
3522 } else {
3523 OS << *ExitValue;
3524 }
3525 }
3526
3527
3528 OS << "\n";
3529 }
3530
Dan Gohmanffd36ba2009-04-21 23:15:49 +00003531 OS << "Determining loop execution counts for: " << F->getName() << "\n";
3532 for (LoopInfo::iterator I = LI->begin(), E = LI->end(); I != E; ++I)
3533 PrintLoopInfo(OS, &SE, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003534}
Dan Gohman13058cc2009-04-21 00:47:46 +00003535
3536void ScalarEvolution::print(std::ostream &o, const Module *M) const {
3537 raw_os_ostream OS(o);
3538 print(OS, M);
3539}